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

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