Document.php 11 KB

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