Document.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. <?php
  2. namespace App;
  3. use App\Enums\AruStatuses;
  4. use App\Enums\DocumentTypes;
  5. use App\Enums\SalesOrderStatuses;
  6. use App\Traits\DateTimeTrait;
  7. use App\Traits\SoftDeleteTrait;
  8. use Carbon\CarbonImmutable;
  9. use Exception;
  10. use NumberFormatter;
  11. use RuntimeException;
  12. /**
  13. * @property int $id
  14. * @property int $company_id Company issuing this document
  15. * @property int $user_id User who created this document
  16. * @property int $sale_id Sale that this document relates to
  17. * @property int $supplier_id Used for goods-in documents
  18. * @property int $location_id
  19. * @property int $related_document_id Used to link a delivery note to an invoice
  20. * @property int $type
  21. * @property int $invoice_status
  22. * @property int $aru_status
  23. * @property string $currency
  24. * @property string $tax_rate
  25. * @property string $billing_address
  26. * @property string $delivery_address
  27. * @property int $number
  28. * @property string $date
  29. * @property string $po_number Used for invoices
  30. * @property string $terms Used for invoices
  31. * @property string $vat_number Used for commercial invoices
  32. * @property string $delivery_company
  33. * @property string $tracking_number
  34. * @property string $delivery_cost
  35. * @property string $notes
  36. * @property string $contact_name
  37. * @property string $contact_phone
  38. * @property string $contact_email
  39. * @property string $dts_finalised
  40. * @property string $dts_paid
  41. */
  42. class Document extends Model {
  43. protected static $table = "document";
  44. protected static $idField = "id";
  45. protected static $fillableFields = [
  46. "company_id", "user_id", "sale_id", "supplier_id", "location_id", "related_document_id",
  47. "type",
  48. "invoice_status", "aru_status",
  49. "currency", "tax_rate",
  50. "billing_address", "delivery_address",
  51. "number", "date", "po_number", "terms", "vat_number",
  52. "delivery_company", "tracking_number", "delivery_cost",
  53. "notes",
  54. "contact_name", "contact_phone", "contact_email",
  55. "dts_finalised", "dts_paid",
  56. "dts_created", "dts_updated", "dts_deleted"
  57. ];
  58. use DateTimeTrait;
  59. use SoftDeleteTrait;
  60. // Static methods
  61. /**
  62. * @param int $document_type
  63. * @return int
  64. * @throws Exception
  65. */
  66. public static function getNextNumber(int $document_type): int {
  67. $document = self::queryOne(["type" => $document_type], ["sort" => "id", "order" => "desc"]);
  68. if($document) {
  69. return $document->number + 1;
  70. }
  71. return 1000;
  72. }
  73. /**
  74. * @param int $number
  75. * @param int $document_type
  76. * @return Document|null
  77. * @throws Exception
  78. */
  79. public static function getByNumber(int $number, int $document_type): ?Document {
  80. return self::queryOne([
  81. "type" => $document_type,
  82. "number" => $number,
  83. "dts_deleted" => null
  84. ]);
  85. }
  86. // Object methods
  87. /**
  88. * @return Company|null
  89. * @throws Exception
  90. */
  91. public function getCompany(): ?Company {
  92. return Company::get($this->company_id);
  93. }
  94. /**
  95. * @return Sale|null
  96. * @throws Exception
  97. */
  98. public function getSale(): ?Sale {
  99. return Sale::get($this->sale_id);
  100. }
  101. /**
  102. * @return Supplier|null
  103. * @throws Exception
  104. */
  105. public function getSupplier(): ?Supplier {
  106. return Supplier::get($this->supplier_id);
  107. }
  108. /**
  109. * @return Location|null
  110. * @throws Exception
  111. */
  112. public function getLocation(): ?Location {
  113. return Location::get($this->location_id);
  114. }
  115. /**
  116. * @return string
  117. * @throws Exception
  118. */
  119. public function getUrl(): string {
  120. if($this->isSalesOrder()) {
  121. // Lead Sales Order
  122. /** @var Sale $sale */
  123. $sale = $this->getSale();
  124. if($sale) {
  125. return sprintf("%s/sales-orders/%s", $sale->getUrl(), $this->number);
  126. }
  127. // ARU Sales Order
  128. $document = $this->getRelatedDocument();
  129. if($document) {
  130. if($document->isAru()) {
  131. return sprintf("%s/sales-orders/%s", $document->getUrl(), $this->number);
  132. }
  133. }
  134. }
  135. if($this->isDeliveryNote()) {
  136. // Sale delivery note
  137. $sale = $this->getSale();
  138. if($sale) {
  139. return sprintf("%s/delivery-notes/%s", $sale->getUrl(), $this->number);
  140. }
  141. // ARU delivery note
  142. $document = $this->getRelatedDocument();
  143. if($document) {
  144. if($document->isAru()) {
  145. return sprintf("%s/delivery-notes/%s", $document->getUrl(), $this->number);
  146. }
  147. }
  148. }
  149. if($this->isGoodsIn()) {
  150. return sprintf("/goods-in/%s", $this->number);
  151. }
  152. if($this->isAru()) {
  153. return sprintf("/arus/%s", $this->number);
  154. }
  155. throw new RuntimeException(__("Unimplemented getUrl for document type: $this->type"));
  156. }
  157. public function isSalesOrder(): bool {
  158. return (int) $this->type === DocumentTypes::SALES_ORDER;
  159. }
  160. public function isDeliveryNote(): bool {
  161. return (int) $this->type === DocumentTypes::DELIVERY_NOTE;
  162. }
  163. public function isGoodsIn(): bool {
  164. return (int) $this->type === DocumentTypes::GOODS_IN;
  165. }
  166. public function getDisplaySalesOrderStatus(): string {
  167. return SalesOrderStatuses::enumToText($this->invoice_status);
  168. }
  169. public function getDisplayAruStatus(): string {
  170. return AruStatuses::enumToText($this->aru_status);
  171. }
  172. public function getDisplaySubtotal(): string {
  173. return (new NumberFormatter("en_GB", NumberFormatter::CURRENCY))->formatCurrency($this->getSubtotal(), $this->currency);
  174. }
  175. public function getDisplayTax(): string {
  176. return (new NumberFormatter("en_GB", NumberFormatter::CURRENCY))->formatCurrency($this->getTax(), $this->currency);
  177. }
  178. public function getDisplayTotal(): string {
  179. $formatter = new NumberFormatter("en_GB", NumberFormatter::CURRENCY);
  180. $subtotal = $this->getSubtotal();
  181. $tax = $this->getTax();
  182. $total = bcadd($subtotal, $tax, 2);
  183. return $formatter->formatCurrency($total, $this->currency);
  184. }
  185. /**
  186. * @return DocumentItem[]
  187. */
  188. public function getItems(array $nvp = []): array {
  189. $nvp = array_merge($nvp, [
  190. "document_id" => $this->id,
  191. "dts_deleted" => null
  192. ]);
  193. return DocumentItem::query($nvp);
  194. }
  195. public function getTitle(): string {
  196. return __("%s %d", $this->getDisplayType(), $this->number);
  197. }
  198. /**
  199. * @return Document|null
  200. * @throws Exception
  201. */
  202. public function getRelatedDocument(): ?Document {
  203. return self::get($this->related_document_id);
  204. }
  205. /**
  206. * @return User
  207. * @throws Exception
  208. */
  209. public function getUser(): User {
  210. return User::get($this->user_id);
  211. }
  212. public function getType(): int {
  213. return $this->type;
  214. }
  215. public function isCreditNote(): bool {
  216. return $this->type === DocumentTypes::CREDIT_NOTE;
  217. }
  218. public function getDisplayType(): string {
  219. return DocumentTypes::enumToText($this->type);
  220. }
  221. public function getBillingAddressHtml(): string {
  222. return nl2br(htmlspecialchars($this->billing_address));
  223. }
  224. public function getDeliveryAddressHtml(): string {
  225. return nl2br(htmlspecialchars($this->delivery_address));
  226. }
  227. public function getAccessToken(): string {
  228. return sha1($this->dts_created . $this->number);
  229. }
  230. public function getPdfFilename(): string {
  231. $type_slug = Util::slug($this->getDisplayType());
  232. return sprintf("%s-%d.pdf", $type_slug, $this->number);
  233. }
  234. /**
  235. * @param string $variant
  236. * @return string
  237. * @throws Exception
  238. */
  239. public function getDownloadPdfUrl(string $variant = ""): string {
  240. return sprintf("%s/download-pdf?access_token=%s&variant=%s", $this->getUrl(), $this->getAccessToken(), $variant);
  241. }
  242. public function isAru(): bool {
  243. return $this->getType() === DocumentTypes::ADVANCE_REPLACEMENT_UNIT;
  244. }
  245. public function hasCosts(): bool {
  246. return ($this->isSalesOrder() || $this->isAru());
  247. }
  248. /**
  249. * Get delivery notes related to this invoice or ARU
  250. * @return Document[]
  251. */
  252. public function getDeliveryNotes(): array {
  253. return self::query([
  254. "type" => DocumentTypes::DELIVERY_NOTE,
  255. "related_document_id" => $this->id,
  256. "dts_deleted" => null
  257. ]);
  258. }
  259. /**
  260. * Get invoices related to this ARU
  261. * @return Document[]
  262. */
  263. public function getSalesOrders(): array {
  264. return self::query([
  265. "type" => DocumentTypes::SALES_ORDER,
  266. "related_document_id" => $this->id,
  267. "dts_deleted" => null
  268. ]);
  269. }
  270. /**
  271. * @return bool
  272. * @throws Exception
  273. */
  274. public function isPartOfAru(): bool {
  275. $related = $this->getRelatedDocument();
  276. return $related && $related->isAru();
  277. }
  278. /**
  279. * @return Document[]
  280. */
  281. public function getGoodsInDocuments(): array {
  282. return self::query([
  283. "type" => DocumentTypes::GOODS_IN,
  284. "related_document_id" => $this->id,
  285. "dts_deleted" => null
  286. ]);
  287. }
  288. public function getDisplayDate(string $format = "d/m/Y"): string {
  289. return CarbonImmutable::parse($this->date)->format($format);
  290. }
  291. public function getSubtotal(): string {
  292. $subtotal = "0.00";
  293. foreach($this->getItems() as $item) {
  294. $subtotal = bcadd($subtotal, $item->getAmount(), 2);
  295. }
  296. return $subtotal;
  297. }
  298. public function getTax(): string {
  299. return bcmul($this->getSubtotal(), $this->tax_rate / 100, 2);
  300. }
  301. public function getNotesHtml(): string {
  302. return nl2br(htmlspecialchars($this->notes));
  303. }
  304. /**
  305. * @return Ticket[]
  306. */
  307. public function getTickets(): array {
  308. return Ticket::query([
  309. "aru_document_id" => $this->id,
  310. "dts_deleted" => null
  311. ]);
  312. }
  313. /**
  314. * @param string|null $variant
  315. * @return string
  316. * @throws Exception
  317. */
  318. public function generatePdf(?string $variant): string {
  319. $host = $_SERVER["HTTP_HOST"];
  320. $render_url = "https://" . $host . $this->getUrl() . "/render-pdf?" . http_build_query([
  321. "access_token" => $this->getAccessToken(),
  322. "variant" => $variant
  323. ]);
  324. chdir($_ENV["DIR_ROOT"]);
  325. $output_filename = $this->id . ".pdf";
  326. $output_path = "pdf-output/" . $output_filename;
  327. $command = sprintf('node pdf.js "%s" "%s"',
  328. $render_url,
  329. $output_filename
  330. );
  331. shell_exec($command);
  332. return $output_path;
  333. }
  334. /**
  335. * @return $this
  336. * @throws Exception
  337. */
  338. public function getRootDocument(): Document {
  339. $related_document = $this->getRelatedDocument();
  340. if($related_document) {
  341. return $related_document->getRootDocument();
  342. }
  343. return $this;
  344. }
  345. /**
  346. * @return Document[]
  347. */
  348. public function getChildDocuments(): array {
  349. return self::query([
  350. "related_document_id" => $this->id,
  351. "dts_deleted" => null
  352. ], [
  353. "sort" => "type",
  354. ]);
  355. }
  356. }