Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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