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 38KB

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