Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

PayBills.php 15KB

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