| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452 |
- <?php
- namespace App;
- use App\Constraint\Constraint;
- use App\Constraint\NotNullConstraint;
- use App\Enums\AruStatuses;
- use App\Enums\DocumentTypes;
- use App\Enums\SalesOrderStatuses;
- use App\Traits\DateTimeTrait;
- use App\Traits\SoftDeleteTrait;
- use Carbon\CarbonImmutable;
- use Exception;
- use NumberFormatter;
- use RuntimeException;
- /**
- * @property int $id
- * @property int $company_id Company issuing this document
- * @property int $user_id User who created this document
- * @property int $sale_id Sale that this document relates to
- * @property int $supplier_id Used for goods-in documents
- * @property int $location_id
- * @property int $related_document_id Used to link a delivery note to an invoice
- * @property int $type
- * @property int $invoice_status
- * @property int $aru_status
- * @property string $currency
- * @property string $tax_rate
- * @property string $billing_address
- * @property string $delivery_address
- * @property int $number
- * @property string $date
- * @property string $po_number Used for invoices
- * @property string $terms Used for invoices
- * @property string $vat_number Used for commercial invoices
- * @property string $delivery_company
- * @property string $tracking_number
- * @property string $delivery_cost
- * @property string $notes
- * @property string $contact_name
- * @property string $contact_phone
- * @property string $contact_email
- * @property string $dts_finalised
- * @property string $dts_paid
- */
- class Document extends Model {
- protected static $table = "document";
- protected static $idField = "id";
- protected static $fillableFields = [
- "company_id", "user_id", "sale_id", "supplier_id", "location_id", "related_document_id",
- "type",
- "invoice_status", "aru_status",
- "currency", "tax_rate",
- "billing_address", "delivery_address",
- "number", "date", "po_number", "terms", "vat_number",
- "delivery_company", "tracking_number", "delivery_cost",
- "notes",
- "contact_name", "contact_phone", "contact_email",
- "dts_finalised", "dts_paid",
- "dts_created", "dts_updated", "dts_deleted"
- ];
- use DateTimeTrait;
- use SoftDeleteTrait;
- // Static methods
- /**
- * @param int $document_type
- * @return int
- * @throws Exception
- */
- public static function getNextNumber(int $document_type): int {
- $document = self::queryOne(["type" => $document_type], ["sort" => "id", "order" => "desc"]);
- if($document) {
- return $document->number + 1;
- }
- return 1000;
- }
- /**
- * @param int $number
- * @param int $document_type
- * @return Document|null
- * @throws Exception
- */
- public static function getByNumber(int $number, int $document_type): ?Document {
- return self::queryOne([
- "type" => $document_type,
- "number" => $number,
- "dts_deleted" => null
- ]);
- }
- // Object methods
- /**
- * @return Company|null
- * @throws Exception
- */
- public function getCompany(): ?Company {
- return Company::get($this->company_id);
- }
- /**
- * @return Sale|null
- * @throws Exception
- */
- public function getSale(): ?Sale {
- return Sale::get($this->sale_id);
- }
- /**
- * @return Supplier|null
- * @throws Exception
- */
- public function getSupplier(): ?Supplier {
- return Supplier::get($this->supplier_id);
- }
- /**
- * @return Location|null
- * @throws Exception
- */
- public function getLocation(): ?Location {
- return Location::get($this->location_id);
- }
- public function getReference(): string {
- switch($this->getType()) {
- case DocumentTypes::GOODS_IN:
- return "G" . $this->number;
- case DocumentTypes::ADVANCE_REPLACEMENT_UNIT:
- return "A" . $this->number;
- case DocumentTypes::SALES_ORDER:
- return "S" . $this->number;
- case DocumentTypes::DELIVERY_NOTE:
- return "D" . $this->number;
- default:
- return $this->number;
- }
- }
- /**
- * @return string
- * @throws Exception
- */
- public function getUrl(): string {
- if($this->isSalesOrder()) {
- // Lead Sales Order
- /** @var Sale $sale */
- $sale = $this->getSale();
- if($sale) {
- return sprintf("%s/sales-orders/%s", $sale->getUrl(), $this->number);
- }
- // ARU Sales Order
- $document = $this->getRelatedDocument();
- if($document) {
- if($document->isAru()) {
- return sprintf("%s/sales-orders/%s", $document->getUrl(), $this->number);
- }
- }
- }
- if($this->isDeliveryNote()) {
- // Sale delivery note
- $sale = $this->getSale();
- if($sale) {
- return sprintf("%s/delivery-notes/%s", $sale->getUrl(), $this->number);
- }
- // ARU delivery note
- $document = $this->getRelatedDocument();
- if($document) {
- if($document->isAru()) {
- return sprintf("%s/delivery-notes/%s", $document->getUrl(), $this->number);
- }
- }
- }
- if($this->isGoodsIn()) {
- return sprintf("/goods-in/%s", $this->number);
- }
- if($this->isAru()) {
- return sprintf("/arus/%s", $this->number);
- }
- throw new RuntimeException(__("Unimplemented getUrl for document type: $this->type"));
- }
- public function isSalesOrder(): bool {
- return (int) $this->type === DocumentTypes::SALES_ORDER;
- }
- public function isDeliveryNote(): bool {
- return (int) $this->type === DocumentTypes::DELIVERY_NOTE;
- }
- public function isGoodsIn(): bool {
- return (int) $this->type === DocumentTypes::GOODS_IN;
- }
- public function getDisplaySalesOrderStatus(): string {
- return SalesOrderStatuses::enumToText($this->invoice_status);
- }
- public function getDisplayAruStatus(): string {
- return AruStatuses::enumToText($this->aru_status);
- }
- public function getDisplaySubtotal(): string {
- return (new NumberFormatter("en_GB", NumberFormatter::CURRENCY))->formatCurrency($this->getSubtotal(), $this->currency);
- }
- public function getDisplayTax(): string {
- return (new NumberFormatter("en_GB", NumberFormatter::CURRENCY))->formatCurrency($this->getTax(), $this->currency);
- }
- public function getDisplayTotal(): string {
- $formatter = new NumberFormatter("en_GB", NumberFormatter::CURRENCY);
- $subtotal = $this->getSubtotal();
- $tax = $this->getTax();
- $total = bcadd($subtotal, $tax, 2);
- return $formatter->formatCurrency($total, $this->currency);
- }
- /**
- * @return DocumentItem[]
- */
- public function getItems(array $nvp = []): array {
- $nvp = array_merge($nvp, [
- "document_id" => $this->id,
- "dts_deleted" => null
- ]);
- return DocumentItem::query($nvp);
- }
- public function getTitle(): string {
- return __("%s %d", $this->getDisplayType(), $this->number);
- }
- /**
- * @return Document|null
- * @throws Exception
- */
- public function getRelatedDocument(): ?Document {
- return self::get($this->related_document_id);
- }
- /**
- * @return User
- * @throws Exception
- */
- public function getUser(): User {
- return User::get($this->user_id);
- }
- public function getType(): int {
- return $this->type;
- }
- public function isCreditNote(): bool {
- return $this->type === DocumentTypes::CREDIT_NOTE;
- }
- public function getDisplayType(): string {
- return DocumentTypes::enumToText($this->type);
- }
- public function getBillingAddressHtml(): string {
- return nl2br(htmlspecialchars($this->billing_address));
- }
- public function getDeliveryAddressHtml(): string {
- return nl2br(htmlspecialchars($this->delivery_address));
- }
- public function getAccessToken(): string {
- return sha1($this->dts_created . $this->number);
- }
- public function getPdfFilename(): string {
- $type_slug = Util::slug($this->getDisplayType());
- return sprintf("%s-%d.pdf", $type_slug, $this->number);
- }
- /**
- * @param string $variant
- * @return string
- * @throws Exception
- */
- public function getDownloadPdfUrl(string $variant = ""): string {
- return sprintf("%s/download-pdf?access_token=%s&variant=%s", $this->getUrl(), $this->getAccessToken(), $variant);
- }
- public function isAru(): bool {
- return $this->getType() === DocumentTypes::ADVANCE_REPLACEMENT_UNIT;
- }
- public function hasCosts(): bool {
- return ($this->isSalesOrder() || $this->isAru());
- }
- /**
- * Get delivery notes related to this invoice or ARU
- * @return Document[]
- */
- public function getDeliveryNotes(): array {
- return self::query([
- "type" => DocumentTypes::DELIVERY_NOTE,
- "related_document_id" => $this->id,
- "dts_deleted" => null
- ]);
- }
- /**
- * Get invoices related to this ARU
- * @return Document[]
- */
- public function getSalesOrders(): array {
- return self::query([
- "type" => DocumentTypes::SALES_ORDER,
- "related_document_id" => $this->id,
- "dts_deleted" => null
- ]);
- }
- /**
- * @return bool
- * @throws Exception
- */
- public function isPartOfAru(): bool {
- $related = $this->getRelatedDocument();
- return $related && $related->isAru();
- }
- /**
- * @return Document[]
- */
- public function getGoodsInDocuments(): array {
- return self::query([
- "type" => DocumentTypes::GOODS_IN,
- "related_document_id" => $this->id,
- "dts_deleted" => null
- ]);
- }
- public function getDisplayDate(string $format = "d/m/Y"): string {
- return CarbonImmutable::parse($this->date)->format($format);
- }
- public function getSubtotal(): string {
- $subtotal = "0.00";
- foreach($this->getItems() as $item) {
- $subtotal = bcadd($subtotal, $item->getAmount(), 2);
- }
- return $subtotal;
- }
- public function getTax(): string {
- return bcmul($this->getSubtotal(), $this->tax_rate / 100, 2);
- }
- public function getNotesHtml(): string {
- return nl2br(htmlspecialchars($this->notes));
- }
- /**
- * @return Ticket[]
- */
- public function getTickets(): array {
- return Ticket::query([
- "aru_document_id" => $this->id,
- "dts_deleted" => null
- ]);
- }
- /**
- * @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;
- }
- /**
- * @return $this
- * @throws Exception
- */
- public function getRootDocument(): Document {
- $related_document = $this->getRelatedDocument();
- if($related_document) {
- return $related_document->getRootDocument();
- }
- return $this;
- }
- /**
- * @return Document[]
- */
- public function getChildDocuments(): array {
- return self::query([
- "related_document_id" => $this->id,
- "dts_deleted" => null
- ], [
- "sort" => "type",
- ]);
- }
- /**
- * @return Product[]
- * @throws Exception
- */
- public function getProducts(): array {
- $products = [];
- foreach($this->getItems(["product_id" => new NotNullConstraint()]) as $item) {
- $products[$item->product_id] = $item->getProduct();
- }
- return array_values($products);
- }
- }
|