document.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. <?php
  2. namespace App;
  3. use App\Enums\DocumentTypes;
  4. use RuntimeException;
  5. /**
  6. * @var string $document_type_string
  7. * @var int $document_number
  8. * @var string $action
  9. */
  10. $action = $action ?? null;
  11. $document_number = $document_number ?? null;
  12. switch($document_type_string) {
  13. case "invoices":
  14. $document_type = DocumentTypes::INVOICE;
  15. break;
  16. case "delivery-notes":
  17. $document_type = DocumentTypes::DELIVERY_NOTE;
  18. break;
  19. case "goods-in":
  20. $document_type = DocumentTypes::GOODS_IN;
  21. break;
  22. case "arus":
  23. $document_type = DocumentTypes::ADVANCE_REPLACEMENT_UNIT;
  24. break;
  25. default:
  26. throw new RuntimeException(__("Invalid document type."));
  27. }
  28. $request = Request::fromRequest();
  29. $controller = new class($document_type, $document_number) {
  30. private ?User $user;
  31. private int $documentType;
  32. private ?int $documentNumber;
  33. private Request $request;
  34. public function __construct(int $document_type, ?int $document_number) {
  35. $core = Core::getInstance();
  36. $this->user = $core->getUser();
  37. $this->documentType = $document_type;
  38. $this->documentNumber = $document_number;
  39. $this->request = Request::fromRequest();
  40. }
  41. private function requireDocument(): Document {
  42. $document = Document::queryOne([
  43. "type" => $this->documentType,
  44. "number" => $this->documentNumber
  45. ]);
  46. if(!$document) {
  47. throw new RuntimeException(__("Document not found."));
  48. }
  49. return $document;
  50. }
  51. private function requireItem(int $item_id): DocumentItem {
  52. $document = $this->requireDocument();
  53. $items = $document->getItems(["id" => $item_id]);
  54. if(!$items) {
  55. throw new RuntimeException(__("Item not found."));
  56. }
  57. return $items[0];
  58. }
  59. private function requireCompany(int $id): Company {
  60. $company = Company::get($id);
  61. if(!$company) {
  62. throw new RuntimeException(__("Company not found."));
  63. }
  64. return $company;
  65. }
  66. private function requireLocation(int $id): Location {
  67. $location = Location::get($id);
  68. if(!$location) {
  69. throw new RuntimeException(__("Location not found."));
  70. }
  71. return $location;
  72. }
  73. private function requireSupplier(int $id): Supplier {
  74. $supplier = Supplier::get($id);
  75. if(!$supplier) {
  76. throw new RuntimeException(__("Supplier not found."));
  77. }
  78. return $supplier;
  79. }
  80. public function view(): void {
  81. $document = $this->requireDocument();
  82. $core = Core::getInstance();
  83. $this->user->requireAdmin();
  84. if($document->isInvoice() || $document->isDeliveryNote()) {
  85. /** @var Sale $sale */
  86. $sale = $document->getSale();
  87. $core->addBreadcrumb("/sales", __("Sales"));
  88. $core->addBreadcrumb($sale->getUrl(), __("Sale %d", $sale->getNumber()));
  89. if($document->isInvoice()) {
  90. $core->addBreadcrumb($document->getUrl(), __("Invoice %d", $document->number));
  91. }
  92. if($document->isDeliveryNote()) {
  93. $core->addBreadcrumb($document->getUrl(), __("Delivery Note %d", $document->number));
  94. }
  95. }
  96. $core->addScript("/js/document-item-modal.js");
  97. $core->addScript("/js/document-page.js");
  98. View::include("header");
  99. View::include("document", compact("document"));
  100. View::include("modals/document_item");
  101. View::include("footer");
  102. }
  103. public function create(): void {
  104. $type = $this->documentType;
  105. if(!DocumentTypes::validate($type)) {
  106. throw new RuntimeException(__("Invalid document type."));
  107. }
  108. $supplier_id = $this->request->int("supplier_id");
  109. $supplier = $supplier_id ? $this->requireSupplier($supplier_id) : null;
  110. // $company_id = $this->request->int("company_id");
  111. // $company = $company_id ? $this->requireCompany($company_id) : null;
  112. $location_id = $this->request->int("location_id");
  113. $location = $location_id ? $this->requireLocation($location_id) : null;
  114. $document = new Document();
  115. $document->user_id = $this->user->id;
  116. $document->supplier_id = $supplier->id ?? null;
  117. // $document->company_id = $company->id ?? null;
  118. $document->location_id = $location->id ?? null;
  119. $document->type = $type;
  120. $document->number = Document::getNextNumber($type);
  121. $document->date = date("Y-m-d");
  122. $document->dts_created = Database::dts();
  123. if($document->isGoodsIn() && !$document->supplier_id && !$document->location_id) {
  124. throw new RuntimeException(__("Supplier or location must be selected for a Goods-In document."));
  125. }
  126. if($document->isAru() && !$document->location_id) {
  127. throw new RuntimeException(__("Location must be selected for an ARU document."));
  128. }
  129. $document->commit();
  130. JSON::success([
  131. "url" => $document->getUrl()
  132. ]);
  133. }
  134. public function update(): void {
  135. $document = $this->requireDocument();
  136. if($document->isInvoice()) {
  137. $document->invoice_status = $this->request->int("invoice_status");
  138. $document->terms = $this->request->string("terms");
  139. $document->currency = $this->request->string("currency");
  140. $document->tax_rate = $this->request->decimal("tax_rate", 2);
  141. $document->dts_finalised = $this->request->dateTime("dts_finalised", "Y-m-d\TH:i", $this->user->getTimezone());
  142. $document->dts_paid = $this->request->dateTime("dts_paid", "Y-m-d\TH:i", $this->user->getTimezone());
  143. }
  144. $document->date = $this->request->string("date");
  145. if($document->isInvoice() || $document->isDeliveryNote()) {
  146. $document->billing_address = $this->request->string("billing_address");
  147. $document->delivery_address = $this->request->string("delivery_address");
  148. $document->po_number = $this->request->string("po_number");
  149. }
  150. $document->notes = $this->request->string("notes");
  151. $document->delivery_company = $this->request->string("delivery_company");
  152. $document->tracking_number = $this->request->string("tracking_number");
  153. $document->commit();
  154. Session::addAlert("success", __("%s document updated successfully.", $document->getDisplayType()));
  155. Http::redirect($document->getUrl());
  156. }
  157. public function submitItem(): void {
  158. $document = $this->requireDocument();
  159. $document_item_id = $this->request->int("document_item_id");
  160. if($document_item_id) {
  161. $item = $this->requireItem($document_item_id);
  162. $item->dts_updated = Database::dts();
  163. }
  164. else {
  165. $item = new DocumentItem();
  166. $item->document_id = $document->id;
  167. $item->dts_created = Database::dts();
  168. }
  169. $item->description = $this->request->string("description");
  170. $item->serial_number = $this->request->string("serial_number");
  171. $item->quantity = $this->request->int("quantity");
  172. $item->unit_price = $this->request->decimal("unit_price", 2);
  173. $item->commit();
  174. JSON::success([
  175. "html" => View::getHtml("document_items_section", ["document" => $document])
  176. ]);
  177. }
  178. public function deleteItem(): void {
  179. $document = $this->requireDocument();
  180. $document_item_id = $this->request->int("document_item_id");
  181. $item = $this->requireItem($document_item_id);
  182. $item->softDelete();
  183. JSON::success([
  184. "html" => View::getHtml("document_items_section", ["document" => $document])
  185. ]);
  186. }
  187. public function deleteItems(): void {
  188. $document_item_ids = $this->request->int("document_item_ids");
  189. if(!$document_item_ids || !is_array($document_item_ids)) {
  190. throw new RuntimeException(__("No items selected."));
  191. }
  192. $items = $this->validateItemIds($document_item_ids);
  193. foreach($items as $item) {
  194. $item->softDelete();
  195. }
  196. $document = $this->requireDocument();
  197. Session::addAlert("success", __("Items deleted successfully."));
  198. Http::redirect($document->getUrl());
  199. }
  200. public function createDeliveryNote(): void {
  201. $document_item_ids = $this->request->int("document_item_ids");
  202. if(!$document_item_ids || !is_array($document_item_ids)) {
  203. throw new RuntimeException(__("No items selected."));
  204. }
  205. $invoice = $this->requireDocument();
  206. $items = $this->validateItemIds($document_item_ids);
  207. $delivery_note = new Document();
  208. $delivery_note->user_id = $this->user->id;
  209. $delivery_note->sale_id = $invoice->sale_id;
  210. $delivery_note->location_id = $invoice->location_id;
  211. $delivery_note->related_document_id = $invoice->id;
  212. $delivery_note->type = DocumentTypes::DELIVERY_NOTE;
  213. $delivery_note->billing_address = $invoice->billing_address;
  214. $delivery_note->delivery_address = $invoice->delivery_address;
  215. $delivery_note->number = Document::getNextNumber(DocumentTypes::DELIVERY_NOTE);
  216. $delivery_note->date = date("Y-m-d");
  217. $delivery_note->delivery_company = $invoice->delivery_company;
  218. $delivery_note->tracking_number = $invoice->tracking_number;
  219. $delivery_note->dts_created = Database::dts();
  220. $delivery_note->commit();
  221. foreach($items as $item) {
  222. $delivery_note_item = new DocumentItem();
  223. $delivery_note_item->document_id = $delivery_note->id;
  224. $delivery_note_item->description = $item->description;
  225. $delivery_note_item->serial_number = $item->serial_number;
  226. $delivery_note_item->quantity = $item->quantity;
  227. $delivery_note_item->unit_price = $item->unit_price;
  228. $delivery_note_item->dts_created = Database::dts();
  229. $delivery_note_item->commit();
  230. }
  231. Session::addAlert("success", __("Delivery note created successfully."));
  232. Http::redirect($delivery_note->getUrl());
  233. }
  234. /**
  235. * @param int[] $document_item_ids
  236. * @return DocumentItem[]
  237. */
  238. private function validateItemIds(array $document_item_ids): array {
  239. $items = [];
  240. foreach($document_item_ids as $document_item_id) {
  241. $items[] = $this->requireItem($document_item_id);
  242. }
  243. return $items;
  244. }
  245. public function renderPdf(): void {
  246. $document = $this->requireDocument();
  247. $variant = $this->request->string("variant");
  248. $access_token = $this->request->string("access_token");
  249. if($access_token !== $document->getAccessToken()) {
  250. throw new RuntimeException(__("Invalid access token."));
  251. }
  252. View::include("document_pdf", compact("document", "variant"));
  253. }
  254. public function downloadPdf(): void {
  255. $document = $this->requireDocument();
  256. $variant = $this->request->string("variant");
  257. $host = $_SERVER["HTTP_HOST"];
  258. $render_url = "https://" . $host . $document->getUrl() . "/render-pdf?" . http_build_query([
  259. "access_token" => $document->getAccessToken(),
  260. "variant" => $variant
  261. ]);
  262. chdir($_ENV["DIR_ROOT"]);
  263. $output_filename = $document->id . ".pdf";
  264. $output_path = "pdf-output/" . $output_filename;
  265. $command = sprintf('node pdf.js "%s" "%s"',
  266. $render_url,
  267. $output_filename
  268. );
  269. shell_exec($command);
  270. if(file_exists($output_path)) {
  271. Http::downloadFile($output_path, $document->getPdfFilename(), "application/pdf");
  272. }
  273. else {
  274. header("Content-Type: text/plain");
  275. http_response_code(500);
  276. echo "Failed to generate PDF.\n";
  277. }
  278. exit();
  279. }
  280. };
  281. switch($action) {
  282. case "create":
  283. $controller->create();
  284. case "submit":
  285. $controller->update();
  286. break;
  287. case "submit-item":
  288. $controller->submitItem();
  289. break;
  290. case "delete-item":
  291. $controller->deleteItem();
  292. break;
  293. case "items-batch-action":
  294. $batch_action = $request->string("batch_action");
  295. switch($batch_action) {
  296. case "delete":
  297. $controller->deleteItems();
  298. break;
  299. case "create-delivery-note":
  300. $controller->createDeliveryNote();
  301. break;
  302. default:
  303. throw new RuntimeException(__("Invalid batch action."));
  304. }
  305. break;
  306. case "render-pdf":
  307. $controller->renderPdf();
  308. break;
  309. case "download-pdf":
  310. $controller->downloadPdf();
  311. break;
  312. default:
  313. $controller->view();
  314. }