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.

BillResource.php 37KB

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