您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Invoice.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 static function getNextDocumentNumber(): string
  143. {
  144. $company = auth()->user()->currentCompany;
  145. if (! $company) {
  146. throw new \RuntimeException('No current company is set for the user.');
  147. }
  148. $defaultInvoiceSettings = $company->defaultInvoice;
  149. $numberPrefix = $defaultInvoiceSettings->number_prefix;
  150. $numberDigits = $defaultInvoiceSettings->number_digits;
  151. $latestDocument = static::query()
  152. ->whereNotNull('invoice_number')
  153. ->latest('invoice_number')
  154. ->first();
  155. $lastNumberNumericPart = $latestDocument
  156. ? (int) substr($latestDocument->invoice_number, strlen($numberPrefix))
  157. : 0;
  158. $numberNext = $lastNumberNumericPart + 1;
  159. return $defaultInvoiceSettings->getNumberNext(
  160. padded: true,
  161. format: true,
  162. prefix: $numberPrefix,
  163. digits: $numberDigits,
  164. next: $numberNext
  165. );
  166. }
  167. public function recordPayment(array $data): void
  168. {
  169. $isRefund = $this->status === InvoiceStatus::Overpaid;
  170. if ($isRefund) {
  171. $transactionType = TransactionType::Withdrawal;
  172. $transactionDescription = "Invoice #{$this->invoice_number}: Refund to {$this->client->name}";
  173. } else {
  174. $transactionType = TransactionType::Deposit;
  175. $transactionDescription = "Invoice #{$this->invoice_number}: Payment from {$this->client->name}";
  176. }
  177. // Create transaction
  178. $this->transactions()->create([
  179. 'company_id' => $this->company_id,
  180. 'type' => $transactionType,
  181. 'is_payment' => true,
  182. 'posted_at' => $data['posted_at'],
  183. 'amount' => $data['amount'],
  184. 'payment_method' => $data['payment_method'],
  185. 'bank_account_id' => $data['bank_account_id'],
  186. 'account_id' => Account::getAccountsReceivableAccount()->id,
  187. 'description' => $transactionDescription,
  188. 'notes' => $data['notes'] ?? null,
  189. ]);
  190. }
  191. public function approveDraft(?Carbon $approvedAt = null): void
  192. {
  193. if (! $this->isDraft()) {
  194. throw new \RuntimeException('Invoice is not in draft status.');
  195. }
  196. $this->createApprovalTransaction();
  197. $approvedAt ??= now();
  198. $this->update([
  199. 'approved_at' => $approvedAt,
  200. 'status' => InvoiceStatus::Unsent,
  201. ]);
  202. }
  203. public function createApprovalTransaction(): void
  204. {
  205. $transaction = $this->transactions()->create([
  206. 'company_id' => $this->company_id,
  207. 'type' => TransactionType::Journal,
  208. 'posted_at' => $this->date,
  209. 'amount' => $this->total,
  210. 'description' => 'Invoice Approval for Invoice #' . $this->invoice_number,
  211. ]);
  212. $baseDescription = "{$this->client->name}: Invoice #{$this->invoice_number}";
  213. $transaction->journalEntries()->create([
  214. 'company_id' => $this->company_id,
  215. 'type' => JournalEntryType::Debit,
  216. 'account_id' => Account::getAccountsReceivableAccount()->id,
  217. 'amount' => $this->total,
  218. 'description' => $baseDescription,
  219. ]);
  220. foreach ($this->lineItems as $lineItem) {
  221. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  222. $transaction->journalEntries()->create([
  223. 'company_id' => $this->company_id,
  224. 'type' => JournalEntryType::Credit,
  225. 'account_id' => $lineItem->offering->income_account_id,
  226. 'amount' => $lineItem->subtotal,
  227. 'description' => $lineItemDescription,
  228. ]);
  229. foreach ($lineItem->adjustments as $adjustment) {
  230. $transaction->journalEntries()->create([
  231. 'company_id' => $this->company_id,
  232. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  233. 'account_id' => $adjustment->account_id,
  234. 'amount' => $lineItem->calculateAdjustmentTotal($adjustment)->getAmount(),
  235. 'description' => $lineItemDescription,
  236. ]);
  237. }
  238. }
  239. }
  240. public function updateApprovalTransaction(): void
  241. {
  242. $transaction = $this->approvalTransaction;
  243. if ($transaction) {
  244. $transaction->delete();
  245. }
  246. $this->createApprovalTransaction();
  247. }
  248. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  249. {
  250. return $action::make('approveDraft')
  251. ->label('Approve')
  252. ->icon('heroicon-o-check-circle')
  253. ->visible(function (self $record) {
  254. return $record->isDraft();
  255. })
  256. ->databaseTransaction()
  257. ->successNotificationTitle('Invoice Approved')
  258. ->action(function (self $record, MountableAction $action) {
  259. $record->approveDraft();
  260. $action->success();
  261. });
  262. }
  263. public static function getMarkAsSentAction(string $action = Action::class): MountableAction
  264. {
  265. return $action::make('markAsSent')
  266. ->label('Mark as Sent')
  267. ->icon('heroicon-o-paper-airplane')
  268. ->visible(static function (self $record) {
  269. return ! $record->last_sent;
  270. })
  271. ->successNotificationTitle('Invoice Sent')
  272. ->action(function (self $record, MountableAction $action) {
  273. $record->update([
  274. 'status' => InvoiceStatus::Sent,
  275. 'last_sent' => now(),
  276. ]);
  277. $action->success();
  278. });
  279. }
  280. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  281. {
  282. return $action::make()
  283. ->excludeAttributes([
  284. 'status',
  285. 'amount_paid',
  286. 'amount_due',
  287. 'created_by',
  288. 'updated_by',
  289. 'created_at',
  290. 'updated_at',
  291. 'invoice_number',
  292. 'date',
  293. 'due_date',
  294. 'approved_at',
  295. 'paid_at',
  296. 'last_sent',
  297. ])
  298. ->modal(false)
  299. ->beforeReplicaSaved(function (self $original, self $replica) {
  300. $replica->status = InvoiceStatus::Draft;
  301. $replica->invoice_number = self::getNextDocumentNumber();
  302. $replica->date = now();
  303. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  304. })
  305. ->databaseTransaction()
  306. ->after(function (self $original, self $replica) {
  307. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  308. $replicaLineItem = $lineItem->replicate([
  309. 'documentable_id',
  310. 'documentable_type',
  311. 'subtotal',
  312. 'total',
  313. 'created_by',
  314. 'updated_by',
  315. 'created_at',
  316. 'updated_at',
  317. ]);
  318. $replicaLineItem->documentable_id = $replica->id;
  319. $replicaLineItem->documentable_type = $replica->getMorphClass();
  320. $replicaLineItem->save();
  321. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  322. });
  323. })
  324. ->successRedirectUrl(static function (self $replica) {
  325. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  326. });
  327. }
  328. }