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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. <?php
  2. namespace App\Filament\Company\Resources\Purchases;
  3. use App\Enums\Accounting\BillStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Filament\Company\Resources\Purchases\BillResource\Pages;
  6. use App\Filament\Tables\Actions\ReplicateBulkAction;
  7. use App\Filament\Tables\Filters\DateRangeFilter;
  8. use App\Models\Accounting\Adjustment;
  9. use App\Models\Accounting\Bill;
  10. use App\Models\Accounting\DocumentLineItem;
  11. use App\Models\Banking\BankAccount;
  12. use App\Models\Common\Offering;
  13. use App\Utilities\Currency\CurrencyConverter;
  14. use Awcodes\TableRepeater\Components\TableRepeater;
  15. use Awcodes\TableRepeater\Header;
  16. use Closure;
  17. use Filament\Forms;
  18. use Filament\Forms\Form;
  19. use Filament\Notifications\Notification;
  20. use Filament\Resources\Resource;
  21. use Filament\Support\Enums\Alignment;
  22. use Filament\Support\Enums\MaxWidth;
  23. use Filament\Tables;
  24. use Filament\Tables\Table;
  25. use Illuminate\Database\Eloquent\Builder;
  26. use Illuminate\Database\Eloquent\Collection;
  27. use Illuminate\Database\Eloquent\Model;
  28. use Illuminate\Support\Facades\Auth;
  29. class BillResource extends Resource
  30. {
  31. protected static ?string $model = Bill::class;
  32. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  33. public static function form(Form $form): Form
  34. {
  35. $company = Auth::user()->currentCompany;
  36. return $form
  37. ->schema([
  38. Forms\Components\Section::make('Bill Details')
  39. ->schema([
  40. Forms\Components\Split::make([
  41. Forms\Components\Group::make([
  42. Forms\Components\Select::make('vendor_id')
  43. ->relationship('vendor', 'name')
  44. ->preload()
  45. ->searchable()
  46. ->required(),
  47. ]),
  48. Forms\Components\Group::make([
  49. Forms\Components\TextInput::make('bill_number')
  50. ->label('Bill Number')
  51. ->default(fn () => Bill::getNextDocumentNumber())
  52. ->required(),
  53. Forms\Components\TextInput::make('order_number')
  54. ->label('P.O/S.O Number'),
  55. Forms\Components\DatePicker::make('date')
  56. ->label('Bill Date')
  57. ->default(now())
  58. ->disabled(function (?Bill $record) {
  59. return $record?->hasPayments();
  60. })
  61. ->required(),
  62. Forms\Components\DatePicker::make('due_date')
  63. ->label('Due Date')
  64. ->default(function () use ($company) {
  65. return now()->addDays($company->defaultBill->payment_terms->getDays());
  66. })
  67. ->required(),
  68. ])->grow(true),
  69. ])->from('md'),
  70. TableRepeater::make('lineItems')
  71. ->relationship()
  72. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  73. if (! is_array($state)) {
  74. $state = [];
  75. }
  76. $relationship = $component->getRelationship();
  77. $existingRecords = $component->getCachedExistingRecords();
  78. $recordsToDelete = [];
  79. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  80. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  81. continue;
  82. }
  83. $recordsToDelete[] = $keyToCheckForDeletion;
  84. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  85. }
  86. $relationship
  87. ->whereKey($recordsToDelete)
  88. ->get()
  89. ->each(static fn (Model $record) => $record->delete());
  90. $childComponentContainers = $component->getChildComponentContainers(
  91. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  92. );
  93. $itemOrder = 1;
  94. $orderColumn = $component->getOrderColumn();
  95. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  96. foreach ($childComponentContainers as $itemKey => $item) {
  97. $itemData = $item->getState(shouldCallHooksBefore: false);
  98. if ($orderColumn) {
  99. $itemData[$orderColumn] = $itemOrder;
  100. $itemOrder++;
  101. }
  102. if ($record = ($existingRecords[$itemKey] ?? null)) {
  103. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  104. if ($itemData === null) {
  105. continue;
  106. }
  107. $translatableContentDriver ?
  108. $translatableContentDriver->updateRecord($record, $itemData) :
  109. $record->fill($itemData)->save();
  110. continue;
  111. }
  112. $relatedModel = $component->getRelatedModel();
  113. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  114. if ($itemData === null) {
  115. continue;
  116. }
  117. if ($translatableContentDriver) {
  118. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  119. } else {
  120. $record = new $relatedModel;
  121. $record->fill($itemData);
  122. }
  123. $record = $relationship->save($record);
  124. $item->model($record)->saveRelationships();
  125. $existingRecords->push($record);
  126. }
  127. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  128. /** @var Bill $bill */
  129. $bill = $component->getRecord();
  130. // Recalculate totals for line items
  131. $bill->lineItems()->each(function (DocumentLineItem $lineItem) {
  132. $lineItem->updateQuietly([
  133. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  134. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  135. ]);
  136. });
  137. $subtotal = $bill->lineItems()->sum('subtotal') / 100;
  138. $taxTotal = $bill->lineItems()->sum('tax_total') / 100;
  139. $discountTotal = $bill->lineItems()->sum('discount_total') / 100;
  140. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  141. $bill->updateQuietly([
  142. 'subtotal' => $subtotal,
  143. 'tax_total' => $taxTotal,
  144. 'discount_total' => $discountTotal,
  145. 'total' => $grandTotal,
  146. ]);
  147. $bill->refresh();
  148. if (! $bill->initialTransaction) {
  149. $bill->createInitialTransaction();
  150. } else {
  151. $bill->updateInitialTransaction();
  152. }
  153. })
  154. ->headers([
  155. Header::make('Items')->width('15%'),
  156. Header::make('Description')->width('25%'),
  157. Header::make('Quantity')->width('10%'),
  158. Header::make('Price')->width('10%'),
  159. Header::make('Taxes')->width('15%'),
  160. Header::make('Discounts')->width('15%'),
  161. Header::make('Amount')->width('10%')->align('right'),
  162. ])
  163. ->schema([
  164. Forms\Components\Select::make('offering_id')
  165. ->relationship('purchasableOffering', 'name')
  166. ->preload()
  167. ->searchable()
  168. ->required()
  169. ->live()
  170. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  171. $offeringId = $state;
  172. $offeringRecord = Offering::with(['purchaseTaxes', 'purchaseDiscounts'])->find($offeringId);
  173. if ($offeringRecord) {
  174. $set('description', $offeringRecord->description);
  175. $set('unit_price', $offeringRecord->price);
  176. $set('purchaseTaxes', $offeringRecord->purchaseTaxes->pluck('id')->toArray());
  177. $set('purchaseDiscounts', $offeringRecord->purchaseDiscounts->pluck('id')->toArray());
  178. }
  179. }),
  180. Forms\Components\TextInput::make('description'),
  181. Forms\Components\TextInput::make('quantity')
  182. ->required()
  183. ->numeric()
  184. ->live()
  185. ->default(1),
  186. Forms\Components\TextInput::make('unit_price')
  187. ->hiddenLabel()
  188. ->numeric()
  189. ->live()
  190. ->default(0),
  191. Forms\Components\Select::make('purchaseTaxes')
  192. ->relationship('purchaseTaxes', 'name')
  193. ->preload()
  194. ->multiple()
  195. ->live()
  196. ->searchable(),
  197. Forms\Components\Select::make('purchaseDiscounts')
  198. ->relationship('purchaseDiscounts', 'name')
  199. ->preload()
  200. ->multiple()
  201. ->live()
  202. ->searchable(),
  203. Forms\Components\Placeholder::make('total')
  204. ->hiddenLabel()
  205. ->content(function (Forms\Get $get) {
  206. $quantity = max((float) ($get('quantity') ?? 0), 0);
  207. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  208. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  209. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  210. $subtotal = $quantity * $unitPrice;
  211. // Calculate tax amount based on subtotal
  212. $taxAmount = 0;
  213. if (! empty($purchaseTaxes)) {
  214. $taxRates = Adjustment::whereIn('id', $purchaseTaxes)->pluck('rate');
  215. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  216. }
  217. // Calculate discount amount based on subtotal
  218. $discountAmount = 0;
  219. if (! empty($purchaseDiscounts)) {
  220. $discountRates = Adjustment::whereIn('id', $purchaseDiscounts)->pluck('rate');
  221. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  222. }
  223. // Final total
  224. $total = $subtotal + ($taxAmount - $discountAmount);
  225. return CurrencyConverter::formatToMoney($total);
  226. }),
  227. ]),
  228. Forms\Components\Grid::make(6)
  229. ->schema([
  230. Forms\Components\ViewField::make('totals')
  231. ->columnStart(5)
  232. ->columnSpan(2)
  233. ->view('filament.forms.components.bill-totals'),
  234. ]),
  235. ]),
  236. ]);
  237. }
  238. public static function table(Table $table): Table
  239. {
  240. return $table
  241. ->defaultSort('due_date')
  242. ->columns([
  243. Tables\Columns\TextColumn::make('status')
  244. ->badge()
  245. ->searchable(),
  246. Tables\Columns\TextColumn::make('due_date')
  247. ->label('Due')
  248. ->asRelativeDay()
  249. ->sortable(),
  250. Tables\Columns\TextColumn::make('date')
  251. ->date()
  252. ->sortable(),
  253. Tables\Columns\TextColumn::make('bill_number')
  254. ->label('Number')
  255. ->searchable()
  256. ->sortable(),
  257. Tables\Columns\TextColumn::make('vendor.name')
  258. ->sortable(),
  259. Tables\Columns\TextColumn::make('total')
  260. ->currency()
  261. ->sortable(),
  262. Tables\Columns\TextColumn::make('amount_paid')
  263. ->label('Amount Paid')
  264. ->currency()
  265. ->sortable(),
  266. Tables\Columns\TextColumn::make('amount_due')
  267. ->label('Amount Due')
  268. ->currency()
  269. ->sortable(),
  270. ])
  271. ->filters([
  272. Tables\Filters\SelectFilter::make('vendor')
  273. ->relationship('vendor', 'name')
  274. ->searchable()
  275. ->preload(),
  276. Tables\Filters\SelectFilter::make('status')
  277. ->options(BillStatus::class)
  278. ->native(false),
  279. Tables\Filters\TernaryFilter::make('has_payments')
  280. ->label('Has Payments')
  281. ->queries(
  282. true: fn (Builder $query) => $query->whereHas('payments'),
  283. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  284. ),
  285. DateRangeFilter::make('date')
  286. ->fromLabel('From Date')
  287. ->untilLabel('To Date')
  288. ->indicatorLabel('Date'),
  289. DateRangeFilter::make('due_date')
  290. ->fromLabel('From Due Date')
  291. ->untilLabel('To Due Date')
  292. ->indicatorLabel('Due'),
  293. ])
  294. ->actions([
  295. Tables\Actions\ActionGroup::make([
  296. Tables\Actions\EditAction::make(),
  297. Tables\Actions\ViewAction::make(),
  298. Tables\Actions\DeleteAction::make(),
  299. Bill::getReplicateAction(Tables\Actions\ReplicateAction::class),
  300. Tables\Actions\Action::make('recordPayment')
  301. ->label('Record Payment')
  302. ->stickyModalHeader()
  303. ->stickyModalFooter()
  304. ->modalFooterActionsAlignment(Alignment::End)
  305. ->modalWidth(MaxWidth::TwoExtraLarge)
  306. ->icon('heroicon-o-credit-card')
  307. ->visible(function (Bill $record) {
  308. return $record->canRecordPayment();
  309. })
  310. ->mountUsing(function (Bill $record, Form $form) {
  311. $form->fill([
  312. 'posted_at' => now(),
  313. 'amount' => $record->amount_due,
  314. ]);
  315. })
  316. ->databaseTransaction()
  317. ->successNotificationTitle('Payment Recorded')
  318. ->form([
  319. Forms\Components\DatePicker::make('posted_at')
  320. ->label('Date'),
  321. Forms\Components\TextInput::make('amount')
  322. ->label('Amount')
  323. ->required()
  324. ->money()
  325. ->live(onBlur: true)
  326. ->helperText(function (Bill $record, $state) {
  327. if (! CurrencyConverter::isValidAmount($state)) {
  328. return null;
  329. }
  330. $amountDue = $record->getRawOriginal('amount_due');
  331. $amount = CurrencyConverter::convertToCents($state);
  332. if ($amount <= 0) {
  333. return 'Please enter a valid positive amount';
  334. }
  335. $newAmountDue = $amountDue - $amount;
  336. return match (true) {
  337. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue),
  338. $newAmountDue === 0 => 'Bill will be fully paid',
  339. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue)),
  340. };
  341. })
  342. ->rules([
  343. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  344. if (! CurrencyConverter::isValidAmount($value)) {
  345. $fail('Please enter a valid amount');
  346. }
  347. },
  348. ]),
  349. Forms\Components\Select::make('payment_method')
  350. ->label('Payment Method')
  351. ->required()
  352. ->options(PaymentMethod::class),
  353. Forms\Components\Select::make('bank_account_id')
  354. ->label('Account')
  355. ->required()
  356. ->options(BankAccount::query()
  357. ->get()
  358. ->pluck('account.name', 'id'))
  359. ->searchable(),
  360. Forms\Components\Textarea::make('notes')
  361. ->label('Notes'),
  362. ])
  363. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  364. $record->recordPayment($data);
  365. $action->success();
  366. }),
  367. ]),
  368. ])
  369. ->bulkActions([
  370. Tables\Actions\BulkActionGroup::make([
  371. Tables\Actions\DeleteBulkAction::make(),
  372. ReplicateBulkAction::make()
  373. ->label('Replicate')
  374. ->modalWidth(MaxWidth::Large)
  375. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  376. ->successNotificationTitle('Bills Replicated Successfully')
  377. ->failureNotificationTitle('Failed to Replicate Bills')
  378. ->databaseTransaction()
  379. ->deselectRecordsAfterCompletion()
  380. ->excludeAttributes([
  381. 'status',
  382. 'amount_paid',
  383. 'amount_due',
  384. 'created_by',
  385. 'updated_by',
  386. 'created_at',
  387. 'updated_at',
  388. 'bill_number',
  389. 'date',
  390. 'due_date',
  391. 'paid_at',
  392. ])
  393. ->beforeReplicaSaved(function (Bill $replica) {
  394. $replica->status = BillStatus::Unpaid;
  395. $replica->bill_number = Bill::getNextDocumentNumber();
  396. $replica->date = now();
  397. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  398. })
  399. ->withReplicatedRelationships(['lineItems'])
  400. ->withExcludedRelationshipAttributes('lineItems', [
  401. 'subtotal',
  402. 'total',
  403. 'created_by',
  404. 'updated_by',
  405. 'created_at',
  406. 'updated_at',
  407. ]),
  408. Tables\Actions\BulkAction::make('recordPayments')
  409. ->label('Record Payments')
  410. ->icon('heroicon-o-credit-card')
  411. ->stickyModalHeader()
  412. ->stickyModalFooter()
  413. ->modalFooterActionsAlignment(Alignment::End)
  414. ->modalWidth(MaxWidth::TwoExtraLarge)
  415. ->databaseTransaction()
  416. ->successNotificationTitle('Payments Recorded')
  417. ->failureNotificationTitle('Failed to Record Payments')
  418. ->deselectRecordsAfterCompletion()
  419. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  420. $cantRecordPayments = $records->contains(fn (Bill $bill) => ! $bill->canRecordPayment());
  421. if ($cantRecordPayments) {
  422. Notification::make()
  423. ->title('Payment Recording Failed')
  424. ->body('Bills that are either paid or voided cannot be processed through bulk payments. Please adjust your selection and try again.')
  425. ->persistent()
  426. ->danger()
  427. ->send();
  428. $action->cancel(true);
  429. }
  430. })
  431. ->mountUsing(function (Collection $records, Form $form) {
  432. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  433. $form->fill([
  434. 'posted_at' => now(),
  435. 'amount' => CurrencyConverter::convertCentsToFormatSimple($totalAmountDue),
  436. ]);
  437. })
  438. ->form([
  439. Forms\Components\DatePicker::make('posted_at')
  440. ->label('Date'),
  441. Forms\Components\TextInput::make('amount')
  442. ->label('Amount')
  443. ->required()
  444. ->money()
  445. ->rules([
  446. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  447. if (! CurrencyConverter::isValidAmount($value)) {
  448. $fail('Please enter a valid amount');
  449. }
  450. },
  451. ]),
  452. Forms\Components\Select::make('payment_method')
  453. ->label('Payment Method')
  454. ->required()
  455. ->options(PaymentMethod::class),
  456. Forms\Components\Select::make('bank_account_id')
  457. ->label('Account')
  458. ->required()
  459. ->options(BankAccount::query()
  460. ->get()
  461. ->pluck('account.name', 'id'))
  462. ->searchable(),
  463. Forms\Components\Textarea::make('notes')
  464. ->label('Notes'),
  465. ])
  466. ->before(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  467. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  468. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  469. if ($totalPaymentAmount > $totalAmountDue) {
  470. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  471. Notification::make()
  472. ->title('Excess Payment Amount')
  473. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  474. ->persistent()
  475. ->warning()
  476. ->send();
  477. $action->halt(true);
  478. }
  479. })
  480. ->action(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  481. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  482. $remainingAmount = $totalPaymentAmount;
  483. $records->each(function (Bill $record) use (&$remainingAmount, $data) {
  484. $amountDue = $record->getRawOriginal('amount_due');
  485. if ($amountDue <= 0 || $remainingAmount <= 0) {
  486. return;
  487. }
  488. $paymentAmount = min($amountDue, $remainingAmount);
  489. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  490. $record->recordPayment($data);
  491. $remainingAmount -= $paymentAmount;
  492. });
  493. $action->success();
  494. }),
  495. ]),
  496. ]);
  497. }
  498. public static function getRelations(): array
  499. {
  500. return [
  501. BillResource\RelationManagers\PaymentsRelationManager::class,
  502. ];
  503. }
  504. public static function getPages(): array
  505. {
  506. return [
  507. 'index' => Pages\ListBills::route('/'),
  508. 'create' => Pages\CreateBill::route('/create'),
  509. 'view' => Pages\ViewBill::route('/{record}'),
  510. 'edit' => Pages\EditBill::route('/{record}/edit'),
  511. ];
  512. }
  513. public static function getWidgets(): array
  514. {
  515. return [
  516. BillResource\Widgets\BillOverview::class,
  517. ];
  518. }
  519. }