1
0

Document.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. return sprintf("/sales-orders/%s", $this->number);
  138. }
  139. if($this->isDeliveryNote()) {
  140. return sprintf("/delivery-notes/%s", $this->number);
  141. }
  142. if($this->isGoodsIn()) {
  143. return sprintf("/goods-in/%s", $this->number);
  144. }
  145. if($this->isAru()) {
  146. return sprintf("/arus/%s", $this->number);
  147. }
  148. throw new RuntimeException(__("Unimplemented getUrl for document type: $this->type"));
  149. }
  150. public function isSalesOrder(): bool {
  151. return (int) $this->type === DocumentTypes::SALES_ORDER;
  152. }
  153. public function isDeliveryNote(): bool {
  154. return (int) $this->type === DocumentTypes::DELIVERY_NOTE;
  155. }
  156. public function isGoodsIn(): bool {
  157. return (int) $this->type === DocumentTypes::GOODS_IN;
  158. }
  159. public function getDisplaySalesOrderStatus(): string {
  160. return SalesOrderStatuses::enumToText($this->invoice_status);
  161. }
  162. public function getDisplayAruStatus(): string {
  163. return AruStatuses::enumToText($this->aru_status);
  164. }
  165. public function getDisplaySubtotal(): string {
  166. return (new NumberFormatter("en_GB", NumberFormatter::CURRENCY))->formatCurrency($this->getSubtotal(), $this->currency);
  167. }
  168. public function getDisplayTax(): string {
  169. return (new NumberFormatter("en_GB", NumberFormatter::CURRENCY))->formatCurrency($this->getTax(), $this->currency);
  170. }
  171. public function getDisplayTotal(): string {
  172. $formatter = new NumberFormatter("en_GB", NumberFormatter::CURRENCY);
  173. $subtotal = $this->getSubtotal();
  174. $tax = $this->getTax();
  175. $total = bcadd($subtotal, $tax, 2);
  176. return $formatter->formatCurrency($total, $this->currency);
  177. }
  178. /**
  179. * @return DocumentItem[]
  180. */
  181. public function getItems(array $nvp = []): array {
  182. $nvp = array_merge($nvp, [
  183. "document_id" => $this->id,
  184. "dts_deleted" => null
  185. ]);
  186. return DocumentItem::query($nvp);
  187. }
  188. public function getTitle(): string {
  189. return __("%s %s", $this->getDisplayType(), $this->getReference());
  190. }
  191. /**
  192. * @return Document|null
  193. * @throws Exception
  194. */
  195. public function getRelatedDocument(): ?Document {
  196. return self::get($this->related_document_id);
  197. }
  198. /**
  199. * @return User
  200. * @throws Exception
  201. */
  202. public function getUser(): User {
  203. return User::get($this->user_id);
  204. }
  205. public function getType(): int {
  206. return $this->type;
  207. }
  208. public function isCreditNote(): bool {
  209. return $this->type === DocumentTypes::CREDIT_NOTE;
  210. }
  211. public function getDisplayType(): string {
  212. return DocumentTypes::enumToText($this->type);
  213. }
  214. public function getBillingAddressHtml(): string {
  215. return nl2br(htmlspecialchars($this->billing_address));
  216. }
  217. public function getDeliveryAddressHtml(): string {
  218. return nl2br(htmlspecialchars($this->delivery_address));
  219. }
  220. public function getAccessToken(): string {
  221. return sha1($this->dts_created . $this->number);
  222. }
  223. public function getPdfFilename(): string {
  224. $type_slug = Util::slug($this->getDisplayType());
  225. return sprintf("%s-%d.pdf", $type_slug, $this->number);
  226. }
  227. /**
  228. * @param string $variant
  229. * @return string
  230. * @throws Exception
  231. */
  232. public function getDownloadPdfUrl(string $variant = ""): string {
  233. return sprintf("%s/download-pdf?access_token=%s&variant=%s", $this->getUrl(), $this->getAccessToken(), $variant);
  234. }
  235. public function isAru(): bool {
  236. return $this->getType() === DocumentTypes::ADVANCE_REPLACEMENT_UNIT;
  237. }
  238. public function hasCosts(): bool {
  239. return ($this->isSalesOrder() || $this->isAru());
  240. }
  241. /**
  242. * Get delivery notes related to this invoice or ARU
  243. * @return Document[]
  244. */
  245. public function getDeliveryNotes(): array {
  246. return self::query([
  247. "type" => DocumentTypes::DELIVERY_NOTE,
  248. "related_document_id" => $this->id,
  249. "dts_deleted" => null
  250. ]);
  251. }
  252. /**
  253. * Get invoices related to this ARU
  254. * @return Document[]
  255. */
  256. public function getSalesOrders(): array {
  257. return self::query([
  258. "type" => DocumentTypes::SALES_ORDER,
  259. "related_document_id" => $this->id,
  260. "dts_deleted" => null
  261. ]);
  262. }
  263. /**
  264. * @return bool
  265. * @throws Exception
  266. */
  267. public function isPartOfAru(): bool {
  268. $related = $this->getRelatedDocument();
  269. return $related && $related->isAru();
  270. }
  271. /**
  272. * @return Document[]
  273. */
  274. public function getGoodsInDocuments(): array {
  275. return self::query([
  276. "type" => DocumentTypes::GOODS_IN,
  277. "related_document_id" => $this->id,
  278. "dts_deleted" => null
  279. ]);
  280. }
  281. public function getDisplayDate(string $format = "d/m/Y"): string {
  282. return CarbonImmutable::parse($this->date)->format($format);
  283. }
  284. public function getSubtotal(): string {
  285. $subtotal = "0.00";
  286. foreach($this->getItems() as $item) {
  287. $subtotal = bcadd($subtotal, $item->getAmount(), 2);
  288. }
  289. return $subtotal;
  290. }
  291. public function getTax(): string {
  292. return bcmul($this->getSubtotal(), $this->tax_rate / 100, 2);
  293. }
  294. public function getNotesHtml(): string {
  295. return nl2br(htmlspecialchars($this->notes));
  296. }
  297. /**
  298. * @return Ticket[]
  299. */
  300. public function getTickets(): array {
  301. return Ticket::query([
  302. "aru_document_id" => $this->id,
  303. "dts_deleted" => null
  304. ]);
  305. }
  306. /**
  307. * @param string|null $variant
  308. * @return string
  309. * @throws Exception
  310. */
  311. public function generatePdf(?string $variant): string {
  312. $host = $_SERVER["HTTP_HOST"];
  313. $render_url = "https://" . $host . $this->getUrl() . "/render-pdf?" . http_build_query([
  314. "access_token" => $this->getAccessToken(),
  315. "variant" => $variant
  316. ]);
  317. chdir($_ENV["DIR_ROOT"]);
  318. $output_filename = $this->id . ".pdf";
  319. $output_path = "pdf-output/" . $output_filename;
  320. $command = sprintf('node pdf.js "%s" "%s"',
  321. $render_url,
  322. $output_filename
  323. );
  324. shell_exec($command);
  325. return $output_path;
  326. }
  327. /**
  328. * @return $this
  329. * @throws Exception
  330. */
  331. public function getRootDocument(): Document {
  332. $related_document = $this->getRelatedDocument();
  333. if($related_document) {
  334. return $related_document->getRootDocument();
  335. }
  336. return $this;
  337. }
  338. /**
  339. * @return Document[]
  340. */
  341. public function getChildDocuments(): array {
  342. return self::query([
  343. "related_document_id" => $this->id,
  344. "dts_deleted" => null
  345. ], [
  346. "sort" => "type",
  347. ]);
  348. }
  349. /**
  350. * @return Product[]
  351. * @throws Exception
  352. */
  353. public function getProducts(): array {
  354. $products = [];
  355. foreach($this->getItems(["product_id" => new NotNullConstraint()]) as $item) {
  356. $products[$item->product_id] = $item->getProduct();
  357. }
  358. return array_values($products);
  359. }
  360. }