You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InvoiceResource.php 39KB

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