Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

InvoiceResource.php 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Enums\Accounting\InvoiceStatus;
  4. use App\Enums\Accounting\JournalEntryType;
  5. use App\Enums\Accounting\PaymentMethod;
  6. use App\Enums\Accounting\TransactionType;
  7. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  8. use App\Filament\Company\Resources\Sales\InvoiceResource\RelationManagers;
  9. use App\Models\Accounting\Account;
  10. use App\Models\Accounting\Adjustment;
  11. use App\Models\Accounting\DocumentLineItem;
  12. use App\Models\Accounting\Invoice;
  13. use App\Models\Banking\BankAccount;
  14. use App\Models\Common\Offering;
  15. use App\Utilities\Currency\CurrencyAccessor;
  16. use App\Utilities\Currency\CurrencyConverter;
  17. use Awcodes\TableRepeater\Components\TableRepeater;
  18. use Awcodes\TableRepeater\Header;
  19. use Carbon\CarbonInterface;
  20. use Closure;
  21. use Filament\Forms;
  22. use Filament\Forms\Components\FileUpload;
  23. use Filament\Forms\Form;
  24. use Filament\Resources\Resource;
  25. use Filament\Support\Enums\Alignment;
  26. use Filament\Support\Enums\MaxWidth;
  27. use Filament\Tables;
  28. use Filament\Tables\Table;
  29. use Illuminate\Database\Eloquent\Model;
  30. use Illuminate\Support\Carbon;
  31. use Illuminate\Support\Facades\Auth;
  32. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  33. class InvoiceResource extends Resource
  34. {
  35. protected static ?string $model = Invoice::class;
  36. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  37. public static function form(Form $form): Form
  38. {
  39. $company = Auth::user()->currentCompany;
  40. return $form
  41. ->schema([
  42. Forms\Components\Section::make('Invoice Header')
  43. ->collapsible()
  44. ->schema([
  45. Forms\Components\Split::make([
  46. Forms\Components\Group::make([
  47. FileUpload::make('logo')
  48. ->openable()
  49. ->maxSize(1024)
  50. ->localizeLabel()
  51. ->visibility('public')
  52. ->disk('public')
  53. ->directory('logos/document')
  54. ->imageResizeMode('contain')
  55. ->imageCropAspectRatio('3:2')
  56. ->panelAspectRatio('3:2')
  57. ->maxWidth(MaxWidth::ExtraSmall)
  58. ->panelLayout('integrated')
  59. ->removeUploadedFileButtonPosition('center bottom')
  60. ->uploadButtonPosition('center bottom')
  61. ->uploadProgressIndicatorPosition('center bottom')
  62. ->getUploadedFileNameForStorageUsing(
  63. static fn (TemporaryUploadedFile $file): string => (string) str($file->getClientOriginalName())
  64. ->prepend(Auth::user()->currentCompany->id . '_'),
  65. )
  66. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/gif']),
  67. ]),
  68. Forms\Components\Group::make([
  69. Forms\Components\TextInput::make('header')
  70. ->default(fn () => $company->defaultInvoice->header),
  71. Forms\Components\TextInput::make('subheader')
  72. ->default(fn () => $company->defaultInvoice->subheader),
  73. Forms\Components\View::make('filament.forms.components.company-info')
  74. ->viewData([
  75. 'company_name' => $company->name,
  76. 'company_address' => $company->profile->address,
  77. 'company_city' => $company->profile->city?->name,
  78. 'company_state' => $company->profile->state?->name,
  79. 'company_zip' => $company->profile->zip_code,
  80. 'company_country' => $company->profile->state?->country->name,
  81. ]),
  82. ])->grow(true),
  83. ])->from('md'),
  84. ]),
  85. Forms\Components\Section::make('Invoice Details')
  86. ->schema([
  87. Forms\Components\Split::make([
  88. Forms\Components\Group::make([
  89. Forms\Components\Select::make('client_id')
  90. ->relationship('client', 'name')
  91. ->preload()
  92. ->searchable()
  93. ->required(),
  94. ]),
  95. Forms\Components\Group::make([
  96. Forms\Components\TextInput::make('invoice_number')
  97. ->label('Invoice Number')
  98. ->default(fn () => Invoice::getNextDocumentNumber()),
  99. Forms\Components\TextInput::make('order_number')
  100. ->label('P.O/S.O Number'),
  101. Forms\Components\DatePicker::make('date')
  102. ->label('Invoice Date')
  103. ->default(now()),
  104. Forms\Components\DatePicker::make('due_date')
  105. ->label('Payment Due')
  106. ->default(function () use ($company) {
  107. return now()->addDays($company->defaultInvoice->payment_terms->getDays());
  108. }),
  109. ])->grow(true),
  110. ])->from('md'),
  111. TableRepeater::make('lineItems')
  112. ->relationship()
  113. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  114. if (! is_array($state)) {
  115. $state = [];
  116. }
  117. $relationship = $component->getRelationship();
  118. $existingRecords = $component->getCachedExistingRecords();
  119. $recordsToDelete = [];
  120. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  121. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  122. continue;
  123. }
  124. $recordsToDelete[] = $keyToCheckForDeletion;
  125. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  126. }
  127. $relationship
  128. ->whereKey($recordsToDelete)
  129. ->get()
  130. ->each(static fn (Model $record) => $record->delete());
  131. $childComponentContainers = $component->getChildComponentContainers(
  132. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  133. );
  134. $itemOrder = 1;
  135. $orderColumn = $component->getOrderColumn();
  136. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  137. foreach ($childComponentContainers as $itemKey => $item) {
  138. $itemData = $item->getState(shouldCallHooksBefore: false);
  139. if ($orderColumn) {
  140. $itemData[$orderColumn] = $itemOrder;
  141. $itemOrder++;
  142. }
  143. if ($record = ($existingRecords[$itemKey] ?? null)) {
  144. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  145. if ($itemData === null) {
  146. continue;
  147. }
  148. $translatableContentDriver ?
  149. $translatableContentDriver->updateRecord($record, $itemData) :
  150. $record->fill($itemData)->save();
  151. continue;
  152. }
  153. $relatedModel = $component->getRelatedModel();
  154. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  155. if ($itemData === null) {
  156. continue;
  157. }
  158. if ($translatableContentDriver) {
  159. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  160. } else {
  161. $record = new $relatedModel;
  162. $record->fill($itemData);
  163. }
  164. $record = $relationship->save($record);
  165. $item->model($record)->saveRelationships();
  166. $existingRecords->push($record);
  167. }
  168. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  169. /** @var Invoice $invoice */
  170. $invoice = $component->getRecord();
  171. // Recalculate totals for line items
  172. $invoice->lineItems()->each(function (DocumentLineItem $lineItem) {
  173. $lineItem->updateQuietly([
  174. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  175. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  176. ]);
  177. });
  178. $subtotal = $invoice->lineItems()->sum('subtotal') / 100;
  179. $taxTotal = $invoice->lineItems()->sum('tax_total') / 100;
  180. $discountTotal = $invoice->lineItems()->sum('discount_total') / 100;
  181. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  182. $invoice->updateQuietly([
  183. 'subtotal' => $subtotal,
  184. 'tax_total' => $taxTotal,
  185. 'discount_total' => $discountTotal,
  186. 'total' => $grandTotal,
  187. ]);
  188. })
  189. ->headers([
  190. Header::make('Items')->width('15%'),
  191. Header::make('Description')->width('25%'),
  192. Header::make('Quantity')->width('10%'),
  193. Header::make('Price')->width('10%'),
  194. Header::make('Taxes')->width('15%'),
  195. Header::make('Discounts')->width('15%'),
  196. Header::make('Amount')->width('10%')->align('right'),
  197. ])
  198. ->schema([
  199. Forms\Components\Select::make('offering_id')
  200. ->relationship('sellableOffering', 'name')
  201. ->preload()
  202. ->searchable()
  203. ->required()
  204. ->live()
  205. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  206. $offeringId = $state;
  207. $offeringRecord = Offering::with('salesTaxes')->find($offeringId);
  208. if ($offeringRecord) {
  209. $set('description', $offeringRecord->description);
  210. $set('unit_price', $offeringRecord->price);
  211. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  212. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  213. }
  214. }),
  215. Forms\Components\TextInput::make('description'),
  216. Forms\Components\TextInput::make('quantity')
  217. ->required()
  218. ->numeric()
  219. ->live()
  220. ->default(1),
  221. Forms\Components\TextInput::make('unit_price')
  222. ->hiddenLabel()
  223. ->numeric()
  224. ->live()
  225. ->default(0),
  226. Forms\Components\Select::make('salesTaxes')
  227. ->relationship('salesTaxes', 'name')
  228. ->preload()
  229. ->multiple()
  230. ->live()
  231. ->searchable(),
  232. Forms\Components\Select::make('salesDiscounts')
  233. ->relationship('salesDiscounts', 'name')
  234. ->preload()
  235. ->multiple()
  236. ->live()
  237. ->searchable(),
  238. Forms\Components\Placeholder::make('total')
  239. ->hiddenLabel()
  240. ->content(function (Forms\Get $get) {
  241. $quantity = max((float) ($get('quantity') ?? 0), 0);
  242. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  243. $salesTaxes = $get('salesTaxes') ?? [];
  244. $salesDiscounts = $get('salesDiscounts') ?? [];
  245. $subtotal = $quantity * $unitPrice;
  246. // Calculate tax amount based on subtotal
  247. $taxAmount = 0;
  248. if (! empty($salesTaxes)) {
  249. $taxRates = Adjustment::whereIn('id', $salesTaxes)->pluck('rate');
  250. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  251. }
  252. // Calculate discount amount based on subtotal
  253. $discountAmount = 0;
  254. if (! empty($salesDiscounts)) {
  255. $discountRates = Adjustment::whereIn('id', $salesDiscounts)->pluck('rate');
  256. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  257. }
  258. // Final total
  259. $total = $subtotal + ($taxAmount - $discountAmount);
  260. return money($total, CurrencyAccessor::getDefaultCurrency(), true)->format();
  261. }),
  262. ]),
  263. Forms\Components\Grid::make(6)
  264. ->schema([
  265. Forms\Components\ViewField::make('totals')
  266. ->columnStart(5)
  267. ->columnSpan(2)
  268. ->view('filament.forms.components.invoice-totals'),
  269. ]),
  270. // Forms\Components\Repeater::make('lineItems')
  271. // ->relationship()
  272. // ->columns(8)
  273. // ->schema([
  274. // Forms\Components\Select::make('offering_id')
  275. // ->relationship('offering', 'name')
  276. // ->preload()
  277. // ->columnSpan(2)
  278. // ->searchable()
  279. // ->required()
  280. // ->live()
  281. // ->afterStateUpdated(function (Forms\Set $set, $state) {
  282. // $offeringId = $state;
  283. // $offeringRecord = Offering::with('salesTaxes')->find($offeringId);
  284. //
  285. // if ($offeringRecord) {
  286. // $set('description', $offeringRecord->description);
  287. // $set('unit_price', $offeringRecord->price);
  288. // $set('total', $offeringRecord->price);
  289. //
  290. // $salesTaxes = $offeringRecord->salesTaxes->map(function ($tax) {
  291. // return [
  292. // 'id' => $tax->id,
  293. // 'amount' => null, // Amount will be calculated dynamically
  294. // ];
  295. // })->toArray();
  296. //
  297. // $set('taxes', $salesTaxes);
  298. // }
  299. // }),
  300. // Forms\Components\TextInput::make('description')
  301. // ->columnSpan(3)
  302. // ->required(),
  303. // Forms\Components\TextInput::make('quantity')
  304. // ->required()
  305. // ->numeric()
  306. // ->live()
  307. // ->default(1),
  308. // Forms\Components\TextInput::make('unit_price')
  309. // ->live()
  310. // ->numeric()
  311. // ->default(0),
  312. // Forms\Components\Placeholder::make('total')
  313. // ->content(function (Forms\Get $get) {
  314. // $quantity = $get('quantity');
  315. // $unitPrice = $get('unit_price');
  316. //
  317. // if ($quantity && $unitPrice) {
  318. // return $quantity * $unitPrice;
  319. // }
  320. // }),
  321. // TableRepeater::make('taxes')
  322. // ->relationship()
  323. // ->columnSpanFull()
  324. // ->columnStart(6)
  325. // ->headers([
  326. // Header::make('')->width('200px'),
  327. // Header::make('')->width('50px')->align('right'),
  328. // ])
  329. // ->defaultItems(0)
  330. // ->schema([
  331. // Forms\Components\Select::make('id') // The ID of the adjustment being attached.
  332. // ->label('Tax Adjustment')
  333. // ->options(
  334. // Adjustment::query()
  335. // ->where('category', AdjustmentCategory::Tax)
  336. // ->pluck('name', 'id')
  337. // )
  338. // ->preload()
  339. // ->searchable()
  340. // ->required()
  341. // ->live(),
  342. // Forms\Components\Placeholder::make('amount')
  343. // ->hiddenLabel()
  344. // ->content(function (Forms\Get $get) {
  345. // $quantity = $get('../../quantity') ?? 0; // Get parent quantity
  346. // $unitPrice = $get('../../unit_price') ?? 0; // Get parent unit price
  347. // $rate = Adjustment::find($get('id'))->rate ?? 0;
  348. //
  349. // $total = $quantity * $unitPrice;
  350. //
  351. // return $total * ($rate / 100);
  352. // }),
  353. // ]),
  354. // ]),
  355. Forms\Components\Textarea::make('terms')
  356. ->columnSpanFull(),
  357. ]),
  358. Forms\Components\Section::make('Invoice Footer')
  359. ->collapsible()
  360. ->schema([
  361. Forms\Components\Textarea::make('footer')
  362. ->columnSpanFull(),
  363. ]),
  364. ]);
  365. }
  366. public static function table(Table $table): Table
  367. {
  368. return $table
  369. ->columns([
  370. Tables\Columns\TextColumn::make('status')
  371. ->badge()
  372. ->searchable(),
  373. Tables\Columns\TextColumn::make('due_date')
  374. ->label('Due')
  375. ->formatStateUsing(function (Tables\Columns\TextColumn $column, mixed $state) {
  376. if (blank($state)) {
  377. return null;
  378. }
  379. $date = Carbon::parse($state)
  380. ->setTimezone($timezone ?? $column->getTimezone());
  381. if ($date->isToday()) {
  382. return 'Today';
  383. }
  384. return $date->diffForHumans([
  385. 'options' => CarbonInterface::ONE_DAY_WORDS,
  386. ]);
  387. })
  388. ->sortable(),
  389. Tables\Columns\TextColumn::make('date')
  390. ->date()
  391. ->sortable(),
  392. Tables\Columns\TextColumn::make('invoice_number')
  393. ->label('Number')
  394. ->searchable(),
  395. Tables\Columns\TextColumn::make('client.name')
  396. ->sortable(),
  397. Tables\Columns\TextColumn::make('total')
  398. ->currency(),
  399. Tables\Columns\TextColumn::make('amount_paid')
  400. ->label('Amount Paid')
  401. ->currency(),
  402. Tables\Columns\TextColumn::make('amount_due')
  403. ->label('Amount Due')
  404. ->currency(),
  405. ])
  406. ->filters([
  407. //
  408. ])
  409. ->actions([
  410. Tables\Actions\ActionGroup::make([
  411. Tables\Actions\EditAction::make(),
  412. Tables\Actions\ViewAction::make(),
  413. Tables\Actions\DeleteAction::make(),
  414. Tables\Actions\ReplicateAction::make()
  415. ->label('Duplicate')
  416. ->excludeAttributes(['status', 'amount_paid', 'amount_due', 'created_by', 'updated_by', 'created_at', 'updated_at', 'invoice_number', 'date', 'due_date'])
  417. ->modal(false)
  418. ->beforeReplicaSaved(function (Invoice $original, Invoice $replica) {
  419. $replica->status = InvoiceStatus::Draft;
  420. $replica->invoice_number = Invoice::getNextDocumentNumber();
  421. $replica->date = now();
  422. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  423. })
  424. ->databaseTransaction()
  425. ->after(function (Invoice $original, Invoice $replica) {
  426. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  427. $replicaLineItem = $lineItem->replicate([
  428. 'documentable_id',
  429. 'documentable_type',
  430. 'subtotal',
  431. 'total',
  432. 'created_by',
  433. 'updated_by',
  434. 'created_at',
  435. 'updated_at',
  436. ]);
  437. $replicaLineItem->documentable_id = $replica->id;
  438. $replicaLineItem->documentable_type = $replica->getMorphClass();
  439. $replicaLineItem->save();
  440. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  441. });
  442. })
  443. ->successRedirectUrl(function (Invoice $replica) {
  444. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  445. }),
  446. Tables\Actions\Action::make('approveDraft')
  447. ->label('Approve')
  448. ->icon('heroicon-o-check-circle')
  449. ->visible(function (Invoice $record) {
  450. return $record->isDraft();
  451. })
  452. ->databaseTransaction()
  453. ->successNotificationTitle('Invoice Approved')
  454. ->action(function (Invoice $record, Tables\Actions\Action $action) {
  455. $transaction = $record->transactions()->create([
  456. 'type' => TransactionType::Journal,
  457. 'posted_at' => now(),
  458. 'amount' => $record->total,
  459. 'description' => 'Invoice Approval for Invoice #' . $record->invoice_number,
  460. ]);
  461. $transaction->journalEntries()->create([
  462. 'type' => JournalEntryType::Debit,
  463. 'account_id' => Account::getAccountsReceivableAccount()->id,
  464. 'amount' => $record->total,
  465. 'description' => $transaction->description,
  466. ]);
  467. foreach ($record->lineItems as $lineItem) {
  468. $transaction->journalEntries()->create([
  469. 'type' => JournalEntryType::Credit,
  470. 'account_id' => $lineItem->offering->income_account_id,
  471. 'amount' => $lineItem->subtotal,
  472. 'description' => $transaction->description,
  473. ]);
  474. foreach ($lineItem->adjustments as $adjustment) {
  475. $transaction->journalEntries()->create([
  476. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  477. 'account_id' => $adjustment->account_id,
  478. 'amount' => $lineItem->calculateAdjustmentTotal($adjustment)->getAmount(),
  479. 'description' => $transaction->description,
  480. ]);
  481. }
  482. }
  483. $record->updateQuietly([
  484. 'status' => InvoiceStatus::Unsent,
  485. ]);
  486. $action->success();
  487. }),
  488. Tables\Actions\Action::make('markAsSent')
  489. ->label('Mark as Sent')
  490. ->icon('heroicon-o-paper-airplane')
  491. ->visible(function (Invoice $record) {
  492. return $record->status === InvoiceStatus::Unsent;
  493. })
  494. ->successNotificationTitle('Invoice Sent')
  495. ->action(function (Invoice $record, Tables\Actions\Action $action) {
  496. $record->updateQuietly([
  497. 'status' => InvoiceStatus::Sent,
  498. ]);
  499. $action->success();
  500. }),
  501. Tables\Actions\Action::make('recordPayment')
  502. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  503. ->stickyModalHeader()
  504. ->stickyModalFooter()
  505. ->modalFooterActionsAlignment(Alignment::End)
  506. ->modalWidth(MaxWidth::TwoExtraLarge)
  507. ->icon('heroicon-o-credit-card')
  508. ->visible(function (Invoice $record) {
  509. return $record->canRecordPayment();
  510. })
  511. ->mountUsing(function (Invoice $record, Form $form) {
  512. $form->fill([
  513. 'posted_at' => now(),
  514. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  515. ]);
  516. })
  517. ->databaseTransaction()
  518. ->successNotificationTitle('Payment Recorded')
  519. ->form([
  520. Forms\Components\DatePicker::make('posted_at')
  521. ->label('Date'),
  522. Forms\Components\TextInput::make('amount')
  523. ->label('Amount')
  524. ->required()
  525. ->money()
  526. ->live(onBlur: true)
  527. ->helperText(function (Invoice $record, $state) {
  528. if (! CurrencyConverter::isValidAmount($state)) {
  529. return null;
  530. }
  531. $amountDue = $record->getRawOriginal('amount_due');
  532. $amount = CurrencyConverter::convertToCents($state);
  533. if ($amount <= 0) {
  534. return 'Please enter a valid positive amount';
  535. }
  536. if ($record->status === InvoiceStatus::Overpaid) {
  537. $newAmountDue = $amountDue + $amount;
  538. } else {
  539. $newAmountDue = $amountDue - $amount;
  540. }
  541. return match (true) {
  542. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue),
  543. $newAmountDue === 0 => 'Invoice will be fully paid',
  544. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue)),
  545. };
  546. })
  547. ->rules([
  548. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  549. if (! CurrencyConverter::isValidAmount($value)) {
  550. $fail('Please enter a valid amount');
  551. }
  552. },
  553. ]),
  554. Forms\Components\Select::make('payment_method')
  555. ->label('Payment Method')
  556. ->required()
  557. ->options(PaymentMethod::class),
  558. Forms\Components\Select::make('bank_account_id')
  559. ->label('Account')
  560. ->required()
  561. ->options(BankAccount::query()
  562. ->get()
  563. ->pluck('account.name', 'id'))
  564. ->searchable(),
  565. Forms\Components\Textarea::make('notes')
  566. ->label('Notes'),
  567. ])
  568. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  569. $record->recordPayment($data);
  570. $action->success();
  571. }),
  572. ]),
  573. ])
  574. ->bulkActions([
  575. Tables\Actions\BulkActionGroup::make([
  576. Tables\Actions\DeleteBulkAction::make(),
  577. ]),
  578. ]);
  579. }
  580. public static function getRelations(): array
  581. {
  582. return [
  583. RelationManagers\PaymentsRelationManager::class,
  584. ];
  585. }
  586. public static function getPages(): array
  587. {
  588. return [
  589. 'index' => Pages\ListInvoices::route('/'),
  590. 'create' => Pages\CreateInvoice::route('/create'),
  591. 'view' => Pages\ViewInvoice::route('/{record}'),
  592. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  593. ];
  594. }
  595. }