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

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