Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

BillResource.php 37KB

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