Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

InvoiceResource.php 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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\Forms\Components\InvoiceTotals;
  11. use App\Filament\Tables\Actions\ReplicateBulkAction;
  12. use App\Filament\Tables\Filters\DateRangeFilter;
  13. use App\Models\Accounting\Adjustment;
  14. use App\Models\Accounting\DocumentLineItem;
  15. use App\Models\Accounting\Invoice;
  16. use App\Models\Banking\BankAccount;
  17. use App\Models\Common\Offering;
  18. use App\Utilities\Currency\CurrencyConverter;
  19. use Awcodes\TableRepeater\Components\TableRepeater;
  20. use Awcodes\TableRepeater\Header;
  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\Facades\Auth;
  35. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  36. class InvoiceResource extends Resource
  37. {
  38. protected static ?string $model = Invoice::class;
  39. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  40. public static function form(Form $form): Form
  41. {
  42. $company = Auth::user()->currentCompany;
  43. return $form
  44. ->schema([
  45. Forms\Components\Section::make('Invoice Header')
  46. ->collapsible()
  47. ->schema([
  48. Forms\Components\Split::make([
  49. Forms\Components\Group::make([
  50. FileUpload::make('logo')
  51. ->openable()
  52. ->maxSize(1024)
  53. ->localizeLabel()
  54. ->visibility('public')
  55. ->disk('public')
  56. ->directory('logos/document')
  57. ->imageResizeMode('contain')
  58. ->imageCropAspectRatio('3:2')
  59. ->panelAspectRatio('3:2')
  60. ->maxWidth(MaxWidth::ExtraSmall)
  61. ->panelLayout('integrated')
  62. ->removeUploadedFileButtonPosition('center bottom')
  63. ->uploadButtonPosition('center bottom')
  64. ->uploadProgressIndicatorPosition('center bottom')
  65. ->getUploadedFileNameForStorageUsing(
  66. static fn (TemporaryUploadedFile $file): string => (string) str($file->getClientOriginalName())
  67. ->prepend(Auth::user()->currentCompany->id . '_'),
  68. )
  69. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/gif']),
  70. ]),
  71. Forms\Components\Group::make([
  72. Forms\Components\TextInput::make('header')
  73. ->default(fn () => $company->defaultInvoice->header),
  74. Forms\Components\TextInput::make('subheader')
  75. ->default(fn () => $company->defaultInvoice->subheader),
  76. Forms\Components\View::make('filament.forms.components.company-info')
  77. ->viewData([
  78. 'company_name' => $company->name,
  79. 'company_address' => $company->profile->address,
  80. 'company_city' => $company->profile->city?->name,
  81. 'company_state' => $company->profile->state?->name,
  82. 'company_zip' => $company->profile->zip_code,
  83. 'company_country' => $company->profile->state?->country->name,
  84. ]),
  85. ])->grow(true),
  86. ])->from('md'),
  87. ]),
  88. Forms\Components\Section::make('Invoice Details')
  89. ->schema([
  90. Forms\Components\Split::make([
  91. Forms\Components\Group::make([
  92. Forms\Components\Select::make('client_id')
  93. ->relationship('client', 'name')
  94. ->preload()
  95. ->searchable()
  96. ->required(),
  97. ]),
  98. Forms\Components\Group::make([
  99. Forms\Components\TextInput::make('invoice_number')
  100. ->label('Invoice Number')
  101. ->default(fn () => Invoice::getNextDocumentNumber()),
  102. Forms\Components\TextInput::make('order_number')
  103. ->label('P.O/S.O Number'),
  104. Forms\Components\DatePicker::make('date')
  105. ->label('Invoice Date')
  106. ->live()
  107. ->default(now())
  108. ->disabled(function (?Invoice $record) {
  109. return $record?->hasPayments();
  110. })
  111. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  112. $date = $state;
  113. $dueDate = $get('due_date');
  114. if ($date && $dueDate && $date > $dueDate) {
  115. $set('due_date', $date);
  116. }
  117. }),
  118. Forms\Components\DatePicker::make('due_date')
  119. ->label('Payment Due')
  120. ->default(function () use ($company) {
  121. return now()->addDays($company->defaultInvoice->payment_terms->getDays());
  122. })
  123. ->minDate(static function (Forms\Get $get) {
  124. return $get('date') ?? now();
  125. }),
  126. Forms\Components\Select::make('discount_method')
  127. ->label('Discount Method')
  128. ->options([
  129. 'line_items' => 'Per Line Item Discounts',
  130. 'invoice' => 'Invoice Level Discount',
  131. ])
  132. ->selectablePlaceholder(false)
  133. ->default('line_items')
  134. ->afterStateUpdated(function ($state, Forms\Set $set) {
  135. $discountMethod = $state;
  136. if ($discountMethod === 'invoice') {
  137. $set('lineItems.*.salesDiscounts', []);
  138. }
  139. })
  140. ->live(),
  141. ])->grow(true),
  142. ])->from('md'),
  143. TableRepeater::make('lineItems')
  144. ->relationship()
  145. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  146. if (! is_array($state)) {
  147. $state = [];
  148. }
  149. $relationship = $component->getRelationship();
  150. $existingRecords = $component->getCachedExistingRecords();
  151. $recordsToDelete = [];
  152. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  153. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  154. continue;
  155. }
  156. $recordsToDelete[] = $keyToCheckForDeletion;
  157. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  158. }
  159. $relationship
  160. ->whereKey($recordsToDelete)
  161. ->get()
  162. ->each(static fn (Model $record) => $record->delete());
  163. $childComponentContainers = $component->getChildComponentContainers(
  164. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  165. );
  166. $itemOrder = 1;
  167. $orderColumn = $component->getOrderColumn();
  168. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  169. foreach ($childComponentContainers as $itemKey => $item) {
  170. $itemData = $item->getState(shouldCallHooksBefore: false);
  171. if ($orderColumn) {
  172. $itemData[$orderColumn] = $itemOrder;
  173. $itemOrder++;
  174. }
  175. if ($record = ($existingRecords[$itemKey] ?? null)) {
  176. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  177. if ($itemData === null) {
  178. continue;
  179. }
  180. $translatableContentDriver ?
  181. $translatableContentDriver->updateRecord($record, $itemData) :
  182. $record->fill($itemData)->save();
  183. continue;
  184. }
  185. $relatedModel = $component->getRelatedModel();
  186. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  187. if ($itemData === null) {
  188. continue;
  189. }
  190. if ($translatableContentDriver) {
  191. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  192. } else {
  193. $record = new $relatedModel;
  194. $record->fill($itemData);
  195. }
  196. $record = $relationship->save($record);
  197. $item->model($record)->saveRelationships();
  198. $existingRecords->push($record);
  199. }
  200. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  201. /** @var Invoice $invoice */
  202. $invoice = $component->getRecord();
  203. // Recalculate totals for line items
  204. // Recalculate totals for line items
  205. $invoice->lineItems()->each(function (DocumentLineItem $lineItem) use ($invoice) {
  206. $lineItem->updateQuietly([
  207. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  208. 'discount_total' => $invoice->discount_method === 'line_items'
  209. ? $lineItem->calculateDiscountTotal()->getAmount()
  210. : 0,
  211. ]);
  212. });
  213. $subtotal = $invoice->lineItems()->sum('subtotal') / 100;
  214. $taxTotal = $invoice->lineItems()->sum('tax_total') / 100;
  215. if ($invoice->discount_method === 'line_items') {
  216. $discountTotal = $invoice->lineItems()->sum('discount_total') / 100;
  217. } else {
  218. // Calculate invoice-level discount
  219. if ($invoice->discount_computation === AdjustmentComputation::Percentage) {
  220. $discountTotal = $subtotal * ($invoice->discount_rate / 100);
  221. } else {
  222. $discountTotal = $invoice->discount_rate;
  223. }
  224. }
  225. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  226. $invoice->updateQuietly([
  227. 'subtotal' => $subtotal,
  228. 'tax_total' => $taxTotal,
  229. 'discount_total' => $discountTotal,
  230. 'total' => $grandTotal,
  231. ]);
  232. if ($invoice->approved_at && $invoice->approvalTransaction) {
  233. $invoice->updateApprovalTransaction();
  234. }
  235. })
  236. ->headers(function (Forms\Get $get) {
  237. $hasDiscounts = $get('discount_method') === 'line_items';
  238. $headers = [
  239. Header::make('Items')->width($hasDiscounts ? '15%' : '20%'),
  240. Header::make('Description')->width($hasDiscounts ? '25%' : '30%'), // Increase when no discounts
  241. Header::make('Quantity')->width('10%'),
  242. Header::make('Price')->width('10%'),
  243. Header::make('Taxes')->width($hasDiscounts ? '15%' : '20%'), // Increase when no discounts
  244. ];
  245. if ($hasDiscounts) {
  246. $headers[] = Header::make('Discounts')->width('15%');
  247. }
  248. $headers[] = Header::make('Amount')->width('10%')->align('right');
  249. return $headers;
  250. })
  251. ->schema([
  252. Forms\Components\Select::make('offering_id')
  253. ->relationship('sellableOffering', 'name')
  254. ->preload()
  255. ->searchable()
  256. ->required()
  257. ->live()
  258. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  259. $offeringId = $state;
  260. $offeringRecord = Offering::with(['salesTaxes', 'salesDiscounts'])->find($offeringId);
  261. if ($offeringRecord) {
  262. $set('description', $offeringRecord->description);
  263. $set('unit_price', $offeringRecord->price);
  264. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  265. $discountMethod = $get('../../discount_method');
  266. if ($discountMethod === 'line_items') {
  267. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  268. }
  269. }
  270. }),
  271. Forms\Components\TextInput::make('description'),
  272. Forms\Components\TextInput::make('quantity')
  273. ->required()
  274. ->numeric()
  275. ->live()
  276. ->default(1),
  277. Forms\Components\TextInput::make('unit_price')
  278. ->hiddenLabel()
  279. ->numeric()
  280. ->live()
  281. ->default(0),
  282. Forms\Components\Select::make('salesTaxes')
  283. ->relationship('salesTaxes', 'name')
  284. ->preload()
  285. ->multiple()
  286. ->live()
  287. ->searchable(),
  288. Forms\Components\Select::make('salesDiscounts')
  289. ->relationship('salesDiscounts', 'name')
  290. ->preload()
  291. ->multiple()
  292. ->live()
  293. ->hidden(function (Forms\Get $get) {
  294. $discountMethod = $get('../../discount_method');
  295. return $discountMethod === 'invoice';
  296. })
  297. ->searchable(),
  298. Forms\Components\Placeholder::make('total')
  299. ->hiddenLabel()
  300. ->content(function (Forms\Get $get) {
  301. $quantity = max((float) ($get('quantity') ?? 0), 0);
  302. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  303. $salesTaxes = $get('salesTaxes') ?? [];
  304. $salesDiscounts = $get('salesDiscounts') ?? [];
  305. $subtotal = $quantity * $unitPrice;
  306. // Calculate tax amount based on subtotal
  307. $taxAmount = 0;
  308. if (! empty($salesTaxes)) {
  309. $taxRates = Adjustment::whereIn('id', $salesTaxes)->pluck('rate');
  310. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  311. }
  312. // Calculate discount amount based on subtotal
  313. $discountAmount = 0;
  314. if (! empty($salesDiscounts)) {
  315. $discountRates = Adjustment::whereIn('id', $salesDiscounts)->pluck('rate');
  316. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  317. }
  318. // Final total
  319. $total = $subtotal + ($taxAmount - $discountAmount);
  320. return CurrencyConverter::formatToMoney($total);
  321. }),
  322. ]),
  323. InvoiceTotals::make(),
  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. }