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 12KB

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