Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

BillResource.php 34KB

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