選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

BillResource.php 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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\DocumentTotals;
  18. use App\Filament\Tables\Actions\ReplicateBulkAction;
  19. use App\Filament\Tables\Columns;
  20. use App\Filament\Tables\Filters\DateRangeFilter;
  21. use App\Models\Accounting\Adjustment;
  22. use App\Models\Accounting\Bill;
  23. use App\Models\Accounting\DocumentLineItem;
  24. use App\Models\Banking\BankAccount;
  25. use App\Models\Common\Offering;
  26. use App\Models\Common\Vendor;
  27. use App\Utilities\Currency\CurrencyAccessor;
  28. use App\Utilities\Currency\CurrencyConverter;
  29. use App\Utilities\RateCalculator;
  30. use Awcodes\TableRepeater\Components\TableRepeater;
  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. ->selectablePlaceholder(false)
  155. ->default(DocumentDiscountMethod::PerLineItem)
  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. TableRepeater::make('lineItems')
  166. ->relationship()
  167. ->saveRelationshipsUsing(null)
  168. ->dehydrated(true)
  169. ->headers(function (Forms\Get $get) use ($settings) {
  170. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  171. $headers = [
  172. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  173. ->width($hasDiscounts ? '15%' : '20%'),
  174. Header::make('Description')
  175. ->width($hasDiscounts ? '15%' : '20%'),
  176. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  177. ->width('10%'),
  178. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  179. ->width('10%'),
  180. Header::make('Taxes')
  181. ->width($hasDiscounts ? '20%' : '30%'),
  182. ];
  183. if ($hasDiscounts) {
  184. $headers[] = Header::make('Discounts')->width('20%');
  185. }
  186. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  187. ->width('10%')
  188. ->align('right');
  189. return $headers;
  190. })
  191. ->schema([
  192. CreateOfferingSelect::make('offering_id')
  193. ->label('Item')
  194. ->required()
  195. ->live()
  196. ->purchasable()
  197. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state, ?DocumentLineItem $record) {
  198. $offeringId = $state;
  199. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  200. $isPerLineItem = $discountMethod->isPerLineItem();
  201. $existingTaxIds = [];
  202. $existingDiscountIds = [];
  203. if ($record) {
  204. $existingTaxIds = $record->purchaseTaxes()->pluck('adjustments.id')->toArray();
  205. if ($isPerLineItem) {
  206. $existingDiscountIds = $record->purchaseDiscounts()->pluck('adjustments.id')->toArray();
  207. }
  208. }
  209. $with = [
  210. 'purchaseTaxes' => static function ($query) use ($existingTaxIds) {
  211. $query->where(static function ($query) use ($existingTaxIds) {
  212. $query->where('status', AdjustmentStatus::Active)
  213. ->orWhereIn('adjustments.id', $existingTaxIds);
  214. });
  215. },
  216. ];
  217. if ($isPerLineItem) {
  218. $with['purchaseDiscounts'] = static function ($query) use ($existingDiscountIds) {
  219. $query->where(static function ($query) use ($existingDiscountIds) {
  220. $query->where('status', AdjustmentStatus::Active)
  221. ->orWhereIn('adjustments.id', $existingDiscountIds);
  222. });
  223. };
  224. }
  225. $offeringRecord = Offering::with($with)->find($offeringId);
  226. if (! $offeringRecord) {
  227. return;
  228. }
  229. $unitPrice = CurrencyConverter::convertToFloat($offeringRecord->price, $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency());
  230. $set('description', $offeringRecord->description);
  231. $set('unit_price', $unitPrice);
  232. $set('purchaseTaxes', $offeringRecord->purchaseTaxes->pluck('id')->toArray());
  233. if ($isPerLineItem) {
  234. $set('purchaseDiscounts', $offeringRecord->purchaseDiscounts->pluck('id')->toArray());
  235. }
  236. }),
  237. Forms\Components\TextInput::make('description'),
  238. Forms\Components\TextInput::make('quantity')
  239. ->required()
  240. ->numeric()
  241. ->live()
  242. ->maxValue(9999999999.99)
  243. ->default(1),
  244. Forms\Components\TextInput::make('unit_price')
  245. ->label('Price')
  246. ->hiddenLabel()
  247. ->numeric()
  248. ->live()
  249. ->maxValue(9999999999.99)
  250. ->default(0),
  251. CreateAdjustmentSelect::make('purchaseTaxes')
  252. ->label('Taxes')
  253. ->category(AdjustmentCategory::Tax)
  254. ->type(AdjustmentType::Purchase)
  255. ->adjustmentsRelationship('purchaseTaxes')
  256. ->saveRelationshipsUsing(null)
  257. ->dehydrated(true)
  258. ->preload()
  259. ->multiple()
  260. ->live()
  261. ->searchable(),
  262. CreateAdjustmentSelect::make('purchaseDiscounts')
  263. ->label('Discounts')
  264. ->category(AdjustmentCategory::Discount)
  265. ->type(AdjustmentType::Purchase)
  266. ->adjustmentsRelationship('purchaseDiscounts')
  267. ->saveRelationshipsUsing(null)
  268. ->dehydrated(true)
  269. ->multiple()
  270. ->live()
  271. ->hidden(function (Forms\Get $get) {
  272. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  273. return $discountMethod->isPerDocument();
  274. })
  275. ->searchable(),
  276. Forms\Components\Placeholder::make('total')
  277. ->hiddenLabel()
  278. ->extraAttributes(['class' => 'text-left sm:text-right'])
  279. ->content(function (Forms\Get $get) {
  280. $quantity = max((float) ($get('quantity') ?? 0), 0);
  281. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  282. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  283. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  284. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  285. $subtotal = $quantity * $unitPrice;
  286. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  287. $taxAmountInCents = Adjustment::whereIn('id', $purchaseTaxes)
  288. ->get()
  289. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  290. if ($adjustment->computation->isPercentage()) {
  291. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  292. } else {
  293. return $adjustment->getRawOriginal('rate');
  294. }
  295. });
  296. $discountAmountInCents = Adjustment::whereIn('id', $purchaseDiscounts)
  297. ->get()
  298. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  299. if ($adjustment->computation->isPercentage()) {
  300. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  301. } else {
  302. return $adjustment->getRawOriginal('rate');
  303. }
  304. });
  305. // Final total
  306. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  307. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  308. }),
  309. ]),
  310. DocumentTotals::make()
  311. ->type(DocumentType::Bill),
  312. ]),
  313. ]);
  314. }
  315. public static function table(Table $table): Table
  316. {
  317. return $table
  318. ->defaultSort('due_date')
  319. ->columns([
  320. Columns::id(),
  321. Tables\Columns\TextColumn::make('status')
  322. ->badge()
  323. ->searchable(),
  324. Tables\Columns\TextColumn::make('due_date')
  325. ->label('Due')
  326. ->asRelativeDay()
  327. ->sortable(),
  328. Tables\Columns\TextColumn::make('date')
  329. ->date()
  330. ->sortable(),
  331. Tables\Columns\TextColumn::make('bill_number')
  332. ->label('Number')
  333. ->searchable()
  334. ->sortable(),
  335. Tables\Columns\TextColumn::make('vendor.name')
  336. ->sortable()
  337. ->searchable()
  338. ->hiddenOn(BillsRelationManager::class),
  339. Tables\Columns\TextColumn::make('total')
  340. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  341. ->sortable()
  342. ->toggleable(),
  343. Tables\Columns\TextColumn::make('amount_paid')
  344. ->label('Amount paid')
  345. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  346. ->sortable()
  347. ->toggleable(),
  348. Tables\Columns\TextColumn::make('amount_due')
  349. ->label('Amount due')
  350. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  351. ->sortable(),
  352. ])
  353. ->filters([
  354. Tables\Filters\SelectFilter::make('vendor')
  355. ->relationship('vendor', 'name')
  356. ->searchable()
  357. ->preload()
  358. ->hiddenOn(BillsRelationManager::class),
  359. Tables\Filters\SelectFilter::make('status')
  360. ->options(BillStatus::class)
  361. ->native(false),
  362. Tables\Filters\TernaryFilter::make('has_payments')
  363. ->label('Has payments')
  364. ->queries(
  365. true: fn (Builder $query) => $query->whereHas('payments'),
  366. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  367. ),
  368. DateRangeFilter::make('date')
  369. ->fromLabel('From date')
  370. ->untilLabel('To date')
  371. ->indicatorLabel('Date'),
  372. DateRangeFilter::make('due_date')
  373. ->fromLabel('From due date')
  374. ->untilLabel('To due date')
  375. ->indicatorLabel('Due'),
  376. ])
  377. ->actions([
  378. Tables\Actions\ActionGroup::make([
  379. Tables\Actions\ActionGroup::make([
  380. Tables\Actions\EditAction::make()
  381. ->url(static fn (Bill $record) => Pages\EditBill::getUrl(['record' => $record])),
  382. Tables\Actions\ViewAction::make()
  383. ->url(static fn (Bill $record) => Pages\ViewBill::getUrl(['record' => $record])),
  384. Bill::getReplicateAction(Tables\Actions\ReplicateAction::class),
  385. Tables\Actions\Action::make('recordPayment')
  386. ->label('Record payment')
  387. ->stickyModalHeader()
  388. ->stickyModalFooter()
  389. ->modalFooterActionsAlignment(Alignment::End)
  390. ->modalWidth(MaxWidth::TwoExtraLarge)
  391. ->icon('heroicon-o-credit-card')
  392. ->visible(function (Bill $record) {
  393. return $record->canRecordPayment();
  394. })
  395. ->mountUsing(function (Bill $record, Form $form) {
  396. $form->fill([
  397. 'posted_at' => now(),
  398. 'amount' => $record->amount_due,
  399. ]);
  400. })
  401. ->databaseTransaction()
  402. ->successNotificationTitle('Payment recorded')
  403. ->form([
  404. Forms\Components\DatePicker::make('posted_at')
  405. ->label('Date'),
  406. Forms\Components\TextInput::make('amount')
  407. ->label('Amount')
  408. ->required()
  409. ->money(fn (Bill $record) => $record->currency_code)
  410. ->live(onBlur: true)
  411. ->helperText(function (Bill $record, $state) {
  412. $billCurrency = $record->currency_code;
  413. if (! CurrencyConverter::isValidAmount($state, $billCurrency)) {
  414. return null;
  415. }
  416. $amountDue = $record->getRawOriginal('amount_due');
  417. $amount = CurrencyConverter::convertToCents($state, $billCurrency);
  418. if ($amount <= 0) {
  419. return 'Please enter a valid positive amount';
  420. }
  421. $newAmountDue = $amountDue - $amount;
  422. return match (true) {
  423. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $billCurrency),
  424. $newAmountDue === 0 => 'Bill will be fully paid',
  425. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $billCurrency),
  426. };
  427. })
  428. ->rules([
  429. static fn (Bill $record): Closure => static function (string $attribute, $value, Closure $fail) use ($record) {
  430. if (! CurrencyConverter::isValidAmount($value, $record->currency_code)) {
  431. $fail('Please enter a valid amount');
  432. }
  433. },
  434. ]),
  435. Forms\Components\Select::make('payment_method')
  436. ->label('Payment method')
  437. ->required()
  438. ->options(PaymentMethod::class),
  439. Forms\Components\Select::make('bank_account_id')
  440. ->label('Account')
  441. ->required()
  442. ->options(function () {
  443. return BankAccount::query()
  444. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  445. ->select(['bank_accounts.id', 'accounts.name'])
  446. ->pluck('accounts.name', 'bank_accounts.id')
  447. ->toArray();
  448. })
  449. ->searchable(),
  450. Forms\Components\Textarea::make('notes')
  451. ->label('Notes'),
  452. ])
  453. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  454. $record->recordPayment($data);
  455. $action->success();
  456. }),
  457. ])->dropdown(false),
  458. Tables\Actions\DeleteAction::make(),
  459. ]),
  460. ])
  461. ->bulkActions([
  462. Tables\Actions\BulkActionGroup::make([
  463. Tables\Actions\DeleteBulkAction::make(),
  464. ReplicateBulkAction::make()
  465. ->label('Replicate')
  466. ->modalWidth(MaxWidth::Large)
  467. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  468. ->successNotificationTitle('Bills replicated successfully')
  469. ->failureNotificationTitle('Failed to replicate bills')
  470. ->databaseTransaction()
  471. ->deselectRecordsAfterCompletion()
  472. ->excludeAttributes([
  473. 'status',
  474. 'amount_paid',
  475. 'amount_due',
  476. 'created_by',
  477. 'updated_by',
  478. 'created_at',
  479. 'updated_at',
  480. 'bill_number',
  481. 'date',
  482. 'due_date',
  483. 'paid_at',
  484. ])
  485. ->beforeReplicaSaved(function (Bill $replica) {
  486. $replica->status = BillStatus::Open;
  487. $replica->bill_number = Bill::getNextDocumentNumber();
  488. $replica->date = now();
  489. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  490. })
  491. ->withReplicatedRelationships(['lineItems'])
  492. ->withExcludedRelationshipAttributes('lineItems', [
  493. 'subtotal',
  494. 'total',
  495. 'created_by',
  496. 'updated_by',
  497. 'created_at',
  498. 'updated_at',
  499. ]),
  500. Tables\Actions\BulkAction::make('recordPayments')
  501. ->label('Record payments')
  502. ->icon('heroicon-o-credit-card')
  503. ->stickyModalHeader()
  504. ->stickyModalFooter()
  505. ->modalFooterActionsAlignment(Alignment::End)
  506. ->modalWidth(MaxWidth::TwoExtraLarge)
  507. ->databaseTransaction()
  508. ->successNotificationTitle('Payments recorded')
  509. ->failureNotificationTitle('Failed to record payments')
  510. ->deselectRecordsAfterCompletion()
  511. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  512. $isInvalid = $records->contains(fn (Bill $bill) => ! $bill->canRecordPayment());
  513. if ($isInvalid) {
  514. Notification::make()
  515. ->title('Payment recording failed')
  516. ->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.')
  517. ->persistent()
  518. ->danger()
  519. ->send();
  520. $action->cancel(true);
  521. }
  522. })
  523. ->mountUsing(function (Collection $records, Form $form) {
  524. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  525. $form->fill([
  526. 'posted_at' => now(),
  527. 'amount' => CurrencyConverter::convertCentsToFormatSimple($totalAmountDue),
  528. ]);
  529. })
  530. ->form([
  531. Forms\Components\DatePicker::make('posted_at')
  532. ->label('Date'),
  533. Forms\Components\TextInput::make('amount')
  534. ->label('Amount')
  535. ->required()
  536. ->money()
  537. ->rules([
  538. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  539. if (! CurrencyConverter::isValidAmount($value)) {
  540. $fail('Please enter a valid amount');
  541. }
  542. },
  543. ]),
  544. Forms\Components\Select::make('payment_method')
  545. ->label('Payment method')
  546. ->required()
  547. ->options(PaymentMethod::class),
  548. Forms\Components\Select::make('bank_account_id')
  549. ->label('Account')
  550. ->required()
  551. ->options(function () {
  552. return BankAccount::query()
  553. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  554. ->select(['bank_accounts.id', 'accounts.name'])
  555. ->pluck('accounts.name', 'bank_accounts.id')
  556. ->toArray();
  557. })
  558. ->searchable(),
  559. Forms\Components\Textarea::make('notes')
  560. ->label('Notes'),
  561. ])
  562. ->before(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  563. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  564. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  565. if ($totalPaymentAmount > $totalAmountDue) {
  566. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  567. Notification::make()
  568. ->title('Excess payment amount')
  569. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  570. ->persistent()
  571. ->warning()
  572. ->send();
  573. $action->halt(true);
  574. }
  575. })
  576. ->action(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  577. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  578. $remainingAmount = $totalPaymentAmount;
  579. $records->each(function (Bill $record) use (&$remainingAmount, $data) {
  580. $amountDue = $record->getRawOriginal('amount_due');
  581. if ($amountDue <= 0 || $remainingAmount <= 0) {
  582. return;
  583. }
  584. $paymentAmount = min($amountDue, $remainingAmount);
  585. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  586. $record->recordPayment($data);
  587. $remainingAmount -= $paymentAmount;
  588. });
  589. $action->success();
  590. }),
  591. ]),
  592. ]);
  593. }
  594. public static function getPages(): array
  595. {
  596. return [
  597. 'index' => Pages\ListBills::route('/'),
  598. 'create' => Pages\CreateBill::route('/create'),
  599. 'view' => Pages\ViewBill::route('/{record}'),
  600. 'edit' => Pages\EditBill::route('/{record}/edit'),
  601. ];
  602. }
  603. public static function getWidgets(): array
  604. {
  605. return [
  606. BillResource\Widgets\BillOverview::class,
  607. ];
  608. }
  609. }