You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Invoice.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\MoneyCast;
  4. use App\Casts\RateCast;
  5. use App\Collections\Accounting\InvoiceCollection;
  6. use App\Concerns\Blamable;
  7. use App\Concerns\CompanyOwned;
  8. use App\Enums\Accounting\AdjustmentComputation;
  9. use App\Enums\Accounting\DocumentDiscountMethod;
  10. use App\Enums\Accounting\InvoiceStatus;
  11. use App\Enums\Accounting\JournalEntryType;
  12. use App\Enums\Accounting\TransactionType;
  13. use App\Filament\Company\Resources\Sales\InvoiceResource;
  14. use App\Models\Common\Client;
  15. use App\Observers\InvoiceObserver;
  16. use App\Utilities\Currency\CurrencyConverter;
  17. use Filament\Actions\Action;
  18. use Filament\Actions\MountableAction;
  19. use Filament\Actions\ReplicateAction;
  20. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  21. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  22. use Illuminate\Database\Eloquent\Builder;
  23. use Illuminate\Database\Eloquent\Casts\Attribute;
  24. use Illuminate\Database\Eloquent\Factories\HasFactory;
  25. use Illuminate\Database\Eloquent\Model;
  26. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  27. use Illuminate\Database\Eloquent\Relations\MorphMany;
  28. use Illuminate\Database\Eloquent\Relations\MorphOne;
  29. use Illuminate\Support\Carbon;
  30. #[ObservedBy(InvoiceObserver::class)]
  31. #[CollectedBy(InvoiceCollection::class)]
  32. class Invoice extends Model
  33. {
  34. use Blamable;
  35. use CompanyOwned;
  36. use HasFactory;
  37. protected $table = 'invoices';
  38. protected $fillable = [
  39. 'company_id',
  40. 'client_id',
  41. 'logo',
  42. 'header',
  43. 'subheader',
  44. 'invoice_number',
  45. 'order_number',
  46. 'date',
  47. 'due_date',
  48. 'approved_at',
  49. 'paid_at',
  50. 'last_sent',
  51. 'status',
  52. 'currency_code',
  53. 'discount_method',
  54. 'discount_computation',
  55. 'discount_rate',
  56. 'subtotal',
  57. 'tax_total',
  58. 'discount_total',
  59. 'total',
  60. 'amount_paid',
  61. 'terms',
  62. 'footer',
  63. 'created_by',
  64. 'updated_by',
  65. ];
  66. protected $casts = [
  67. 'date' => 'date',
  68. 'due_date' => 'date',
  69. 'approved_at' => 'datetime',
  70. 'paid_at' => 'datetime',
  71. 'last_sent' => 'datetime',
  72. 'status' => InvoiceStatus::class,
  73. 'discount_method' => DocumentDiscountMethod::class,
  74. 'discount_computation' => AdjustmentComputation::class,
  75. 'discount_rate' => RateCast::class,
  76. 'subtotal' => MoneyCast::class,
  77. 'tax_total' => MoneyCast::class,
  78. 'discount_total' => MoneyCast::class,
  79. 'total' => MoneyCast::class,
  80. 'amount_paid' => MoneyCast::class,
  81. 'amount_due' => MoneyCast::class,
  82. ];
  83. public function client(): BelongsTo
  84. {
  85. return $this->belongsTo(Client::class);
  86. }
  87. public function lineItems(): MorphMany
  88. {
  89. return $this->morphMany(DocumentLineItem::class, 'documentable');
  90. }
  91. public function transactions(): MorphMany
  92. {
  93. return $this->morphMany(Transaction::class, 'transactionable');
  94. }
  95. public function payments(): MorphMany
  96. {
  97. return $this->transactions()->where('is_payment', true);
  98. }
  99. public function deposits(): MorphMany
  100. {
  101. return $this->transactions()->where('type', TransactionType::Deposit)->where('is_payment', true);
  102. }
  103. public function withdrawals(): MorphMany
  104. {
  105. return $this->transactions()->where('type', TransactionType::Withdrawal)->where('is_payment', true);
  106. }
  107. public function approvalTransaction(): MorphOne
  108. {
  109. return $this->morphOne(Transaction::class, 'transactionable')
  110. ->where('type', TransactionType::Journal);
  111. }
  112. public function scopeUnpaid(Builder $query): Builder
  113. {
  114. return $query->whereNotIn('status', [
  115. InvoiceStatus::Paid,
  116. InvoiceStatus::Void,
  117. InvoiceStatus::Draft,
  118. InvoiceStatus::Overpaid,
  119. ]);
  120. }
  121. protected function isCurrentlyOverdue(): Attribute
  122. {
  123. return Attribute::get(function () {
  124. return $this->due_date->isBefore(today()) && $this->canBeOverdue();
  125. });
  126. }
  127. public function isDraft(): bool
  128. {
  129. return $this->status === InvoiceStatus::Draft;
  130. }
  131. public function canRecordPayment(): bool
  132. {
  133. return ! in_array($this->status, [
  134. InvoiceStatus::Draft,
  135. InvoiceStatus::Paid,
  136. InvoiceStatus::Void,
  137. ]);
  138. }
  139. public function canBulkRecordPayment(): bool
  140. {
  141. return ! in_array($this->status, [
  142. InvoiceStatus::Draft,
  143. InvoiceStatus::Paid,
  144. InvoiceStatus::Void,
  145. InvoiceStatus::Overpaid,
  146. ]);
  147. }
  148. public function canBeOverdue(): bool
  149. {
  150. return in_array($this->status, InvoiceStatus::canBeOverdue());
  151. }
  152. public function hasPayments(): bool
  153. {
  154. return $this->payments->isNotEmpty();
  155. }
  156. public static function getNextDocumentNumber(): string
  157. {
  158. $company = auth()->user()->currentCompany;
  159. if (! $company) {
  160. throw new \RuntimeException('No current company is set for the user.');
  161. }
  162. $defaultInvoiceSettings = $company->defaultInvoice;
  163. $numberPrefix = $defaultInvoiceSettings->number_prefix;
  164. $numberDigits = $defaultInvoiceSettings->number_digits;
  165. $latestDocument = static::query()
  166. ->whereNotNull('invoice_number')
  167. ->latest('invoice_number')
  168. ->first();
  169. $lastNumberNumericPart = $latestDocument
  170. ? (int) substr($latestDocument->invoice_number, strlen($numberPrefix))
  171. : 0;
  172. $numberNext = $lastNumberNumericPart + 1;
  173. return $defaultInvoiceSettings->getNumberNext(
  174. padded: true,
  175. format: true,
  176. prefix: $numberPrefix,
  177. digits: $numberDigits,
  178. next: $numberNext
  179. );
  180. }
  181. public function recordPayment(array $data): void
  182. {
  183. $isRefund = $this->status === InvoiceStatus::Overpaid;
  184. if ($isRefund) {
  185. $transactionType = TransactionType::Withdrawal;
  186. $transactionDescription = "Invoice #{$this->invoice_number}: Refund to {$this->client->name}";
  187. } else {
  188. $transactionType = TransactionType::Deposit;
  189. $transactionDescription = "Invoice #{$this->invoice_number}: Payment from {$this->client->name}";
  190. }
  191. // Create transaction
  192. $this->transactions()->create([
  193. 'company_id' => $this->company_id,
  194. 'type' => $transactionType,
  195. 'is_payment' => true,
  196. 'posted_at' => $data['posted_at'],
  197. 'amount' => $data['amount'],
  198. 'payment_method' => $data['payment_method'],
  199. 'bank_account_id' => $data['bank_account_id'],
  200. 'account_id' => Account::getAccountsReceivableAccount()->id,
  201. 'description' => $transactionDescription,
  202. 'notes' => $data['notes'] ?? null,
  203. ]);
  204. }
  205. public function approveDraft(?Carbon $approvedAt = null): void
  206. {
  207. if (! $this->isDraft()) {
  208. throw new \RuntimeException('Invoice is not in draft status.');
  209. }
  210. $this->createApprovalTransaction();
  211. $approvedAt ??= now();
  212. $this->update([
  213. 'approved_at' => $approvedAt,
  214. 'status' => InvoiceStatus::Unsent,
  215. ]);
  216. }
  217. public function createApprovalTransaction(): void
  218. {
  219. $transaction = $this->transactions()->create([
  220. 'company_id' => $this->company_id,
  221. 'type' => TransactionType::Journal,
  222. 'posted_at' => $this->date,
  223. 'amount' => $this->total,
  224. 'description' => 'Invoice Approval for Invoice #' . $this->invoice_number,
  225. ]);
  226. $baseDescription = "{$this->client->name}: Invoice #{$this->invoice_number}";
  227. $transaction->journalEntries()->create([
  228. 'company_id' => $this->company_id,
  229. 'type' => JournalEntryType::Debit,
  230. 'account_id' => Account::getAccountsReceivableAccount()->id,
  231. 'amount' => $this->total,
  232. 'description' => $baseDescription,
  233. ]);
  234. $totalLineItemSubtotal = (int) $this->lineItems()->sum('subtotal');
  235. $invoiceDiscountTotalCents = (int) $this->getRawOriginal('discount_total');
  236. $remainingDiscountCents = $invoiceDiscountTotalCents;
  237. foreach ($this->lineItems as $index => $lineItem) {
  238. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  239. $transaction->journalEntries()->create([
  240. 'company_id' => $this->company_id,
  241. 'type' => JournalEntryType::Credit,
  242. 'account_id' => $lineItem->offering->income_account_id,
  243. 'amount' => $lineItem->subtotal,
  244. 'description' => $lineItemDescription,
  245. ]);
  246. foreach ($lineItem->adjustments as $adjustment) {
  247. $transaction->journalEntries()->create([
  248. 'company_id' => $this->company_id,
  249. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  250. 'account_id' => $adjustment->account_id,
  251. 'amount' => $lineItem->calculateAdjustmentTotal($adjustment)->getAmount(),
  252. 'description' => $lineItemDescription,
  253. ]);
  254. }
  255. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotal > 0) {
  256. $lineItemSubtotalCents = (int) $lineItem->getRawOriginal('subtotal');
  257. if ($index === $this->lineItems->count() - 1) {
  258. $lineItemDiscount = $remainingDiscountCents;
  259. } else {
  260. $lineItemDiscount = (int) round(
  261. ($lineItemSubtotalCents / $totalLineItemSubtotal) * $invoiceDiscountTotalCents
  262. );
  263. $remainingDiscountCents -= $lineItemDiscount;
  264. }
  265. if ($lineItemDiscount > 0) {
  266. $transaction->journalEntries()->create([
  267. 'company_id' => $this->company_id,
  268. 'type' => JournalEntryType::Debit,
  269. 'account_id' => Account::getSalesDiscountAccount()->id,
  270. 'amount' => CurrencyConverter::convertCentsToFormatSimple($lineItemDiscount),
  271. 'description' => "{$lineItemDescription} (Proportional Discount)",
  272. ]);
  273. }
  274. }
  275. }
  276. }
  277. public function updateApprovalTransaction(): void
  278. {
  279. $transaction = $this->approvalTransaction;
  280. if ($transaction) {
  281. $transaction->delete();
  282. }
  283. $this->createApprovalTransaction();
  284. }
  285. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  286. {
  287. return $action::make('approveDraft')
  288. ->label('Approve')
  289. ->icon('heroicon-o-check-circle')
  290. ->visible(function (self $record) {
  291. return $record->isDraft();
  292. })
  293. ->databaseTransaction()
  294. ->successNotificationTitle('Invoice Approved')
  295. ->action(function (self $record, MountableAction $action) {
  296. $record->approveDraft();
  297. $action->success();
  298. });
  299. }
  300. public static function getMarkAsSentAction(string $action = Action::class): MountableAction
  301. {
  302. return $action::make('markAsSent')
  303. ->label('Mark as Sent')
  304. ->icon('heroicon-o-paper-airplane')
  305. ->visible(static function (self $record) {
  306. return ! $record->last_sent;
  307. })
  308. ->successNotificationTitle('Invoice Sent')
  309. ->action(function (self $record, MountableAction $action) {
  310. $record->update([
  311. 'status' => InvoiceStatus::Sent,
  312. 'last_sent' => now(),
  313. ]);
  314. $action->success();
  315. });
  316. }
  317. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  318. {
  319. return $action::make()
  320. ->excludeAttributes([
  321. 'status',
  322. 'amount_paid',
  323. 'amount_due',
  324. 'created_by',
  325. 'updated_by',
  326. 'created_at',
  327. 'updated_at',
  328. 'invoice_number',
  329. 'date',
  330. 'due_date',
  331. 'approved_at',
  332. 'paid_at',
  333. 'last_sent',
  334. ])
  335. ->modal(false)
  336. ->beforeReplicaSaved(function (self $original, self $replica) {
  337. $replica->status = InvoiceStatus::Draft;
  338. $replica->invoice_number = self::getNextDocumentNumber();
  339. $replica->date = now();
  340. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  341. })
  342. ->databaseTransaction()
  343. ->after(function (self $original, self $replica) {
  344. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  345. $replicaLineItem = $lineItem->replicate([
  346. 'documentable_id',
  347. 'documentable_type',
  348. 'subtotal',
  349. 'total',
  350. 'created_by',
  351. 'updated_by',
  352. 'created_at',
  353. 'updated_at',
  354. ]);
  355. $replicaLineItem->documentable_id = $replica->id;
  356. $replicaLineItem->documentable_type = $replica->getMorphClass();
  357. $replicaLineItem->save();
  358. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  359. });
  360. })
  361. ->successRedirectUrl(static function (self $replica) {
  362. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  363. });
  364. }
  365. }