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

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