Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

PaymentsRelationManager.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <?php
  2. namespace App\Filament\Company\Resources\Purchases\BillResource\RelationManagers;
  3. use App\Enums\Accounting\PaymentMethod;
  4. use App\Enums\Accounting\TransactionType;
  5. use App\Models\Accounting\Bill;
  6. use App\Models\Accounting\Transaction;
  7. use App\Models\Banking\BankAccount;
  8. use App\Utilities\Currency\CurrencyAccessor;
  9. use App\Utilities\Currency\CurrencyConverter;
  10. use Closure;
  11. use Filament\Forms;
  12. use Filament\Forms\Form;
  13. use Filament\Resources\RelationManagers\RelationManager;
  14. use Filament\Support\Colors\Color;
  15. use Filament\Support\Enums\FontWeight;
  16. use Filament\Support\Enums\MaxWidth;
  17. use Filament\Tables;
  18. use Filament\Tables\Table;
  19. class PaymentsRelationManager extends RelationManager
  20. {
  21. protected static string $relationship = 'payments';
  22. protected static ?string $modelLabel = 'Payment';
  23. protected $listeners = [
  24. 'refresh' => '$refresh',
  25. ];
  26. public function isReadOnly(): bool
  27. {
  28. return false;
  29. }
  30. public function form(Form $form): Form
  31. {
  32. return $form
  33. ->columns(1)
  34. ->schema([
  35. Forms\Components\DatePicker::make('posted_at')
  36. ->label('Date'),
  37. Forms\Components\Grid::make()
  38. ->schema([
  39. Forms\Components\Select::make('bank_account_id')
  40. ->label('Account')
  41. ->required()
  42. ->live()
  43. ->options(function () {
  44. return BankAccount::query()
  45. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  46. ->select(['bank_accounts.id', 'accounts.name', 'accounts.currency_code'])
  47. ->get()
  48. ->mapWithKeys(function ($account) {
  49. $label = $account->name;
  50. if ($account->currency_code) {
  51. $label .= " ({$account->currency_code})";
  52. }
  53. return [$account->id => $label];
  54. })
  55. ->toArray();
  56. })
  57. ->searchable(),
  58. Forms\Components\TextInput::make('amount')
  59. ->label('Amount')
  60. ->required()
  61. ->money(function (RelationManager $livewire) {
  62. /** @var Bill $bill */
  63. $bill = $livewire->getOwnerRecord();
  64. return $bill->currency_code;
  65. })
  66. ->live(onBlur: true)
  67. ->helperText(function (RelationManager $livewire, $state, ?Transaction $record) {
  68. /** @var Bill $ownerRecord */
  69. $ownerRecord = $livewire->getOwnerRecord();
  70. $billCurrency = $ownerRecord->currency_code;
  71. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  72. return null;
  73. }
  74. $amountDue = $ownerRecord->getRawOriginal('amount_due');
  75. $amount = CurrencyConverter::convertToCents($state, 'USD');
  76. if ($amount <= 0) {
  77. return 'Please enter a valid positive amount';
  78. }
  79. $currentPaymentAmount = $record?->getRawOriginal('amount') ?? 0;
  80. $newAmountDue = $amountDue - $amount + $currentPaymentAmount;
  81. return match (true) {
  82. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $billCurrency),
  83. $newAmountDue === 0 => 'Bill will be fully paid',
  84. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $billCurrency),
  85. };
  86. })
  87. ->rules([
  88. static fn (RelationManager $livewire): Closure => static function (string $attribute, $value, Closure $fail) use ($livewire) {
  89. /** @var Bill $bill */
  90. $bill = $livewire->getOwnerRecord();
  91. if (! CurrencyConverter::isValidAmount($value, $bill->currency_code)) {
  92. $fail('Please enter a valid amount');
  93. }
  94. },
  95. ]),
  96. ])->columns(2),
  97. Forms\Components\Placeholder::make('currency_conversion')
  98. ->label('Currency Conversion')
  99. ->content(function (Forms\Get $get, RelationManager $livewire) {
  100. $amount = $get('amount');
  101. $bankAccountId = $get('bank_account_id');
  102. /** @var Bill $bill */
  103. $bill = $livewire->getOwnerRecord();
  104. $billCurrency = $bill->currency_code;
  105. if (empty($amount) || empty($bankAccountId) || ! CurrencyConverter::isValidAmount($amount, 'USD')) {
  106. return null;
  107. }
  108. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  109. if (! $bankAccount) {
  110. return null;
  111. }
  112. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  113. // If currencies are the same, no conversion needed
  114. if ($billCurrency === $bankCurrency) {
  115. return null;
  116. }
  117. // Convert amount from bill currency to bank currency
  118. $amountInBillCurrencyCents = CurrencyConverter::convertToCents($amount, 'USD');
  119. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  120. $amountInBillCurrencyCents,
  121. $billCurrency,
  122. $bankCurrency
  123. );
  124. $formattedBankAmount = CurrencyConverter::formatCentsToMoney($amountInBankCurrencyCents, $bankCurrency);
  125. return "Payment will be recorded as {$formattedBankAmount} in the bank account's currency ({$bankCurrency}).";
  126. })
  127. ->hidden(function (Forms\Get $get, RelationManager $livewire) {
  128. $bankAccountId = $get('bank_account_id');
  129. if (empty($bankAccountId)) {
  130. return true;
  131. }
  132. /** @var Bill $bill */
  133. $bill = $livewire->getOwnerRecord();
  134. $billCurrency = $bill->currency_code;
  135. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  136. if (! $bankAccount) {
  137. return true;
  138. }
  139. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  140. // Hide if currencies are the same
  141. return $billCurrency === $bankCurrency;
  142. }),
  143. Forms\Components\Select::make('payment_method')
  144. ->label('Payment method')
  145. ->required()
  146. ->options(PaymentMethod::class),
  147. Forms\Components\Textarea::make('notes')
  148. ->label('Notes'),
  149. ]);
  150. }
  151. public function table(Table $table): Table
  152. {
  153. return $table
  154. ->recordTitleAttribute('description')
  155. ->columns([
  156. Tables\Columns\TextColumn::make('posted_at')
  157. ->label('Date')
  158. ->sortable()
  159. ->defaultDateFormat(),
  160. Tables\Columns\TextColumn::make('type')
  161. ->label('Type')
  162. ->sortable()
  163. ->toggleable(isToggledHiddenByDefault: true),
  164. Tables\Columns\TextColumn::make('description')
  165. ->label('Description')
  166. ->limit(30)
  167. ->toggleable(),
  168. Tables\Columns\TextColumn::make('bankAccount.account.name')
  169. ->label('Account')
  170. ->toggleable(),
  171. Tables\Columns\TextColumn::make('amount')
  172. ->label('Amount')
  173. ->weight(static fn (Transaction $transaction) => $transaction->reviewed ? null : FontWeight::SemiBold)
  174. ->color(
  175. static fn (Transaction $transaction) => match ($transaction->type) {
  176. TransactionType::Deposit => Color::rgb('rgb(' . Color::Green[700] . ')'),
  177. TransactionType::Journal => 'primary',
  178. default => null,
  179. }
  180. )
  181. ->sortable()
  182. ->currency(static fn (Transaction $transaction) => $transaction->bankAccount?->account->currency_code ?? CurrencyAccessor::getDefaultCurrency()),
  183. ])
  184. ->filters([
  185. //
  186. ])
  187. ->headerActions([
  188. Tables\Actions\CreateAction::make()
  189. ->label('Record payment')
  190. ->modalHeading(fn (Tables\Actions\CreateAction $action) => $action->getLabel())
  191. ->modalWidth(MaxWidth::TwoExtraLarge)
  192. ->visible(function () {
  193. return $this->getOwnerRecord()->canRecordPayment();
  194. })
  195. ->mountUsing(function (Form $form) {
  196. $record = $this->getOwnerRecord();
  197. $form->fill([
  198. 'posted_at' => now(),
  199. 'amount' => $record->amount_due,
  200. ]);
  201. })
  202. ->databaseTransaction()
  203. ->successNotificationTitle('Payment recorded')
  204. ->action(function (Tables\Actions\CreateAction $action, array $data) {
  205. /** @var Bill $record */
  206. $record = $this->getOwnerRecord();
  207. $record->recordPayment($data);
  208. $action->success();
  209. $this->dispatch('refresh');
  210. }),
  211. ])
  212. ->actions([
  213. Tables\Actions\DeleteAction::make()
  214. ->after(fn () => $this->dispatch('refresh')),
  215. ])
  216. ->bulkActions([
  217. Tables\Actions\BulkActionGroup::make([
  218. Tables\Actions\DeleteBulkAction::make(),
  219. ]),
  220. ]);
  221. }
  222. }