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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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->amount_due;
  75. $amount = CurrencyConverter::convertToCents($state, 'USD');
  76. if ($amount <= 0) {
  77. return 'Please enter a valid positive amount';
  78. }
  79. $currentPaymentAmount = $record?->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 (): Closure => static function (string $attribute, $value, Closure $fail) {
  89. if (! CurrencyConverter::isValidAmount($value, 'USD')) {
  90. $fail('Please enter a valid amount');
  91. }
  92. },
  93. ]),
  94. ])->columns(2),
  95. Forms\Components\Placeholder::make('currency_conversion')
  96. ->label('Currency Conversion')
  97. ->content(function (Forms\Get $get, RelationManager $livewire) {
  98. $amount = $get('amount');
  99. $bankAccountId = $get('bank_account_id');
  100. /** @var Bill $bill */
  101. $bill = $livewire->getOwnerRecord();
  102. $billCurrency = $bill->currency_code;
  103. if (empty($amount) || empty($bankAccountId) || ! CurrencyConverter::isValidAmount($amount, 'USD')) {
  104. return null;
  105. }
  106. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  107. if (! $bankAccount) {
  108. return null;
  109. }
  110. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  111. // If currencies are the same, no conversion needed
  112. if ($billCurrency === $bankCurrency) {
  113. return null;
  114. }
  115. // Convert amount from bill currency to bank currency
  116. $amountInBillCurrencyCents = CurrencyConverter::convertToCents($amount, 'USD');
  117. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  118. $amountInBillCurrencyCents,
  119. $billCurrency,
  120. $bankCurrency
  121. );
  122. $formattedBankAmount = CurrencyConverter::formatCentsToMoney($amountInBankCurrencyCents, $bankCurrency);
  123. return "Payment will be recorded as {$formattedBankAmount} in the bank account's currency ({$bankCurrency}).";
  124. })
  125. ->hidden(function (Forms\Get $get, RelationManager $livewire) {
  126. $bankAccountId = $get('bank_account_id');
  127. if (empty($bankAccountId)) {
  128. return true;
  129. }
  130. /** @var Bill $bill */
  131. $bill = $livewire->getOwnerRecord();
  132. $billCurrency = $bill->currency_code;
  133. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  134. if (! $bankAccount) {
  135. return true;
  136. }
  137. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  138. // Hide if currencies are the same
  139. return $billCurrency === $bankCurrency;
  140. }),
  141. Forms\Components\Select::make('payment_method')
  142. ->label('Payment method')
  143. ->required()
  144. ->options(PaymentMethod::class),
  145. Forms\Components\Textarea::make('notes')
  146. ->label('Notes'),
  147. ]);
  148. }
  149. public function table(Table $table): Table
  150. {
  151. return $table
  152. ->recordTitleAttribute('description')
  153. ->columns([
  154. Tables\Columns\TextColumn::make('posted_at')
  155. ->label('Date')
  156. ->sortable()
  157. ->defaultDateFormat(),
  158. Tables\Columns\TextColumn::make('type')
  159. ->label('Type')
  160. ->sortable()
  161. ->toggleable(isToggledHiddenByDefault: true),
  162. Tables\Columns\TextColumn::make('description')
  163. ->label('Description')
  164. ->limit(30)
  165. ->toggleable(),
  166. Tables\Columns\TextColumn::make('bankAccount.account.name')
  167. ->label('Account')
  168. ->toggleable(),
  169. Tables\Columns\TextColumn::make('amount')
  170. ->label('Amount')
  171. ->weight(static fn (Transaction $transaction) => $transaction->reviewed ? null : FontWeight::SemiBold)
  172. ->color(
  173. static fn (Transaction $transaction) => match ($transaction->type) {
  174. TransactionType::Deposit => Color::rgb('rgb(' . Color::Green[700] . ')'),
  175. TransactionType::Journal => 'primary',
  176. default => null,
  177. }
  178. )
  179. ->sortable()
  180. ->currency(static fn (Transaction $transaction) => $transaction->bankAccount?->account->currency_code ?? CurrencyAccessor::getDefaultCurrency()),
  181. ])
  182. ->filters([
  183. //
  184. ])
  185. ->headerActions([
  186. Tables\Actions\CreateAction::make()
  187. ->label('Record payment')
  188. ->modalHeading(fn (Tables\Actions\CreateAction $action) => $action->getLabel())
  189. ->modalWidth(MaxWidth::TwoExtraLarge)
  190. ->visible(function () {
  191. return $this->getOwnerRecord()->canRecordPayment();
  192. })
  193. ->mountUsing(function (Form $form) {
  194. $record = $this->getOwnerRecord();
  195. $form->fill([
  196. 'posted_at' => now(),
  197. 'amount' => $record->amount_due,
  198. ]);
  199. })
  200. ->databaseTransaction()
  201. ->successNotificationTitle('Payment recorded')
  202. ->action(function (Tables\Actions\CreateAction $action, array $data) {
  203. /** @var Bill $record */
  204. $record = $this->getOwnerRecord();
  205. $record->recordPayment($data);
  206. $action->success();
  207. $this->dispatch('refresh');
  208. }),
  209. ])
  210. ->actions([
  211. Tables\Actions\DeleteAction::make()
  212. ->after(fn () => $this->dispatch('refresh')),
  213. ])
  214. ->bulkActions([
  215. Tables\Actions\BulkActionGroup::make([
  216. Tables\Actions\DeleteBulkAction::make(),
  217. ]),
  218. ]);
  219. }
  220. }