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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. ->label('Price')
  257. ->hiddenLabel()
  258. ->money(useAffix: false)
  259. ->live()
  260. ->maxValue(9999999999.99)
  261. ->default(0),
  262. Forms\Components\Group::make([
  263. CreateAdjustmentSelect::make('purchaseTaxes')
  264. ->label('Taxes')
  265. ->hiddenLabel()
  266. ->placeholder('Select taxes')
  267. ->category(AdjustmentCategory::Tax)
  268. ->type(AdjustmentType::Purchase)
  269. ->adjustmentsRelationship('purchaseTaxes')
  270. ->saveRelationshipsUsing(null)
  271. ->dehydrated(true)
  272. ->inlineSuffix()
  273. ->preload()
  274. ->multiple()
  275. ->live()
  276. ->searchable(),
  277. CreateAdjustmentSelect::make('purchaseDiscounts')
  278. ->label('Discounts')
  279. ->hiddenLabel()
  280. ->placeholder('Select discounts')
  281. ->category(AdjustmentCategory::Discount)
  282. ->type(AdjustmentType::Purchase)
  283. ->adjustmentsRelationship('purchaseDiscounts')
  284. ->saveRelationshipsUsing(null)
  285. ->dehydrated(true)
  286. ->inlineSuffix()
  287. ->multiple()
  288. ->live()
  289. ->hidden(function (Forms\Get $get) {
  290. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  291. return $discountMethod->isPerDocument();
  292. })
  293. ->searchable(),
  294. ])->columnSpan(1),
  295. Forms\Components\Placeholder::make('total')
  296. ->hiddenLabel()
  297. ->extraAttributes(['class' => 'text-left sm:text-right'])
  298. ->content(function (Forms\Get $get) {
  299. $quantity = max((float) ($get('quantity') ?? 0), 0);
  300. $unitPrice = CurrencyConverter::isValidAmount($get('unit_price'), 'USD')
  301. ? CurrencyConverter::convertToFloat($get('unit_price'), 'USD')
  302. : 0;
  303. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  304. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  305. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  306. $subtotal = $quantity * $unitPrice;
  307. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  308. $taxAmountInCents = Adjustment::whereIn('id', $purchaseTaxes)
  309. ->get()
  310. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  311. if ($adjustment->computation->isPercentage()) {
  312. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  313. } else {
  314. return $adjustment->getRawOriginal('rate');
  315. }
  316. });
  317. $discountAmountInCents = Adjustment::whereIn('id', $purchaseDiscounts)
  318. ->get()
  319. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  320. if ($adjustment->computation->isPercentage()) {
  321. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  322. } else {
  323. return $adjustment->getRawOriginal('rate');
  324. }
  325. });
  326. // Final total
  327. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  328. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  329. }),
  330. ]),
  331. DocumentTotals::make()
  332. ->type(DocumentType::Bill),
  333. ]),
  334. ]);
  335. }
  336. public static function table(Table $table): Table
  337. {
  338. return $table
  339. ->defaultSort('due_date')
  340. ->columns([
  341. Columns::id(),
  342. Tables\Columns\TextColumn::make('status')
  343. ->badge()
  344. ->searchable(),
  345. Tables\Columns\TextColumn::make('due_date')
  346. ->label('Due')
  347. ->asRelativeDay()
  348. ->sortable(),
  349. Tables\Columns\TextColumn::make('date')
  350. ->date()
  351. ->sortable(),
  352. Tables\Columns\TextColumn::make('bill_number')
  353. ->label('Number')
  354. ->searchable()
  355. ->sortable(),
  356. Tables\Columns\TextColumn::make('vendor.name')
  357. ->sortable()
  358. ->searchable()
  359. ->hiddenOn(BillsRelationManager::class),
  360. Tables\Columns\TextColumn::make('total')
  361. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  362. ->sortable()
  363. ->toggleable(),
  364. Tables\Columns\TextColumn::make('amount_paid')
  365. ->label('Amount paid')
  366. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  367. ->sortable()
  368. ->toggleable(),
  369. Tables\Columns\TextColumn::make('amount_due')
  370. ->label('Amount due')
  371. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  372. ->sortable(),
  373. ])
  374. ->filters([
  375. Tables\Filters\SelectFilter::make('vendor')
  376. ->relationship('vendor', 'name')
  377. ->searchable()
  378. ->preload()
  379. ->hiddenOn(BillsRelationManager::class),
  380. Tables\Filters\SelectFilter::make('status')
  381. ->options(BillStatus::class)
  382. ->native(false),
  383. Tables\Filters\TernaryFilter::make('has_payments')
  384. ->label('Has payments')
  385. ->queries(
  386. true: fn (Builder $query) => $query->whereHas('payments'),
  387. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  388. ),
  389. DateRangeFilter::make('date')
  390. ->fromLabel('From date')
  391. ->untilLabel('To date')
  392. ->indicatorLabel('Date'),
  393. DateRangeFilter::make('due_date')
  394. ->fromLabel('From due date')
  395. ->untilLabel('To due date')
  396. ->indicatorLabel('Due'),
  397. ])
  398. ->actions([
  399. Tables\Actions\ActionGroup::make([
  400. Tables\Actions\ActionGroup::make([
  401. Tables\Actions\EditAction::make()
  402. ->url(static fn (Bill $record) => Pages\EditBill::getUrl(['record' => $record])),
  403. Tables\Actions\ViewAction::make()
  404. ->url(static fn (Bill $record) => Pages\ViewBill::getUrl(['record' => $record])),
  405. Bill::getReplicateAction(Tables\Actions\ReplicateAction::class),
  406. Tables\Actions\Action::make('recordPayment')
  407. ->label('Record payment')
  408. ->stickyModalHeader()
  409. ->stickyModalFooter()
  410. ->modalFooterActionsAlignment(Alignment::End)
  411. ->modalWidth(MaxWidth::TwoExtraLarge)
  412. ->icon('heroicon-o-credit-card')
  413. ->visible(function (Bill $record) {
  414. return $record->canRecordPayment();
  415. })
  416. ->mountUsing(function (Bill $record, Form $form) {
  417. $form->fill([
  418. 'posted_at' => now(),
  419. 'amount' => $record->amount_due,
  420. ]);
  421. })
  422. ->databaseTransaction()
  423. ->successNotificationTitle('Payment recorded')
  424. ->form([
  425. Forms\Components\DatePicker::make('posted_at')
  426. ->label('Date'),
  427. Forms\Components\TextInput::make('amount')
  428. ->label('Amount')
  429. ->required()
  430. ->money(fn (Bill $record) => $record->currency_code)
  431. ->live(onBlur: true)
  432. ->helperText(function (Bill $record, $state) {
  433. $billCurrency = $record->currency_code;
  434. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  435. return null;
  436. }
  437. $amountDue = $record->amount_due;
  438. $amount = CurrencyConverter::convertToCents($state, 'USD');
  439. if ($amount <= 0) {
  440. return 'Please enter a valid positive amount';
  441. }
  442. $newAmountDue = $amountDue - $amount;
  443. return match (true) {
  444. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $billCurrency),
  445. $newAmountDue === 0 => 'Bill will be fully paid',
  446. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $billCurrency),
  447. };
  448. })
  449. ->rules([
  450. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  451. if (! CurrencyConverter::isValidAmount($value, 'USD')) {
  452. $fail('Please enter a valid amount');
  453. }
  454. },
  455. ]),
  456. Forms\Components\Select::make('payment_method')
  457. ->label('Payment method')
  458. ->required()
  459. ->options(PaymentMethod::class),
  460. Forms\Components\Select::make('bank_account_id')
  461. ->label('Account')
  462. ->required()
  463. ->options(function () {
  464. return BankAccount::query()
  465. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  466. ->select(['bank_accounts.id', 'accounts.name'])
  467. ->pluck('accounts.name', 'bank_accounts.id')
  468. ->toArray();
  469. })
  470. ->searchable(),
  471. Forms\Components\Textarea::make('notes')
  472. ->label('Notes'),
  473. ])
  474. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  475. $record->recordPayment($data);
  476. $action->success();
  477. }),
  478. ])->dropdown(false),
  479. Tables\Actions\DeleteAction::make(),
  480. ]),
  481. ])
  482. ->bulkActions([
  483. Tables\Actions\BulkActionGroup::make([
  484. Tables\Actions\DeleteBulkAction::make(),
  485. ReplicateBulkAction::make()
  486. ->label('Replicate')
  487. ->modalWidth(MaxWidth::Large)
  488. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  489. ->successNotificationTitle('Bills replicated successfully')
  490. ->failureNotificationTitle('Failed to replicate bills')
  491. ->databaseTransaction()
  492. ->deselectRecordsAfterCompletion()
  493. ->excludeAttributes([
  494. 'status',
  495. 'amount_paid',
  496. 'amount_due',
  497. 'created_by',
  498. 'updated_by',
  499. 'created_at',
  500. 'updated_at',
  501. 'bill_number',
  502. 'date',
  503. 'due_date',
  504. 'paid_at',
  505. ])
  506. ->beforeReplicaSaved(function (Bill $replica) {
  507. $replica->status = BillStatus::Open;
  508. $replica->bill_number = Bill::getNextDocumentNumber();
  509. $replica->date = now();
  510. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  511. })
  512. ->withReplicatedRelationships(['lineItems'])
  513. ->withExcludedRelationshipAttributes('lineItems', [
  514. 'subtotal',
  515. 'total',
  516. 'created_by',
  517. 'updated_by',
  518. 'created_at',
  519. 'updated_at',
  520. ]),
  521. Tables\Actions\BulkAction::make('recordPayments')
  522. ->label('Record payments')
  523. ->icon('heroicon-o-credit-card')
  524. ->stickyModalHeader()
  525. ->stickyModalFooter()
  526. ->modalFooterActionsAlignment(Alignment::End)
  527. ->modalWidth(MaxWidth::TwoExtraLarge)
  528. ->databaseTransaction()
  529. ->successNotificationTitle('Payments recorded')
  530. ->failureNotificationTitle('Failed to record payments')
  531. ->deselectRecordsAfterCompletion()
  532. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  533. $isInvalid = $records->contains(fn (Bill $bill) => ! $bill->canRecordPayment());
  534. if ($isInvalid) {
  535. Notification::make()
  536. ->title('Payment recording failed')
  537. ->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.')
  538. ->persistent()
  539. ->danger()
  540. ->send();
  541. $action->cancel(true);
  542. }
  543. })
  544. ->mountUsing(function (Collection $records, Form $form) {
  545. $totalAmountDue = $records->sum('amount_due');
  546. $form->fill([
  547. 'posted_at' => now(),
  548. 'amount' => $totalAmountDue,
  549. ]);
  550. })
  551. ->form([
  552. Forms\Components\DatePicker::make('posted_at')
  553. ->label('Date'),
  554. Forms\Components\TextInput::make('amount')
  555. ->label('Amount')
  556. ->required()
  557. ->money()
  558. ->rules([
  559. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  560. if (! CurrencyConverter::isValidAmount($value)) {
  561. $fail('Please enter a valid amount');
  562. }
  563. },
  564. ]),
  565. Forms\Components\Select::make('payment_method')
  566. ->label('Payment method')
  567. ->required()
  568. ->options(PaymentMethod::class),
  569. Forms\Components\Select::make('bank_account_id')
  570. ->label('Account')
  571. ->required()
  572. ->options(function () {
  573. return BankAccount::query()
  574. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  575. ->select(['bank_accounts.id', 'accounts.name'])
  576. ->pluck('accounts.name', 'bank_accounts.id')
  577. ->toArray();
  578. })
  579. ->searchable(),
  580. Forms\Components\Textarea::make('notes')
  581. ->label('Notes'),
  582. ])
  583. ->before(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  584. $totalPaymentAmount = $data['amount'] ?? 0;
  585. $totalAmountDue = $records->sum('amount_due');
  586. if ($totalPaymentAmount > $totalAmountDue) {
  587. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  588. Notification::make()
  589. ->title('Excess payment amount')
  590. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  591. ->persistent()
  592. ->warning()
  593. ->send();
  594. $action->halt(true);
  595. }
  596. })
  597. ->action(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  598. $totalPaymentAmount = $data['amount'] ?? 0;
  599. $remainingAmount = $totalPaymentAmount;
  600. $records->each(function (Bill $record) use (&$remainingAmount, $data) {
  601. $amountDue = $record->amount_due;
  602. if ($amountDue <= 0 || $remainingAmount <= 0) {
  603. return;
  604. }
  605. $paymentAmount = min($amountDue, $remainingAmount);
  606. $data['amount'] = $paymentAmount;
  607. $record->recordPayment($data);
  608. $remainingAmount -= $paymentAmount;
  609. });
  610. $action->success();
  611. }),
  612. ]),
  613. ]);
  614. }
  615. public static function getPages(): array
  616. {
  617. return [
  618. 'index' => Pages\ListBills::route('/'),
  619. 'create' => Pages\CreateBill::route('/create'),
  620. 'view' => Pages\ViewBill::route('/{record}'),
  621. 'edit' => Pages\EditBill::route('/{record}/edit'),
  622. ];
  623. }
  624. public static function getWidgets(): array
  625. {
  626. return [
  627. BillResource\Widgets\BillOverview::class,
  628. ];
  629. }
  630. }