Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Invoice.php 12KB

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