فهرست منبع

Add ability to email PDFs

Alan Lam 3 سال پیش
والد
کامیت
da60e455f6
8فایلهای تغییر یافته به همراه261 افزوده شده و 36 حذف شده
  1. 2 1
      composer.json
  2. 83 2
      composer.lock
  3. 69 18
      controllers/document.php
  4. 28 0
      engine/Document.php
  5. 14 0
      public/js/document-page.js
  6. 2 2
      routes/default.php
  7. 26 0
      templates/email/document.html
  8. 37 13
      views/document.php

+ 2 - 1
composer.json

@@ -28,7 +28,8 @@
         "paragonie/anti-csrf": "^2.3",
         "robmorgan/phinx": "^0.12.10",
         "vlucas/phpdotenv": "^5.4",
-		"ext-bcmath": "*"
+		"ext-bcmath": "*",
+        "phpmailer/phpmailer": "^6.7"
 	},
 	"require-dev": {
 		"roave/security-advisories": "dev-latest"

+ 83 - 2
composer.lock

@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "e0800ed0a0c20006a21217617050785c",
+    "content-hash": "6ca30ffdfaa2756167d8b62fc9810f84",
     "packages": [
         {
             "name": "cakephp/core",
@@ -737,6 +737,86 @@
             },
             "time": "2022-06-14T06:56:20+00:00"
         },
+        {
+            "name": "phpmailer/phpmailer",
+            "version": "v6.7.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/PHPMailer/PHPMailer.git",
+                "reference": "49cd7ea3d2563f028d7811f06864a53b1f15ff55"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/49cd7ea3d2563f028d7811f06864a53b1f15ff55",
+                "reference": "49cd7ea3d2563f028d7811f06864a53b1f15ff55",
+                "shasum": ""
+            },
+            "require": {
+                "ext-ctype": "*",
+                "ext-filter": "*",
+                "ext-hash": "*",
+                "php": ">=5.5.0"
+            },
+            "require-dev": {
+                "dealerdirect/phpcodesniffer-composer-installer": "^0.7.2",
+                "doctrine/annotations": "^1.2.6 || ^1.13.3",
+                "php-parallel-lint/php-console-highlighter": "^1.0.0",
+                "php-parallel-lint/php-parallel-lint": "^1.3.2",
+                "phpcompatibility/php-compatibility": "^9.3.5",
+                "roave/security-advisories": "dev-latest",
+                "squizlabs/php_codesniffer": "^3.7.1",
+                "yoast/phpunit-polyfills": "^1.0.4"
+            },
+            "suggest": {
+                "ext-mbstring": "Needed to send email in multibyte encoding charset or decode encoded addresses",
+                "ext-openssl": "Needed for secure SMTP sending and DKIM signing",
+                "greew/oauth2-azure-provider": "Needed for Microsoft Azure XOAUTH2 authentication",
+                "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication",
+                "league/oauth2-google": "Needed for Google XOAUTH2 authentication",
+                "psr/log": "For optional PSR-3 debug logging",
+                "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)",
+                "thenetworg/oauth2-azure": "Needed for Microsoft XOAUTH2 authentication"
+            },
+            "type": "library",
+            "autoload": {
+                "psr-4": {
+                    "PHPMailer\\PHPMailer\\": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "LGPL-2.1-only"
+            ],
+            "authors": [
+                {
+                    "name": "Marcus Bointon",
+                    "email": "phpmailer@synchromedia.co.uk"
+                },
+                {
+                    "name": "Jim Jagielski",
+                    "email": "jimjag@gmail.com"
+                },
+                {
+                    "name": "Andy Prevost",
+                    "email": "codeworxtech@users.sourceforge.net"
+                },
+                {
+                    "name": "Brent R. Matzelle"
+                }
+            ],
+            "description": "PHPMailer is a full-featured email creation and transfer class for PHP",
+            "support": {
+                "issues": "https://github.com/PHPMailer/PHPMailer/issues",
+                "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.7.1"
+            },
+            "funding": [
+                {
+                    "url": "https://github.com/Synchro",
+                    "type": "github"
+                }
+            ],
+            "time": "2022-12-08T13:30:06+00:00"
+        },
         {
             "name": "phpoption/phpoption",
             "version": "1.8.1",
@@ -2851,7 +2931,8 @@
         "ext-intl": "*",
         "ext-json": "*",
         "ext-curl": "*",
-        "ext-simplexml": "*"
+        "ext-simplexml": "*",
+        "ext-bcmath": "*"
     },
     "platform-dev": [],
     "plugin-api-version": "2.2.0"

+ 69 - 18
controllers/document.php

@@ -3,6 +3,8 @@
 namespace App;
 
 use App\Enums\DocumentTypes;
+use Exception;
+use PHPMailer\PHPMailer\PHPMailer;
 use RuntimeException;
 
 /**
@@ -413,24 +415,7 @@ $controller = new class($document_type, $document_number) {
 		$document = $this->requireDocument();
 		$variant = $this->request->string("variant");
 
-		$host = $_SERVER["HTTP_HOST"];
-
-		$render_url = "https://" . $host .  $document->getUrl() . "/render-pdf?" . http_build_query([
-			"access_token" => $document->getAccessToken(),
-			"variant" => $variant
-		]);
-
-		chdir($_ENV["DIR_ROOT"]);
-
-		$output_filename = $document->id . ".pdf";
-		$output_path = "pdf-output/" . $output_filename;
-
-		$command = sprintf('node pdf.js "%s" "%s"',
-			$render_url,
-			$output_filename
-		);
-
-		shell_exec($command);
+		$output_path = $document->generatePdf($variant);
 
 		if(file_exists($output_path)) {
 			Http::downloadFile($output_path, $document->getPdfFilename(), "application/pdf");
@@ -444,6 +429,68 @@ $controller = new class($document_type, $document_number) {
 		exit();
 	}
 
+	public function emailPdf(): void {
+
+		$document = $this->requireDocument();
+
+		try {
+			if(!$document->contact_email) {
+				throw new RuntimeException(__("Contact Email must be set."));
+			}
+			if(!$document->contact_name) {
+				throw new RuntimeException(__("Contact Name must be set."));
+			}
+
+			$company = $document->getCompany();
+			if(!$company) {
+				throw new RuntimeException(__("Company must be set."));
+			}
+
+			$variant = $this->request->string("variant");
+
+			$pdf_path = $document->generatePdf($variant);
+			if(!file_exists($pdf_path)) {
+				throw new RuntimeException(__("Failed to generate PDF."));
+			}
+
+			$title = $document->getTitle();
+
+			if($document->isSalesOrder()) {
+				if($variant === "commercial") {
+					$title = __("Commercial Invoice %d", $document->number);
+				}
+				else {
+					$title = __("Proforma Invoice %d", $document->number);
+				}
+			}
+
+			$body = file_get_contents("templates/email/document.html");
+			$search_replace = [
+				"%contact-name%" => $document->contact_name,
+				"%document-title%" => $title,
+				"%company-name%" => $company->name
+			];
+			$body = str_replace(array_keys($search_replace), array_values($search_replace), $body);
+
+			$mailer = new PHPMailer(true);
+			$mailer->setFrom("no-reply@electrocoin.com", $company->name);
+			$mailer->addAddress($document->contact_email, $document->contact_name);
+			$mailer->CharSet = PHPMailer::CHARSET_UTF8;
+			$mailer->Subject = $title;
+			$mailer->Body = $body;
+			$mailer->AltBody = strip_tags($body);
+			$mailer->addAttachment($pdf_path, $title . ".pdf");
+
+			$mailer->send();
+
+			JSON::success();
+		}
+		catch(Exception $e) {
+			JSON::fail($e->getMessage());
+		}
+
+	}
+
 };
 
 switch($action) {
@@ -498,6 +545,10 @@ switch($action) {
 		$controller->downloadPdf();
 		break;
 
+	case "email-pdf":
+		$controller->emailPdf();
+		break;
+
 	default:
 		$controller->view();
 }

+ 28 - 0
engine/Document.php

@@ -367,4 +367,32 @@ class Document extends Model {
 		]);
 	}
 
+	/**
+	 * @param string|null $variant
+	 * @return string
+	 * @throws Exception
+	 */
+	public function generatePdf(?string $variant): string {
+		$host = $_SERVER["HTTP_HOST"];
+
+		$render_url = "https://" . $host .  $this->getUrl() . "/render-pdf?" . http_build_query([
+				"access_token" => $this->getAccessToken(),
+				"variant" => $variant
+			]);
+
+		chdir($_ENV["DIR_ROOT"]);
+
+		$output_filename = $this->id . ".pdf";
+		$output_path = "pdf-output/" . $output_filename;
+
+		$command = sprintf('node pdf.js "%s" "%s"',
+			$render_url,
+			$output_filename
+		);
+
+		shell_exec($command);
+
+		return $output_path;
+	}
+
 }

+ 14 - 0
public/js/document-page.js

@@ -47,6 +47,20 @@ class DocumentPage {
 				window.open($element.attr("href"));
 			});
 		});
+
+		const $emailActions = $(".email-pdf-action");
+		$emailActions.on("click", event => {
+			const $element = $(event.currentTarget);
+			const { variant } = $element.data();
+
+			DocumentPage.SaveForm().then(() => {
+				$.post(window.location + "/email-pdf", {
+					variant: variant
+				}).then(() => {
+					toastr.success("Email sent successfully.");
+				});
+			});
+		});
 	}
 
 	static SaveForm() {

+ 2 - 2
routes/default.php

@@ -57,7 +57,7 @@ $this->addRoute("/^leads\/(\d+)$/", "sale", ["number"], ["requireUser" => true])
 $this->addRoute("/^leads\/(\d+)\/(submit|submit-note|delete-note|submit-item|delete-item|items-batch-action)$/", "sale", ["number", "action"], ["requireUser" => true]);
 
 $this->addRoute("/^(?:leads|arus)\/\d+\/(sales-orders|delivery-notes)\/(\d+)$/", "document", ["document_type_string", "document_number"], ["requireUser" => true]);
-$this->addRoute("/^(?:leads|arus)\/\d+\/(sales-orders|delivery-notes)\/(\d+)\/(submit|submit-item|delete-item|items-batch-action|download-pdf)$/", "document", ["document_type_string", "document_number", "action"], ["requireUser" => true]);
+$this->addRoute("/^(?:leads|arus)\/\d+\/(sales-orders|delivery-notes)\/(\d+)\/(submit|submit-item|delete-item|items-batch-action|download-pdf|email-pdf)$/", "document", ["document_type_string", "document_number", "action"], ["requireUser" => true]);
 $this->addRoute("/^(?:leads|arus)\/\d+\/(sales-orders|delivery-notes)\/(\d+)\/(render-pdf)$/", "document", ["document_type_string", "document_number", "action"]);
 
 $this->addRoute("/^tickets$/", "tickets", [], ["requireUser" => true]);
@@ -69,7 +69,7 @@ $this->addRoute("/^(goods-in|arus)\/(create)$/", "document", ["document_type_str
 $this->addRoute("/^(goods-in|arus|sales-orders|delivery-notes)$/", "documents", ["type_string"], ["requireUser" => true]);
 
 $this->addRoute("/^(goods-in|arus)\/(\d+)$/", "document", ["document_type_string", "document_number"], ["requireUser" => true]);
-$this->addRoute("/^(goods-in|arus)\/(\d+)\/(submit|submit-item|delete-item|items-batch-action|download-pdf)$/", "document", ["document_type_string", "document_number", "action"], ["requireUser" => true]);
+$this->addRoute("/^(goods-in|arus)\/(\d+)\/(submit|submit-item|delete-item|items-batch-action|download-pdf|email-pdf)$/", "document", ["document_type_string", "document_number", "action"], ["requireUser" => true]);
 $this->addRoute("/^(goods-in|arus)\/(\d+)\/(render-pdf)$/", "document", ["document_type_string", "document_number", "action"]);
 
 $this->addRoute("/^download-file\/(ticket-comment-attachment)\/(\d+)$/", "download_file", ["type", "id"], ["requireUser" => true]);

+ 26 - 0
templates/email/document.html

@@ -0,0 +1,26 @@
+<!doctype html>
+<html lang="en">
+<head>
+	<meta charset="UTF-8">
+	<meta name="viewport"
+		  content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
+	<meta http-equiv="X-UA-Compatible" content="ie=edge">
+	<title>Document</title>
+	<style>
+		body {
+			font-family: sans-serif;
+		}
+	</style>
+</head>
+<body>
+	<p>
+		Dear %contact-name%,
+	</p>
+	<p>
+		Please find attached: %document-title%
+	</p>
+	<p>
+		%company-name%
+	</p>
+</body>
+</html>

+ 37 - 13
views/document.php

@@ -390,23 +390,47 @@ $location = $document->getLocation();
 		<?php
 		if($document->isSalesOrder()) {
 			?>
-			<a class="btn btn-primary pdf-action" href="<?=htmlspecialchars($document->getDownloadPdfUrl())?>" target="_blank" class="dropdown-item pdf-action">
-				<i class="fa fa-fw fa-file-invoice"></i>
-				<?=htmlspecialchars(__("Proforma Invoice PDF"))?>
-			</a>
-
-			<a class="btn btn-primary pdf-action" href="<?=htmlspecialchars($document->getDownloadPdfUrl("commercial"))?>" target="_blank" class="dropdown-item pdf-action">
-				<i class="fa fa-fw fa-file-invoice"></i>
-				<?=htmlspecialchars(__("Commercial Invoice PDF"))?>
-			</a>
+			<div class="btn-group">
+				<a class="btn btn-primary pdf-action" href="<?=htmlspecialchars($document->getDownloadPdfUrl())?>" target="_blank" class="dropdown-item pdf-action">
+					<i class="fa fa-fw fa-file-invoice"></i>
+					<?=htmlspecialchars(__("Proforma Invoice PDF"))?>
+				</a>
+				<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
+					<span class="visually-hidden"><?=htmlspecialchars(__("Toggle Dropdown"))?></span>
+				</button>
+				<div class="dropdown-menu dropdown-menu-end">
+					<button type="button" class="dropdown-item email-pdf-action"><?=htmlspecialchars(__("Email PDF"))?></button>
+				</div>
+			</div>
+
+			<div class="btn-group">
+				<a class="btn btn-primary pdf-action" href="<?=htmlspecialchars($document->getDownloadPdfUrl("commercial"))?>" target="_blank" class="dropdown-item pdf-action">
+					<i class="fa fa-fw fa-file-invoice"></i>
+					<?=htmlspecialchars(__("Commercial Invoice PDF"))?>
+				</a>
+				<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
+					<span class="visually-hidden"><?=htmlspecialchars(__("Toggle Dropdown"))?></span>
+				</button>
+				<div class="dropdown-menu dropdown-menu-end">
+					<button type="button" class="dropdown-item email-pdf-action" data-variant="commercial"><?=htmlspecialchars(__("Email PDF"))?></button>
+				</div>
+			</div>
 			<?php
 		}
 		else {
 			?>
-			<a href="<?=htmlspecialchars($document->getDownloadPdfUrl())?>" class="btn btn-primary pdf-action" target="_blank">
-				<i class="fa fa-fw fa-file-pdf"></i>
-				<?=htmlspecialchars(__("%s PDF", $document->getDisplayType()))?>
-			</a>
+			<div class="btn-group">
+				<a href="<?=htmlspecialchars($document->getDownloadPdfUrl())?>" class="btn btn-primary pdf-action" target="_blank">
+					<i class="fa fa-fw fa-file-pdf"></i>
+					<?=htmlspecialchars(__("%s PDF", $document->getDisplayType()))?>
+				</a>
+				<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
+					<span class="visually-hidden"><?=htmlspecialchars(__("Toggle Dropdown"))?></span>
+				</button>
+				<div class="dropdown-menu dropdown-menu-end">
+					<button type="button" class="dropdown-item email-pdf-action"><?=htmlspecialchars(__("Email PDF"))?></button>
+				</div>
+			</div>
 			<?php
 		}
 		?>