Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

BillResource.php 36KB

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