Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

PayBills.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <?php
  2. namespace App\Filament\Company\Resources\Purchases\BillResource\Pages;
  3. use App\Enums\Accounting\BillStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Filament\Company\Resources\Purchases\BillResource;
  6. use App\Filament\Tables\Columns\CustomTextInputColumn;
  7. use App\Models\Accounting\Bill;
  8. use App\Models\Accounting\Transaction;
  9. use App\Models\Banking\BankAccount;
  10. use App\Models\Common\Vendor;
  11. use App\Models\Setting\Currency;
  12. use App\Utilities\Currency\CurrencyAccessor;
  13. use App\Utilities\Currency\CurrencyConverter;
  14. use Filament\Actions;
  15. use Filament\Forms;
  16. use Filament\Forms\Form;
  17. use Filament\Notifications\Notification;
  18. use Filament\Resources\Pages\ListRecords;
  19. use Filament\Support\RawJs;
  20. use Filament\Tables;
  21. use Filament\Tables\Columns\Summarizers\Summarizer;
  22. use Filament\Tables\Columns\TextColumn;
  23. use Filament\Tables\Table;
  24. use Illuminate\Contracts\Support\Htmlable;
  25. use Illuminate\Database\Eloquent\Collection;
  26. use Illuminate\Database\Query\Builder;
  27. use Illuminate\Support\Str;
  28. use Livewire\Attributes\Computed;
  29. /**
  30. * @property Form $form
  31. */
  32. class PayBills extends ListRecords
  33. {
  34. protected static string $resource = BillResource::class;
  35. protected static string $view = 'filament.company.resources.purchases.bill-resource.pages.pay-bills';
  36. public array $paymentAmounts = [];
  37. public ?array $data = [];
  38. public function getBreadcrumb(): ?string
  39. {
  40. return 'Pay';
  41. }
  42. public function getTitle(): string | Htmlable
  43. {
  44. return 'Pay Bills';
  45. }
  46. public function mount(): void
  47. {
  48. parent::mount();
  49. $this->form->fill();
  50. $this->reset('tableFilters');
  51. }
  52. protected function getHeaderActions(): array
  53. {
  54. return [
  55. Actions\Action::make('processPayments')
  56. ->color('primary')
  57. ->requiresConfirmation()
  58. ->modalHeading('Confirm payments')
  59. ->modalDescription(function () {
  60. $billCount = collect($this->paymentAmounts)->filter(fn ($amount) => $amount > 0)->count();
  61. $totalAmount = array_sum($this->paymentAmounts);
  62. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  63. $totalFormatted = CurrencyConverter::formatCentsToMoney($totalAmount, $currencyCode, true);
  64. return "You are about to pay {$billCount} " . Str::plural('bill', $billCount) . " for a total of {$totalFormatted}. This action cannot be undone.";
  65. })
  66. ->action(function () {
  67. $data = $this->data;
  68. $tableRecords = $this->getTableRecords();
  69. $paidCount = 0;
  70. $totalPaid = 0;
  71. /** @var Bill $bill */
  72. foreach ($tableRecords as $bill) {
  73. if (! $bill->canRecordPayment()) {
  74. continue;
  75. }
  76. // Get the payment amount from our component state
  77. $paymentAmount = $this->getPaymentAmount($bill);
  78. if ($paymentAmount <= 0) {
  79. continue;
  80. }
  81. $paymentData = [
  82. 'posted_at' => $data['posted_at'],
  83. 'payment_method' => $data['payment_method'],
  84. 'bank_account_id' => $data['bank_account_id'],
  85. 'amount' => $paymentAmount,
  86. ];
  87. $bill->recordPayment($paymentData);
  88. $paidCount++;
  89. $totalPaid += $paymentAmount;
  90. }
  91. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  92. $totalFormatted = CurrencyConverter::formatCentsToMoney($totalPaid, $currencyCode, true);
  93. Notification::make()
  94. ->title('Bills paid successfully')
  95. ->body("Paid {$paidCount} " . Str::plural('bill', $paidCount) . " for a total of {$totalFormatted}")
  96. ->success()
  97. ->send();
  98. $this->reset('paymentAmounts');
  99. $this->resetTable();
  100. }),
  101. ];
  102. }
  103. /**
  104. * @return array<int | string, string | Form>
  105. */
  106. protected function getForms(): array
  107. {
  108. return [
  109. 'form',
  110. ];
  111. }
  112. public function form(Form $form): Form
  113. {
  114. return $form
  115. ->live()
  116. ->schema([
  117. Forms\Components\Grid::make(3)
  118. ->schema([
  119. Forms\Components\Select::make('bank_account_id')
  120. ->label('Account')
  121. ->options(static function () {
  122. return Transaction::getBankAccountOptionsFlat();
  123. })
  124. ->default(fn () => BankAccount::where('enabled', true)->first()?->id)
  125. ->selectablePlaceholder(false)
  126. ->searchable()
  127. ->softRequired(),
  128. Forms\Components\DatePicker::make('posted_at')
  129. ->label('Date')
  130. ->default(now())
  131. ->softRequired(),
  132. Forms\Components\Select::make('payment_method')
  133. ->label('Payment method')
  134. ->selectablePlaceholder(false)
  135. ->options(PaymentMethod::class)
  136. ->default(PaymentMethod::BankPayment)
  137. ->softRequired(),
  138. ]),
  139. ])->statePath('data');
  140. }
  141. public function table(Table $table): Table
  142. {
  143. return $table
  144. ->query(
  145. Bill::query()
  146. ->with(['vendor'])
  147. ->unpaid()
  148. )
  149. ->recordClasses(['is-spreadsheet'])
  150. ->defaultSort('due_date')
  151. ->paginated(false)
  152. ->columns([
  153. TextColumn::make('vendor.name')
  154. ->label('Vendor')
  155. ->sortable(),
  156. TextColumn::make('bill_number')
  157. ->label('Bill number')
  158. ->sortable(),
  159. TextColumn::make('due_date')
  160. ->label('Due date')
  161. ->defaultDateFormat()
  162. ->sortable(),
  163. Tables\Columns\TextColumn::make('status')
  164. ->badge()
  165. ->sortable(),
  166. TextColumn::make('amount_due')
  167. ->label('Amount due')
  168. ->currency(static fn (Bill $record) => $record->currency_code)
  169. ->alignEnd()
  170. ->sortable()
  171. ->summarize([
  172. Summarizer::make()
  173. ->using(function (Builder $query) {
  174. $totalAmountDue = $query->sum('amount_due');
  175. $bankAccountCurrency = $this->getSelectedBankAccount()->account->currency_code;
  176. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? $bankAccountCurrency;
  177. if ($activeCurrency !== $bankAccountCurrency) {
  178. $totalAmountDue = CurrencyConverter::convertBalance($totalAmountDue, $activeCurrency, $bankAccountCurrency);
  179. }
  180. return CurrencyConverter::formatCentsToMoney($totalAmountDue, $bankAccountCurrency, true);
  181. }),
  182. Summarizer::make()
  183. ->using(function (Builder $query) {
  184. $totalAmountDue = $query->sum('amount_due');
  185. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  186. return CurrencyConverter::formatCentsToMoney($totalAmountDue, $currencyCode, true);
  187. })
  188. ->visible(function () {
  189. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? null;
  190. $bankAccountCurrency = $this->getSelectedBankAccount()->account->currency_code;
  191. return $activeCurrency && $activeCurrency !== $bankAccountCurrency;
  192. }),
  193. ]),
  194. CustomTextInputColumn::make('payment_amount')
  195. ->label('Payment amount')
  196. ->alignEnd()
  197. ->navigable()
  198. ->mask(RawJs::make('$money($input)'))
  199. ->updateStateUsing(function (Bill $record, $state) {
  200. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  201. $this->paymentAmounts[$record->id] = 0;
  202. return '0.00';
  203. }
  204. $paymentCents = CurrencyConverter::convertToCents($state, 'USD');
  205. if ($paymentCents > $record->amount_due) {
  206. $paymentCents = $record->amount_due;
  207. }
  208. $this->paymentAmounts[$record->id] = $paymentCents;
  209. return $state;
  210. })
  211. ->getStateUsing(function (Bill $record) {
  212. $paymentAmount = $this->paymentAmounts[$record->id] ?? 0;
  213. return CurrencyConverter::convertCentsToFormatSimple($paymentAmount, 'USD');
  214. })
  215. ->summarize([
  216. Summarizer::make()
  217. ->using(function () {
  218. $total = array_sum($this->paymentAmounts);
  219. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  220. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? $defaultCurrency;
  221. if ($activeCurrency !== $defaultCurrency) {
  222. $total = CurrencyConverter::convertBalance($total, $activeCurrency, $defaultCurrency);
  223. }
  224. return CurrencyConverter::formatCentsToMoney($total, $defaultCurrency, true);
  225. }),
  226. Summarizer::make()
  227. ->using(fn () => $this->totalPaymentAmount)
  228. ->visible(function () {
  229. $activeCurrency = $this->getTableFilterState('currency_code')['value'] ?? null;
  230. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  231. return $activeCurrency && $activeCurrency !== $defaultCurrency;
  232. }),
  233. ]),
  234. ])
  235. ->bulkActions([
  236. Tables\Actions\BulkAction::make('setFullAmounts')
  237. ->label('Set full amounts')
  238. ->icon('heroicon-o-banknotes')
  239. ->color('primary')
  240. ->deselectRecordsAfterCompletion()
  241. ->action(function (Collection $records) {
  242. $records->each(function (Bill $bill) {
  243. $this->paymentAmounts[$bill->id] = $bill->amount_due;
  244. });
  245. }),
  246. Tables\Actions\BulkAction::make('clearAmounts')
  247. ->label('Clear amounts')
  248. ->icon('heroicon-o-x-mark')
  249. ->color('gray')
  250. ->deselectRecordsAfterCompletion()
  251. ->action(function (Collection $records) {
  252. $records->each(function (Bill $bill) {
  253. $this->paymentAmounts[$bill->id] = 0;
  254. });
  255. }),
  256. ])
  257. ->filters([
  258. Tables\Filters\SelectFilter::make('currency_code')
  259. ->label('Currency')
  260. ->selectablePlaceholder(false)
  261. ->default(CurrencyAccessor::getDefaultCurrency())
  262. ->options(Currency::query()->pluck('name', 'code')->toArray())
  263. ->searchable()
  264. ->resetState([
  265. 'value' => CurrencyAccessor::getDefaultCurrency(),
  266. ])
  267. ->indicateUsing(function (Tables\Filters\SelectFilter $filter, array $state) {
  268. if (blank($state['value'] ?? null)) {
  269. return [];
  270. }
  271. $label = collect($filter->getOptions())
  272. ->mapWithKeys(fn (string | array $label, string $value): array => is_array($label) ? $label : [$value => $label])
  273. ->get($state['value']);
  274. if (blank($label)) {
  275. return [];
  276. }
  277. $indicator = $filter->getLabel();
  278. return Tables\Filters\Indicator::make("{$indicator}: {$label}")->removable(false);
  279. }),
  280. Tables\Filters\SelectFilter::make('vendor_id')
  281. ->label('Vendor')
  282. ->options(fn () => Vendor::query()->pluck('name', 'id')->toArray())
  283. ->searchable(),
  284. Tables\Filters\SelectFilter::make('status')
  285. ->multiple()
  286. ->options(BillStatus::getUnpaidOptions()),
  287. ]);
  288. }
  289. protected function getPaymentAmount(Bill $record): int
  290. {
  291. return $this->paymentAmounts[$record->id] ?? 0;
  292. }
  293. #[Computed]
  294. public function totalPaymentAmount(): string
  295. {
  296. $total = array_sum($this->paymentAmounts);
  297. $currencyCode = $this->getTableFilterState('currency_code')['value'];
  298. return CurrencyConverter::formatCentsToMoney($total, $currencyCode, true);
  299. }
  300. public function getSelectedBankAccount(): BankAccount
  301. {
  302. $bankAccountId = $this->data['bank_account_id'];
  303. $bankAccount = BankAccount::find($bankAccountId);
  304. return $bankAccount ?: BankAccount::where('enabled', true)->first();
  305. }
  306. protected function handleTableFilterUpdates(): void
  307. {
  308. parent::handleTableFilterUpdates();
  309. $visibleBillIds = $this->getTableRecords()->pluck('id')->toArray();
  310. $visibleBillKeys = array_flip($visibleBillIds);
  311. $this->paymentAmounts = array_intersect_key($this->paymentAmounts, $visibleBillKeys);
  312. }
  313. }