Document.php 10 KB

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