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

InvoiceResource.php 37KB

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