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

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