document.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. <?php
  2. namespace App;
  3. use App\Enums\DocumentTypes;
  4. use App\Helpers\EmailHelper;
  5. use Exception;
  6. use PHPMailer\PHPMailer\PHPMailer;
  7. use RuntimeException;
  8. /**
  9. * @var string $document_type_string
  10. * @var int $document_number
  11. * @var string $action
  12. */
  13. $action = $action ?? null;
  14. $document_number = $document_number ?? null;
  15. $document_type = DocumentTypes::fromRouteName($document_type_string);
  16. $request = Request::fromRequest();
  17. $controller = new class($document_type, $document_number) {
  18. private ?User $user;
  19. private int $documentType;
  20. private ?int $documentNumber;
  21. private Request $request;
  22. public function __construct(int $document_type, ?int $document_number) {
  23. $core = Core::getInstance();
  24. $this->user = $core->getUser();
  25. $this->documentType = $document_type;
  26. $this->documentNumber = $document_number;
  27. $this->request = Request::fromRequest();
  28. }
  29. private function requireDocument(): Document {
  30. $document = Document::queryOne([
  31. "type" => $this->documentType,
  32. "number" => $this->documentNumber
  33. ]);
  34. if(!$document) {
  35. throw new RuntimeException(__("Document not found."));
  36. }
  37. return $document;
  38. }
  39. private function requireItem(int $item_id): DocumentItem {
  40. $document = $this->requireDocument();
  41. $items = $document->getItems(["id" => $item_id]);
  42. if(!$items) {
  43. throw new RuntimeException(__("Item not found."));
  44. }
  45. return $items[0];
  46. }
  47. private function requireCompany(int $id): Company {
  48. return Company::require($id);
  49. }
  50. private function requireLocation(int $id): Location {
  51. return Location::require($id);
  52. }
  53. private function requireTicket(int $id): Ticket {
  54. return Ticket::require($id);
  55. }
  56. private function requireSupplier(int $id): Supplier {
  57. return Supplier::require($id);
  58. }
  59. public function view(): void {
  60. $document = $this->requireDocument();
  61. $core = Core::getInstance();
  62. $this->user->requireAdmin();
  63. if($document->isSalesOrder() || $document->isDeliveryNote()) {
  64. /** @var Sale $sale */
  65. $sale = $document->getSale();
  66. if($sale) {
  67. $core->addBreadcrumb("/leads", __("Leads"));
  68. $core->addBreadcrumb($sale->getUrl(), $sale->getReference());
  69. }
  70. if($document->isPartOfAru()) {
  71. /** @var Document $aru */
  72. $aru = $document->getRelatedDocument();
  73. $core->addBreadcrumb("/arus", __("ARUs"));
  74. $core->addBreadcrumb($aru->getUrl(), $aru->getTitle());
  75. }
  76. }
  77. else if($document->isGoodsIn()) {
  78. $core->addBreadcrumb("/goods-in", __("Goods-In"));
  79. }
  80. else if($document->isAru()) {
  81. $core->addBreadcrumb("/arus", __("ARUs"));
  82. }
  83. $core->addBreadcrumb($document->getUrl(), $document->getTitle());
  84. $core->addScript("/js/document-item-modal.js");
  85. $core->addScript("/js/document-page.js");
  86. View::include("header");
  87. View::include("document", compact("document"));
  88. View::include("modals/document_item");
  89. View::include("footer");
  90. }
  91. public function create(): void {
  92. $type = $this->documentType;
  93. if(!DocumentTypes::validate($type)) {
  94. throw new RuntimeException(__("Invalid document type."));
  95. }
  96. $supplier_id = $this->request->int("supplier_id");
  97. $supplier = $supplier_id ? $this->requireSupplier($supplier_id) : null;
  98. $company_id = $this->request->int("company_id");
  99. $company = $company_id ? $this->requireCompany($company_id) : null;
  100. $location_id = $this->request->int("location_id");
  101. $location = $location_id ? $this->requireLocation($location_id) : null;
  102. $ticket_id = $this->request->int("ticket_id");
  103. $ticket = $ticket_id ? $this->requireTicket($ticket_id) : null;
  104. $document = new Document();
  105. $document->company_id = $company->id ?? null;
  106. $document->user_id = $this->user->id;
  107. $document->supplier_id = $supplier->id ?? null;
  108. $document->location_id = $location->id ?? null;
  109. $billing_address_string = "";
  110. $delivery_address_string = "";
  111. if($location) {
  112. $customer = $location->getCustomer();
  113. $delivery_address = $location->getAddress();
  114. $billing_entity = $location->getBillingEntity();
  115. if($billing_entity) {
  116. $billing_name = $billing_entity->name;
  117. $billing_address = $billing_entity->getAddress();
  118. }
  119. else {
  120. $billing_name = $customer->name;
  121. $billing_address = $customer->getAddress();
  122. }
  123. $billing_lines = array_merge([$billing_name], $billing_address->getLines());
  124. $billing_address_string = implode("\n", $billing_lines);
  125. $delivery_lines = array_merge([$location->name], $delivery_address->getLines());
  126. $delivery_address_string = implode("\n", $delivery_lines);
  127. $document->billing_address = $billing_address_string;
  128. $document->delivery_address = $delivery_address_string;
  129. $document->vat_number = $customer->vat_number;
  130. $document->contact_name = $location->contact_name;
  131. $document->contact_phone = $location->contact_phone;
  132. $document->contact_email = $location->contact_email;
  133. }
  134. $document->type = $type;
  135. $document->number = Document::getNextNumber($type);
  136. $document->date = date("Y-m-d");
  137. $document->dts_created = Database::dts();
  138. if($document->isSalesOrder() && !$document->location_id) {
  139. throw new RuntimeException(__("Location must be selected for a Sales Order document."));
  140. }
  141. if($document->isGoodsIn() && !$document->supplier_id && !$document->location_id) {
  142. throw new RuntimeException(__("Supplier or location must be selected for a Goods-In document."));
  143. }
  144. if($document->isAru() && !$document->location_id) {
  145. throw new RuntimeException(__("Location must be selected for an ARU document."));
  146. }
  147. $document->commit();
  148. if($document->isAru() && $ticket) {
  149. $ticket->aru_document_id = $document->id;
  150. $ticket->commit();
  151. }
  152. $item_description = $this->request->string("item_description");
  153. $item_serial_number = $this->request->string("item_serial_number");
  154. if($item_description) {
  155. $item = new DocumentItem();
  156. $item->document_id = $document->id;
  157. $item->description = $item_description;
  158. $item->serial_number = $item_serial_number;
  159. $item->quantity = 1;
  160. $item->unit_price = "0.00";
  161. $item->dts_created = Database::dts();
  162. $item->commit();
  163. }
  164. if($document->hasCosts() && $location) {
  165. $document->currency = "GBP";
  166. $document->tax_rate = "20.00";
  167. $document->billing_address = $billing_address_string;
  168. $document->delivery_address = $delivery_address_string;
  169. $document->commit();
  170. }
  171. Json::success([
  172. "url" => $document->getUrl()
  173. ]);
  174. }
  175. public function update(): void {
  176. $document = $this->requireDocument();
  177. $company_id = $this->request->int("company_id");
  178. if($company_id) {
  179. $company = $this->requireCompany($company_id);
  180. $document->company_id = $company->id;
  181. }
  182. $location_id = $this->request->int("location_id");
  183. if($document->location_id && $location_id) {
  184. $location = $this->requireLocation($location_id);
  185. $document->location_id = $location->id;
  186. }
  187. if($document->isSalesOrder()) {
  188. $document->invoice_status = $this->request->int("invoice_status");
  189. $document->terms = $this->request->string("terms");
  190. $document->vat_number = $this->request->string("vat_number");
  191. $document->currency = $this->request->string("currency");
  192. $document->tax_rate = $this->request->decimal("tax_rate", 2);
  193. $date_finalised = $this->request->date("dts_finalised");
  194. if($date_finalised) {
  195. $document->dts_finalised = $date_finalised . " 12:00:00";
  196. }
  197. else {
  198. $document->dts_finalised = null;
  199. }
  200. $date_paid = $this->request->date("dts_paid");
  201. if($date_paid) {
  202. $document->dts_paid = $date_paid . " 12:00:00";
  203. }
  204. else {
  205. $document->dts_paid = null;
  206. }
  207. }
  208. if($document->isAru()) {
  209. $document->aru_status = $this->request->int("aru_status");
  210. }
  211. $document->date = $this->request->string("date");
  212. if($document->isSalesOrder() || $document->isDeliveryNote()) {
  213. $document->billing_address = $this->request->string("billing_address");
  214. $document->delivery_address = $this->request->string("delivery_address");
  215. $document->po_number = $this->request->string("po_number");
  216. }
  217. $document->notes = $this->request->string("notes");
  218. $document->proforma_notes = $this->request->string("proforma_notes");
  219. $document->commercial_notes = $this->request->string("commercial_notes");
  220. if($document->isDeliveryNote()) {
  221. $document->delivery_company = $this->request->string("delivery_company");
  222. $document->tracking_number = $this->request->string("tracking_number");
  223. }
  224. $document->delivery_cost = $this->request->decimal("delivery_cost", 2);
  225. $document->contact_name = $this->request->string("contact_name");
  226. $document->contact_phone = $this->request->string("contact_phone");
  227. $document->contact_email = $this->request->email("contact_email");
  228. $document->commit();
  229. if(Http::isAjax()) {
  230. Json::success();
  231. }
  232. else {
  233. Session::addAlert("success", __("%s document updated successfully.", $document->getDisplayType()));
  234. Http::redirect($document->getUrl());
  235. }
  236. }
  237. public function submitItem(): void {
  238. $document = $this->requireDocument();
  239. $document_item_id = $this->request->int("document_item_id");
  240. if($document_item_id) {
  241. $item = $this->requireItem($document_item_id);
  242. $item->dts_updated = Database::dts();
  243. }
  244. else {
  245. $item = new DocumentItem();
  246. $item->document_id = $document->id;
  247. $item->dts_created = Database::dts();
  248. }
  249. $item->description = $this->request->string("description");
  250. $item->serial_number = $this->request->string("serial_number");
  251. $item->quantity = $this->request->int("quantity");
  252. $item->unit_price = $this->request->decimal("unit_price", 2);
  253. $item->insurance_value = $this->request->decimal("insurance_value", 2);
  254. $item->commit();
  255. Json::success([
  256. "html" => View::getHtml("document_items_section", ["document" => $document])
  257. ]);
  258. }
  259. public function deleteItem(): void {
  260. $document = $this->requireDocument();
  261. $document_item_id = $this->request->int("document_item_id");
  262. $item = $this->requireItem($document_item_id);
  263. $item->softDelete();
  264. Json::success([
  265. "html" => View::getHtml("document_items_section", ["document" => $document])
  266. ]);
  267. }
  268. public function deleteItems(): void {
  269. $document_item_ids = $this->request->int("document_item_ids");
  270. if(!$document_item_ids || !is_array($document_item_ids)) {
  271. throw new RuntimeException(__("No items selected."));
  272. }
  273. $items = $this->validateItemIds($document_item_ids);
  274. foreach($items as $item) {
  275. $item->softDelete();
  276. }
  277. $document = $this->requireDocument();
  278. Session::addAlert("success", __("Items deleted successfully."));
  279. Http::redirect($document->getUrl());
  280. }
  281. public function createDocumentWithItems(int $document_type): void {
  282. $document_item_ids = $this->request->int("document_item_ids");
  283. if(!$document_item_ids || !is_array($document_item_ids)) {
  284. throw new RuntimeException(__("No items selected."));
  285. }
  286. $source_document = $this->requireDocument();
  287. $items = $this->validateItemIds($document_item_ids);
  288. $document = new Document();
  289. $document->company_id = $source_document->company_id;
  290. $document->user_id = $this->user->id;
  291. $document->sale_id = $source_document->sale_id;
  292. $document->location_id = $source_document->location_id;
  293. $document->related_document_id = $source_document->id;
  294. $document->type = $document_type;
  295. $document->currency = $source_document->currency;
  296. $document->tax_rate = $source_document->tax_rate;
  297. $document->billing_address = $source_document->billing_address;
  298. $document->delivery_address = $source_document->delivery_address;
  299. $document->number = Document::getNextNumber($document_type);
  300. $document->date = date("Y-m-d");
  301. $document->delivery_company = $source_document->delivery_company;
  302. $document->tracking_number = $source_document->tracking_number;
  303. $document->notes = $source_document->notes;
  304. $document->po_number = $source_document->po_number;
  305. $document->vat_number = $source_document->vat_number;
  306. $document->contact_name = $source_document->contact_name;
  307. $document->contact_phone = $source_document->contact_phone;
  308. $document->contact_email = $source_document->contact_email;
  309. $document->dts_created = Database::dts();
  310. $document->commit();
  311. foreach($items as $item) {
  312. $document_item = new DocumentItem();
  313. $document_item->document_id = $document->id;
  314. $document_item->product_id = $item->product_id;
  315. $document_item->description = $item->description;
  316. $document_item->serial_number = $item->serial_number;
  317. $document_item->quantity = $item->quantity;
  318. $document_item->unit_price = $item->unit_price;
  319. $document_item->dts_created = Database::dts();
  320. $document_item->commit();
  321. }
  322. Session::addAlert("success", __("%s created successfully.", $document->getDisplayType()));
  323. Http::redirect($document->getUrl());
  324. }
  325. /**
  326. * @param int[] $document_item_ids
  327. * @return DocumentItem[]
  328. */
  329. private function validateItemIds(array $document_item_ids): array {
  330. $items = [];
  331. foreach($document_item_ids as $document_item_id) {
  332. $items[] = $this->requireItem($document_item_id);
  333. }
  334. return $items;
  335. }
  336. public function renderPdf(): void {
  337. $document = $this->requireDocument();
  338. $variant = $this->request->string("variant");
  339. $access_token = $this->request->string("access_token");
  340. if($access_token !== $document->getAccessToken()) {
  341. throw new RuntimeException(__("Invalid access token."));
  342. }
  343. $view = "document_pdf";
  344. if($document->isPartOfAru() && $document->isDeliveryNote()) {
  345. $view = "aru_dn_pdf";
  346. }
  347. View::include($view, compact("document", "variant"));
  348. }
  349. public function downloadPdf(): void {
  350. $document = $this->requireDocument();
  351. $variant = $this->request->string("variant");
  352. $output_path = $document->generatePdf($variant);
  353. if(file_exists($output_path)) {
  354. Http::downloadFile($output_path, $document->getPdfFilename($variant), "application/pdf");
  355. }
  356. else {
  357. header("Content-Type: text/plain");
  358. http_response_code(500);
  359. echo "Failed to generate PDF.\n";
  360. }
  361. exit();
  362. }
  363. public function emailPdf(): void {
  364. $include_brochures = $this->request->int("include_brochures");
  365. $document = $this->requireDocument();
  366. $core = Core::getInstance();
  367. /** @var User $user */
  368. $user = $core->getUser();
  369. try {
  370. if(!$document->contact_email) {
  371. throw new RuntimeException(__("Contact Email must be set."));
  372. }
  373. if(!$document->contact_name) {
  374. throw new RuntimeException(__("Contact Name must be set."));
  375. }
  376. $company = $document->getCompany();
  377. if(!$company) {
  378. throw new RuntimeException(__("Company must be set."));
  379. }
  380. $variant = $this->request->string("variant");
  381. $pdf_path = $document->generatePdf($variant);
  382. if(!file_exists($pdf_path)) {
  383. throw new RuntimeException(__("Failed to generate PDF."));
  384. }
  385. $title = $document->getTitle();
  386. $text = "Hereby attached is your information.";
  387. if($document->isSalesOrder()) {
  388. if($variant === "commercial") {
  389. $title = __("Commercial Invoice %d", $document->number);
  390. $text = __("Hereby attached is your Commercial Invoice as requested.");
  391. }
  392. else {
  393. $title = __("Proforma Invoice %d", $document->number);
  394. $text = __("Hereby attached is your Pro-forma Offer.");
  395. }
  396. }
  397. if($document->isDeliveryNote()) {
  398. $text = __("Hereby attached is your Delivery Note information.");
  399. }
  400. $body = file_get_contents("templates/email/document.html");
  401. $search_replace = [
  402. "%contact-name%" => $document->contact_name,
  403. "%document-title%" => $title,
  404. "%company-name%" => $company->name,
  405. "%user-name%" => $user->getDisplayName(),
  406. "%document-text%" => $text
  407. ];
  408. $body = str_replace(array_keys($search_replace), array_values($search_replace), $body);
  409. $mailer = EmailHelper::getMailer();
  410. $mailer->addAddress($document->contact_email, $document->contact_name);
  411. $mailer->CharSet = PHPMailer::CHARSET_UTF8;
  412. $mailer->Subject = $title;
  413. $mailer->Body = $body;
  414. $mailer->AltBody = strip_tags($body);
  415. $mailer->addAttachment($pdf_path, $title . ".pdf");
  416. if($include_brochures) {
  417. foreach($document->getProducts() as $product) {
  418. if($product->hasBrochure()) {
  419. $attachment_name = $product->name . ".pdf";
  420. $mailer->addAttachment($product->getBrochurePath(), $attachment_name);
  421. }
  422. }
  423. }
  424. $mailer->send();
  425. $core->getLogger()->info(sprintf("%s emailed to %s by %s <%s>", $document->getTitle(), $document->contact_email, $user->getDisplayName(), $user->email));
  426. Json::success();
  427. }
  428. catch(Exception $e) {
  429. Json::fail($e->getMessage());
  430. }
  431. }
  432. };
  433. switch($action) {
  434. case "create":
  435. $controller->create();
  436. break;
  437. case "submit":
  438. $controller->update();
  439. break;
  440. case "submit-item":
  441. $controller->submitItem();
  442. break;
  443. case "delete-item":
  444. $controller->deleteItem();
  445. break;
  446. case "items-batch-action":
  447. $batch_action = $request->string("batch_action");
  448. switch($batch_action) {
  449. case "delete":
  450. $controller->deleteItems();
  451. break;
  452. case "create-sales-order":
  453. $controller->createDocumentWithItems(DocumentTypes::SALES_ORDER);
  454. break;
  455. case "create-delivery-note":
  456. $controller->createDocumentWithItems(DocumentTypes::DELIVERY_NOTE);
  457. break;
  458. case "create-goods-in":
  459. $controller->createDocumentWithItems(DocumentTypes::GOODS_IN);
  460. break;
  461. default:
  462. throw new RuntimeException(__("Invalid batch action."));
  463. }
  464. break;
  465. case "render-pdf":
  466. $controller->renderPdf();
  467. break;
  468. case "download-pdf":
  469. $controller->downloadPdf();
  470. break;
  471. case "email-pdf":
  472. $controller->emailPdf();
  473. break;
  474. default:
  475. $controller->view();
  476. }