user = $core->getUser(); $this->documentType = $document_type; $this->documentNumber = $document_number; $this->request = Request::fromRequest(); } private function requireDocument(): Document { $document = Document::queryOne([ "type" => $this->documentType, "number" => $this->documentNumber ]); if(!$document) { throw new RuntimeException(__("Document not found.")); } return $document; } private function requireItem(int $item_id): DocumentItem { $document = $this->requireDocument(); $items = $document->getItems(["id" => $item_id]); if(!$items) { throw new RuntimeException(__("Item not found.")); } return $items[0]; } private function requireCompany(int $id): Company { return Company::require($id); } private function requireLocation(int $id): Location { return Location::require($id); } private function requireTicket(int $id): Ticket { return Ticket::require($id); } private function requireSupplier(int $id): Supplier { return Supplier::require($id); } public function view(): void { $document = $this->requireDocument(); $core = Core::getInstance(); $this->user->requireAdmin(); if($document->isSalesOrder() || $document->isDeliveryNote()) { /** @var Sale $sale */ $sale = $document->getSale(); if($sale) { $core->addBreadcrumb("/leads", __("Leads")); $core->addBreadcrumb($sale->getUrl(), $sale->getReference()); } if($document->isPartOfAru()) { /** @var Document $aru */ $aru = $document->getRelatedDocument(); $core->addBreadcrumb("/arus", __("ARUs")); $core->addBreadcrumb($aru->getUrl(), $aru->getTitle()); } } else if($document->isGoodsIn()) { $core->addBreadcrumb("/goods-in", __("Goods-In")); } else if($document->isAru()) { $core->addBreadcrumb("/arus", __("ARUs")); } $core->addBreadcrumb($document->getUrl(), $document->getTitle()); $core->addScript("/js/document-item-modal.js"); $core->addScript("/js/document-page.js"); View::include("header"); View::include("document", compact("document")); View::include("modals/document_item"); View::include("footer"); } public function create(): void { $type = $this->documentType; if(!DocumentTypes::validate($type)) { throw new RuntimeException(__("Invalid document type.")); } $supplier_id = $this->request->int("supplier_id"); $supplier = $supplier_id ? $this->requireSupplier($supplier_id) : null; $company_id = $this->request->int("company_id"); $company = $company_id ? $this->requireCompany($company_id) : null; $location_id = $this->request->int("location_id"); $location = $location_id ? $this->requireLocation($location_id) : null; $ticket_id = $this->request->int("ticket_id"); $ticket = $ticket_id ? $this->requireTicket($ticket_id) : null; $document = new Document(); $document->company_id = $company->id ?? null; $document->user_id = $this->user->id; $document->supplier_id = $supplier->id ?? null; $document->location_id = $location->id ?? null; if($location) { $customer = $location->getCustomer(); $address = $location->getAddress(); $lines = array_merge([$location->name], $address->getLines()); $address_string = implode("\n", $lines); $document->billing_address = $address_string; $document->delivery_address = $address_string; $document->vat_number = $customer->vat_number; } $document->type = $type; $document->number = Document::getNextNumber($type); $document->date = date("Y-m-d"); $document->dts_created = Database::dts(); if($document->isSalesOrder() && !$document->location_id) { throw new RuntimeException(__("Location must be selected for a Sales Order document.")); } if($document->isGoodsIn() && !$document->supplier_id && !$document->location_id) { throw new RuntimeException(__("Supplier or location must be selected for a Goods-In document.")); } if($document->isAru() && !$document->location_id) { throw new RuntimeException(__("Location must be selected for an ARU document.")); } $document->commit(); if($document->isAru() && $ticket) { $ticket->aru_document_id = $document->id; $ticket->commit(); } $item_description = $this->request->string("item_description"); $item_serial_number = $this->request->string("item_serial_number"); if($item_description) { $item = new DocumentItem(); $item->document_id = $document->id; $item->description = $item_description; $item->serial_number = $item_serial_number; $item->quantity = 1; $item->unit_price = "0.00"; $item->dts_created = Database::dts(); $item->commit(); } if($document->hasCosts() && $location) { $address = $location->getAddress(); $document->currency = "GBP"; $document->tax_rate = "20.00"; $document->billing_address = (string) $address; $document->delivery_address = (string) $address; $document->commit(); } Json::success([ "url" => $document->getUrl() ]); } public function update(): void { $document = $this->requireDocument(); $company_id = $this->request->int("company_id"); if($company_id) { $company = $this->requireCompany($company_id); $document->company_id = $company->id; } if($document->isSalesOrder()) { $document->invoice_status = $this->request->int("invoice_status"); $document->terms = $this->request->string("terms"); $document->vat_number = $this->request->string("vat_number"); $document->currency = $this->request->string("currency"); $document->tax_rate = $this->request->decimal("tax_rate", 2); $document->dts_finalised = $this->request->dateTime("dts_finalised", "Y-m-d\TH:i", $this->user->getTimezone()); $document->dts_paid = $this->request->dateTime("dts_paid", "Y-m-d\TH:i", $this->user->getTimezone()); } if($document->isAru()) { $document->aru_status = $this->request->int("aru_status"); } $document->date = $this->request->string("date"); if($document->isSalesOrder() || $document->isDeliveryNote()) { $document->billing_address = $this->request->string("billing_address"); $document->delivery_address = $this->request->string("delivery_address"); $document->po_number = $this->request->string("po_number"); } $document->notes = $this->request->string("notes"); $document->delivery_company = $this->request->string("delivery_company"); $document->tracking_number = $this->request->string("tracking_number"); $document->delivery_cost = $this->request->decimal("delivery_cost", 2); $document->contact_name = $this->request->string("contact_name"); $document->contact_phone = $this->request->string("contact_phone"); $document->contact_email = $this->request->email("contact_email"); $document->commit(); if(Http::isAjax()) { Json::success(); } else { Session::addAlert("success", __("%s document updated successfully.", $document->getDisplayType())); Http::redirect($document->getUrl()); } } public function submitItem(): void { $document = $this->requireDocument(); $document_item_id = $this->request->int("document_item_id"); if($document_item_id) { $item = $this->requireItem($document_item_id); $item->dts_updated = Database::dts(); } else { $item = new DocumentItem(); $item->document_id = $document->id; $item->dts_created = Database::dts(); } $item->description = $this->request->string("description"); $item->serial_number = $this->request->string("serial_number"); $item->quantity = $this->request->int("quantity"); $item->unit_price = $this->request->decimal("unit_price", 2); $item->insurance_value = $this->request->decimal("insurance_value", 2); $item->commit(); Json::success([ "html" => View::getHtml("document_items_section", ["document" => $document]) ]); } public function deleteItem(): void { $document = $this->requireDocument(); $document_item_id = $this->request->int("document_item_id"); $item = $this->requireItem($document_item_id); $item->softDelete(); Json::success([ "html" => View::getHtml("document_items_section", ["document" => $document]) ]); } public function deleteItems(): void { $document_item_ids = $this->request->int("document_item_ids"); if(!$document_item_ids || !is_array($document_item_ids)) { throw new RuntimeException(__("No items selected.")); } $items = $this->validateItemIds($document_item_ids); foreach($items as $item) { $item->softDelete(); } $document = $this->requireDocument(); Session::addAlert("success", __("Items deleted successfully.")); Http::redirect($document->getUrl()); } public function createDocumentWithItems(int $document_type): void { $document_item_ids = $this->request->int("document_item_ids"); if(!$document_item_ids || !is_array($document_item_ids)) { throw new RuntimeException(__("No items selected.")); } $source_document = $this->requireDocument(); $items = $this->validateItemIds($document_item_ids); $document = new Document(); $document->company_id = $source_document->company_id; $document->user_id = $this->user->id; $document->sale_id = $source_document->sale_id; $document->location_id = $source_document->location_id; $document->related_document_id = $source_document->id; $document->type = $document_type; $document->currency = $source_document->currency; $document->tax_rate = $source_document->tax_rate; $document->billing_address = $source_document->billing_address; $document->delivery_address = $source_document->delivery_address; $document->number = Document::getNextNumber($document_type); $document->date = date("Y-m-d"); $document->delivery_company = $source_document->delivery_company; $document->tracking_number = $source_document->tracking_number; $document->notes = $source_document->notes; $document->po_number = $source_document->po_number; $document->vat_number = $source_document->vat_number; $document->contact_name = $source_document->contact_name; $document->contact_phone = $source_document->contact_phone; $document->contact_email = $source_document->contact_email; $document->dts_created = Database::dts(); $document->commit(); foreach($items as $item) { $document_item = new DocumentItem(); $document_item->document_id = $document->id; $document_item->product_id = $item->product_id; $document_item->description = $item->description; $document_item->serial_number = $item->serial_number; $document_item->quantity = $item->quantity; $document_item->unit_price = $item->unit_price; $document_item->dts_created = Database::dts(); $document_item->commit(); } Session::addAlert("success", __("%s created successfully.", $document->getDisplayType())); Http::redirect($document->getUrl()); } /** * @param int[] $document_item_ids * @return DocumentItem[] */ private function validateItemIds(array $document_item_ids): array { $items = []; foreach($document_item_ids as $document_item_id) { $items[] = $this->requireItem($document_item_id); } return $items; } public function renderPdf(): void { $document = $this->requireDocument(); $variant = $this->request->string("variant"); $access_token = $this->request->string("access_token"); if($access_token !== $document->getAccessToken()) { throw new RuntimeException(__("Invalid access token.")); } $view = "document_pdf"; if($document->isPartOfAru() && $document->isDeliveryNote()) { $view = "aru_dn_pdf"; } View::include($view, compact("document", "variant")); } public function downloadPdf(): void { $document = $this->requireDocument(); $variant = $this->request->string("variant"); $output_path = $document->generatePdf($variant); if(file_exists($output_path)) { Http::downloadFile($output_path, $document->getPdfFilename(), "application/pdf"); } else { header("Content-Type: text/plain"); http_response_code(500); echo "Failed to generate PDF.\n"; } exit(); } public function emailPdf(): void { $include_brochures = $this->request->int("include_brochures"); $document = $this->requireDocument(); $core = Core::getInstance(); /** @var User $user */ $user = $core->getUser(); 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(); $text = "Hereby attached is your information."; if($document->isSalesOrder()) { if($variant === "commercial") { $title = __("Commercial Invoice %d", $document->number); $text = __("Hereby attached is your Commercial Invoice as requested."); } else { $title = __("Proforma Invoice %d", $document->number); $text = __("Hereby attached is your Pro-forma Offer."); } } if($document->isDeliveryNote()) { $text = __("Hereby attached is your Delivery Note information."); } $body = file_get_contents("templates/email/document.html"); $search_replace = [ "%contact-name%" => $document->contact_name, "%document-title%" => $title, "%company-name%" => $company->name, "%user-name%" => $user->getDisplayName(), "%document-text%" => $text ]; $body = str_replace(array_keys($search_replace), array_values($search_replace), $body); $mailer = EmailHelper::getMailer(); $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"); if($include_brochures) { foreach($document->getProducts() as $product) { if($product->hasBrochure()) { $attachment_name = $product->name . ".pdf"; $mailer->addAttachment($product->getBrochurePath(), $attachment_name); } } } $mailer->send(); $core->getLogger()->info(sprintf("%s emailed to %s by %s <%s>", $document->getTitle(), $document->contact_email, $user->getDisplayName(), $user->email)); Json::success(); } catch(Exception $e) { Json::fail($e->getMessage()); } } }; switch($action) { case "create": $controller->create(); break; case "submit": $controller->update(); break; case "submit-item": $controller->submitItem(); break; case "delete-item": $controller->deleteItem(); break; case "items-batch-action": $batch_action = $request->string("batch_action"); switch($batch_action) { case "delete": $controller->deleteItems(); break; case "create-sales-order": $controller->createDocumentWithItems(DocumentTypes::SALES_ORDER); break; case "create-delivery-note": $controller->createDocumentWithItems(DocumentTypes::DELIVERY_NOTE); break; case "create-goods-in": $controller->createDocumentWithItems(DocumentTypes::GOODS_IN); break; default: throw new RuntimeException(__("Invalid batch action.")); } break; case "render-pdf": $controller->renderPdf(); break; case "download-pdf": $controller->downloadPdf(); break; case "email-pdf": $controller->emailPdf(); break; default: $controller->view(); }