Document.php 10 KB

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