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

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