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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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\Exports\Accounting\BillExporter;
  14. use App\Filament\Forms\Components\CreateAdjustmentSelect;
  15. use App\Filament\Forms\Components\CreateCurrencySelect;
  16. use App\Filament\Forms\Components\CreateOfferingSelect;
  17. use App\Filament\Forms\Components\CreateVendorSelect;
  18. use App\Filament\Forms\Components\CustomTableRepeater;
  19. use App\Filament\Forms\Components\DocumentTotals;
  20. use App\Filament\Tables\Actions\ReplicateBulkAction;
  21. use App\Filament\Tables\Columns;
  22. use App\Filament\Tables\Filters\DateRangeFilter;
  23. use App\Models\Accounting\Adjustment;
  24. use App\Models\Accounting\Bill;
  25. use App\Models\Accounting\DocumentLineItem;
  26. use App\Models\Banking\BankAccount;
  27. use App\Models\Common\Offering;
  28. use App\Models\Common\Vendor;
  29. use App\Services\CompanySettingsService;
  30. use App\Utilities\Currency\CurrencyAccessor;
  31. use App\Utilities\Currency\CurrencyConverter;
  32. use App\Utilities\RateCalculator;
  33. use Awcodes\TableRepeater\Header;
  34. use Closure;
  35. use Filament\Forms;
  36. use Filament\Forms\Form;
  37. use Filament\Resources\Resource;
  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\Support\Carbon;
  44. use Illuminate\Support\Facades\Auth;
  45. class BillResource extends Resource
  46. {
  47. protected static ?string $model = Bill::class;
  48. public static function form(Form $form): Form
  49. {
  50. $company = Auth::user()->currentCompany;
  51. $settings = $company->defaultBill;
  52. return $form
  53. ->schema([
  54. Forms\Components\Section::make('Bill Details')
  55. ->schema([
  56. Forms\Components\Split::make([
  57. Forms\Components\Group::make([
  58. CreateVendorSelect::make('vendor_id')
  59. ->label('Vendor')
  60. ->required()
  61. ->live()
  62. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  63. if (! $state) {
  64. return;
  65. }
  66. $currencyCode = Vendor::find($state)?->currency_code;
  67. if ($currencyCode) {
  68. $set('currency_code', $currencyCode);
  69. }
  70. }),
  71. CreateCurrencySelect::make('currency_code'),
  72. ]),
  73. Forms\Components\Group::make([
  74. Forms\Components\TextInput::make('bill_number')
  75. ->label('Bill number')
  76. ->default(static fn () => Bill::getNextDocumentNumber())
  77. ->required(),
  78. Forms\Components\TextInput::make('order_number')
  79. ->label('P.O/S.O Number'),
  80. Cluster::make([
  81. Forms\Components\DatePicker::make('date')
  82. ->label('Bill date')
  83. ->live()
  84. ->default(now())
  85. ->timezone(CompanySettingsService::getDefaultTimezone())
  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. ->timezone(CompanySettingsService::getDefaultTimezone())
  135. ->required()
  136. ->live()
  137. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  138. if (! $state) {
  139. return;
  140. }
  141. $date = $get('date');
  142. $paymentTerms = $get('payment_terms');
  143. if (! $date || $paymentTerms === 'custom' || ! $paymentTerms) {
  144. return;
  145. }
  146. $term = PaymentTerms::parse($paymentTerms);
  147. $expected = Carbon::parse($date)->addDays($term->getDays());
  148. if (! Carbon::parse($state)->isSameDay($expected)) {
  149. $set('payment_terms', 'custom');
  150. }
  151. }),
  152. Forms\Components\Select::make('discount_method')
  153. ->label('Discount method')
  154. ->options(DocumentDiscountMethod::class)
  155. ->softRequired()
  156. ->default($settings->discount_method)
  157. ->afterStateUpdated(function ($state, Forms\Set $set) {
  158. $discountMethod = DocumentDiscountMethod::parse($state);
  159. if ($discountMethod->isPerDocument()) {
  160. $set('lineItems.*.purchaseDiscounts', []);
  161. }
  162. })
  163. ->live(),
  164. ])->grow(true),
  165. ])->from('md'),
  166. CustomTableRepeater::make('lineItems')
  167. ->hiddenLabel()
  168. ->relationship()
  169. ->saveRelationshipsUsing(null)
  170. ->dehydrated(true)
  171. ->reorderable()
  172. ->orderColumn('line_number')
  173. ->reorderAtStart()
  174. ->cloneable()
  175. ->addActionLabel('Add an item')
  176. ->headers(function (Forms\Get $get) use ($settings) {
  177. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  178. $headers = [
  179. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  180. ->width('30%'),
  181. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  182. ->width('10%'),
  183. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  184. ->width('10%'),
  185. ];
  186. if ($hasDiscounts) {
  187. $headers[] = Header::make('Adjustments')->width('30%');
  188. } else {
  189. $headers[] = Header::make('Taxes')->width('30%');
  190. }
  191. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  192. ->width('10%')
  193. ->align('right');
  194. return $headers;
  195. })
  196. ->schema([
  197. Forms\Components\Group::make([
  198. CreateOfferingSelect::make('offering_id')
  199. ->label('Item')
  200. ->hiddenLabel()
  201. ->placeholder('Select item')
  202. ->required()
  203. ->live()
  204. ->inlineSuffix()
  205. ->purchasable()
  206. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state, ?DocumentLineItem $record) {
  207. $offeringId = $state;
  208. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  209. $isPerLineItem = $discountMethod->isPerLineItem();
  210. $existingTaxIds = [];
  211. $existingDiscountIds = [];
  212. if ($record) {
  213. $existingTaxIds = $record->purchaseTaxes()->pluck('adjustments.id')->toArray();
  214. if ($isPerLineItem) {
  215. $existingDiscountIds = $record->purchaseDiscounts()->pluck('adjustments.id')->toArray();
  216. }
  217. }
  218. $with = [
  219. 'purchaseTaxes' => static function ($query) use ($existingTaxIds) {
  220. $query->where(static function ($query) use ($existingTaxIds) {
  221. $query->where('status', AdjustmentStatus::Active)
  222. ->orWhereIn('adjustments.id', $existingTaxIds);
  223. });
  224. },
  225. ];
  226. if ($isPerLineItem) {
  227. $with['purchaseDiscounts'] = static function ($query) use ($existingDiscountIds) {
  228. $query->where(static function ($query) use ($existingDiscountIds) {
  229. $query->where('status', AdjustmentStatus::Active)
  230. ->orWhereIn('adjustments.id', $existingDiscountIds);
  231. });
  232. };
  233. }
  234. $offeringRecord = Offering::with($with)->find($offeringId);
  235. if (! $offeringRecord) {
  236. return;
  237. }
  238. $unitPrice = CurrencyConverter::convertCentsToFormatSimple($offeringRecord->price, 'USD');
  239. $set('description', $offeringRecord->description);
  240. $set('unit_price', $unitPrice);
  241. $set('purchaseTaxes', $offeringRecord->purchaseTaxes->pluck('id')->toArray());
  242. if ($isPerLineItem) {
  243. $set('purchaseDiscounts', $offeringRecord->purchaseDiscounts->pluck('id')->toArray());
  244. }
  245. }),
  246. Forms\Components\TextInput::make('description')
  247. ->placeholder('Enter item description')
  248. ->hiddenLabel(),
  249. ])->columnSpan(1),
  250. Forms\Components\TextInput::make('quantity')
  251. ->required()
  252. ->numeric()
  253. ->live()
  254. ->maxValue(9999999999.99)
  255. ->default(1),
  256. Forms\Components\TextInput::make('unit_price')
  257. ->hiddenLabel()
  258. ->money(useAffix: false)
  259. ->live()
  260. ->default(0),
  261. Forms\Components\Group::make([
  262. CreateAdjustmentSelect::make('purchaseTaxes')
  263. ->label('Taxes')
  264. ->hiddenLabel()
  265. ->placeholder('Select taxes')
  266. ->category(AdjustmentCategory::Tax)
  267. ->type(AdjustmentType::Purchase)
  268. ->adjustmentsRelationship('purchaseTaxes')
  269. ->saveRelationshipsUsing(null)
  270. ->dehydrated(true)
  271. ->inlineSuffix()
  272. ->preload()
  273. ->multiple()
  274. ->live()
  275. ->searchable(),
  276. CreateAdjustmentSelect::make('purchaseDiscounts')
  277. ->label('Discounts')
  278. ->hiddenLabel()
  279. ->placeholder('Select discounts')
  280. ->category(AdjustmentCategory::Discount)
  281. ->type(AdjustmentType::Purchase)
  282. ->adjustmentsRelationship('purchaseDiscounts')
  283. ->saveRelationshipsUsing(null)
  284. ->dehydrated(true)
  285. ->inlineSuffix()
  286. ->multiple()
  287. ->live()
  288. ->hidden(function (Forms\Get $get) {
  289. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  290. return $discountMethod->isPerDocument();
  291. })
  292. ->searchable(),
  293. ])->columnSpan(1),
  294. Forms\Components\Placeholder::make('total')
  295. ->hiddenLabel()
  296. ->extraAttributes(['class' => 'text-left sm:text-right'])
  297. ->content(function (Forms\Get $get) {
  298. $quantity = max((float) ($get('quantity') ?? 0), 0);
  299. $unitPrice = CurrencyConverter::isValidAmount($get('unit_price'), 'USD')
  300. ? CurrencyConverter::convertToFloat($get('unit_price'), 'USD')
  301. : 0;
  302. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  303. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  304. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  305. $subtotal = $quantity * $unitPrice;
  306. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  307. $taxAmountInCents = Adjustment::whereIn('id', $purchaseTaxes)
  308. ->get()
  309. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  310. if ($adjustment->computation->isPercentage()) {
  311. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  312. } else {
  313. return $adjustment->getRawOriginal('rate');
  314. }
  315. });
  316. $discountAmountInCents = Adjustment::whereIn('id', $purchaseDiscounts)
  317. ->get()
  318. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  319. if ($adjustment->computation->isPercentage()) {
  320. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  321. } else {
  322. return $adjustment->getRawOriginal('rate');
  323. }
  324. });
  325. // Final total
  326. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  327. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  328. }),
  329. ]),
  330. DocumentTotals::make()
  331. ->type(DocumentType::Bill),
  332. ]),
  333. ]);
  334. }
  335. public static function table(Table $table): Table
  336. {
  337. return $table
  338. ->defaultSort('due_date')
  339. ->columns([
  340. Columns::id(),
  341. Tables\Columns\TextColumn::make('status')
  342. ->badge()
  343. ->searchable(),
  344. Tables\Columns\TextColumn::make('due_date')
  345. ->label('Due')
  346. ->asRelativeDay()
  347. ->sortable(),
  348. Tables\Columns\TextColumn::make('date')
  349. ->date()
  350. ->sortable(),
  351. Tables\Columns\TextColumn::make('bill_number')
  352. ->label('Number')
  353. ->searchable()
  354. ->sortable(),
  355. Tables\Columns\TextColumn::make('vendor.name')
  356. ->sortable()
  357. ->searchable()
  358. ->hiddenOn(BillsRelationManager::class),
  359. Tables\Columns\TextColumn::make('total')
  360. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  361. ->sortable()
  362. ->toggleable(),
  363. Tables\Columns\TextColumn::make('amount_paid')
  364. ->label('Amount paid')
  365. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  366. ->sortable()
  367. ->toggleable(),
  368. Tables\Columns\TextColumn::make('amount_due')
  369. ->label('Amount due')
  370. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  371. ->sortable(),
  372. ])
  373. ->filters([
  374. Tables\Filters\SelectFilter::make('vendor')
  375. ->relationship('vendor', 'name')
  376. ->searchable()
  377. ->preload()
  378. ->hiddenOn(BillsRelationManager::class),
  379. Tables\Filters\SelectFilter::make('status')
  380. ->options(BillStatus::class)
  381. ->native(false),
  382. Tables\Filters\TernaryFilter::make('has_payments')
  383. ->label('Has payments')
  384. ->queries(
  385. true: fn (Builder $query) => $query->whereHas('payments'),
  386. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  387. ),
  388. DateRangeFilter::make('date')
  389. ->fromLabel('From date')
  390. ->untilLabel('To date')
  391. ->indicatorLabel('Date'),
  392. DateRangeFilter::make('due_date')
  393. ->fromLabel('From due date')
  394. ->untilLabel('To due date')
  395. ->indicatorLabel('Due'),
  396. ])
  397. ->headerActions([
  398. Tables\Actions\ExportAction::make()
  399. ->exporter(BillExporter::class),
  400. ])
  401. ->actions([
  402. Tables\Actions\ActionGroup::make([
  403. Tables\Actions\ActionGroup::make([
  404. Tables\Actions\EditAction::make()
  405. ->url(static fn (Bill $record) => Pages\EditBill::getUrl(['record' => $record])),
  406. Tables\Actions\ViewAction::make()
  407. ->url(static fn (Bill $record) => Pages\ViewBill::getUrl(['record' => $record])),
  408. Bill::getReplicateAction(Tables\Actions\ReplicateAction::class),
  409. Tables\Actions\Action::make('recordPayment')
  410. ->label('Record payment')
  411. ->slideOver()
  412. ->modalWidth(MaxWidth::TwoExtraLarge)
  413. ->icon('heroicon-m-credit-card')
  414. ->visible(function (Bill $record) {
  415. return $record->canRecordPayment();
  416. })
  417. ->mountUsing(function (Bill $record, Form $form) {
  418. $form->fill([
  419. 'posted_at' => now(),
  420. 'amount' => $record->amount_due,
  421. ]);
  422. })
  423. ->databaseTransaction()
  424. ->successNotificationTitle('Payment recorded')
  425. ->form([
  426. Forms\Components\DatePicker::make('posted_at')
  427. ->label('Date'),
  428. Forms\Components\Grid::make()
  429. ->schema([
  430. Forms\Components\Select::make('bank_account_id')
  431. ->label('Account')
  432. ->required()
  433. ->live()
  434. ->options(function () {
  435. return BankAccount::query()
  436. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  437. ->select(['bank_accounts.id', 'accounts.name', 'accounts.currency_code'])
  438. ->get()
  439. ->mapWithKeys(function ($account) {
  440. $label = $account->name;
  441. if ($account->currency_code) {
  442. $label .= " ({$account->currency_code})";
  443. }
  444. return [$account->id => $label];
  445. })
  446. ->toArray();
  447. })
  448. ->searchable(),
  449. Forms\Components\TextInput::make('amount')
  450. ->label('Amount')
  451. ->required()
  452. ->money(fn (Bill $record) => $record->currency_code)
  453. ->live(onBlur: true)
  454. ->helperText(function (Bill $record, $state) {
  455. $billCurrency = $record->currency_code;
  456. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  457. return null;
  458. }
  459. $amountDue = $record->amount_due;
  460. $amount = CurrencyConverter::convertToCents($state, 'USD');
  461. if ($amount <= 0) {
  462. return 'Please enter a valid positive amount';
  463. }
  464. $newAmountDue = $amountDue - $amount;
  465. return match (true) {
  466. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $billCurrency),
  467. $newAmountDue === 0 => 'Bill will be fully paid',
  468. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $billCurrency),
  469. };
  470. })
  471. ->rules([
  472. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  473. if (! CurrencyConverter::isValidAmount($value, 'USD')) {
  474. $fail('Please enter a valid amount');
  475. }
  476. },
  477. ]),
  478. ])->columns(2),
  479. Forms\Components\Placeholder::make('currency_conversion')
  480. ->label('Currency Conversion')
  481. ->content(function (Forms\Get $get, Bill $record) {
  482. $amount = $get('amount');
  483. $bankAccountId = $get('bank_account_id');
  484. $billCurrency = $record->currency_code;
  485. if (empty($amount) || empty($bankAccountId) || ! CurrencyConverter::isValidAmount($amount, 'USD')) {
  486. return null;
  487. }
  488. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  489. if (! $bankAccount) {
  490. return null;
  491. }
  492. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  493. // If currencies are the same, no conversion needed
  494. if ($billCurrency === $bankCurrency) {
  495. return null;
  496. }
  497. // Convert amount from bill currency to bank currency
  498. $amountInBillCurrencyCents = CurrencyConverter::convertToCents($amount, 'USD');
  499. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  500. $amountInBillCurrencyCents,
  501. $billCurrency,
  502. $bankCurrency
  503. );
  504. $formattedBankAmount = CurrencyConverter::formatCentsToMoney($amountInBankCurrencyCents, $bankCurrency);
  505. return "Payment will be recorded as {$formattedBankAmount} in the bank account's currency ({$bankCurrency}).";
  506. })
  507. ->hidden(function (Forms\Get $get, Bill $record) {
  508. $bankAccountId = $get('bank_account_id');
  509. if (empty($bankAccountId)) {
  510. return true;
  511. }
  512. $billCurrency = $record->currency_code;
  513. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  514. if (! $bankAccount) {
  515. return true;
  516. }
  517. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  518. // Hide if currencies are the same
  519. return $billCurrency === $bankCurrency;
  520. }),
  521. Forms\Components\Select::make('payment_method')
  522. ->label('Payment method')
  523. ->required()
  524. ->options(PaymentMethod::class),
  525. Forms\Components\Textarea::make('notes')
  526. ->label('Notes'),
  527. ])
  528. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  529. $record->recordPayment($data);
  530. $action->success();
  531. }),
  532. ])->dropdown(false),
  533. Tables\Actions\DeleteAction::make(),
  534. ]),
  535. ])
  536. ->bulkActions([
  537. Tables\Actions\BulkActionGroup::make([
  538. Tables\Actions\DeleteBulkAction::make(),
  539. ReplicateBulkAction::make()
  540. ->label('Replicate')
  541. ->modalWidth(MaxWidth::Large)
  542. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  543. ->successNotificationTitle('Bills replicated successfully')
  544. ->failureNotificationTitle('Failed to replicate bills')
  545. ->databaseTransaction()
  546. ->deselectRecordsAfterCompletion()
  547. ->excludeAttributes([
  548. 'status',
  549. 'amount_paid',
  550. 'amount_due',
  551. 'created_by',
  552. 'updated_by',
  553. 'created_at',
  554. 'updated_at',
  555. 'bill_number',
  556. 'date',
  557. 'due_date',
  558. 'paid_at',
  559. ])
  560. ->beforeReplicaSaved(function (Bill $replica) {
  561. $replica->status = BillStatus::Open;
  562. $replica->bill_number = Bill::getNextDocumentNumber();
  563. $replica->date = now();
  564. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  565. })
  566. ->withReplicatedRelationships(['lineItems'])
  567. ->withExcludedRelationshipAttributes('lineItems', [
  568. 'subtotal',
  569. 'total',
  570. 'created_by',
  571. 'updated_by',
  572. 'created_at',
  573. 'updated_at',
  574. ]),
  575. ]),
  576. ]);
  577. }
  578. public static function getPages(): array
  579. {
  580. return [
  581. 'index' => Pages\ListBills::route('/'),
  582. 'pay-bills' => Pages\PayBills::route('/pay-bills'),
  583. 'create' => Pages\CreateBill::route('/create'),
  584. 'view' => Pages\ViewBill::route('/{record}'),
  585. 'edit' => Pages\EditBill::route('/{record}/edit'),
  586. ];
  587. }
  588. public static function getWidgets(): array
  589. {
  590. return [
  591. BillResource\Widgets\BillOverview::class,
  592. ];
  593. }
  594. }