You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InvoiceResource.php 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Enums\Accounting\AdjustmentCategory;
  4. use App\Enums\Accounting\AdjustmentStatus;
  5. use App\Enums\Accounting\AdjustmentType;
  6. use App\Enums\Accounting\DocumentDiscountMethod;
  7. use App\Enums\Accounting\DocumentType;
  8. use App\Enums\Accounting\InvoiceStatus;
  9. use App\Enums\Accounting\PaymentMethod;
  10. use App\Enums\Setting\PaymentTerms;
  11. use App\Filament\Company\Resources\Sales\ClientResource\RelationManagers\InvoicesRelationManager;
  12. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  13. use App\Filament\Company\Resources\Sales\InvoiceResource\Widgets;
  14. use App\Filament\Forms\Components\CreateAdjustmentSelect;
  15. use App\Filament\Forms\Components\CreateClientSelect;
  16. use App\Filament\Forms\Components\CreateCurrencySelect;
  17. use App\Filament\Forms\Components\CreateOfferingSelect;
  18. use App\Filament\Forms\Components\CustomTableRepeater;
  19. use App\Filament\Forms\Components\DocumentFooterSection;
  20. use App\Filament\Forms\Components\DocumentHeaderSection;
  21. use App\Filament\Forms\Components\DocumentTotals;
  22. use App\Filament\Tables\Actions\ReplicateBulkAction;
  23. use App\Filament\Tables\Columns;
  24. use App\Filament\Tables\Filters\DateRangeFilter;
  25. use App\Models\Accounting\Adjustment;
  26. use App\Models\Accounting\DocumentLineItem;
  27. use App\Models\Accounting\Invoice;
  28. use App\Models\Banking\BankAccount;
  29. use App\Models\Common\Client;
  30. use App\Models\Common\Offering;
  31. use App\Utilities\Currency\CurrencyAccessor;
  32. use App\Utilities\Currency\CurrencyConverter;
  33. use App\Utilities\RateCalculator;
  34. use Awcodes\TableRepeater\Header;
  35. use Closure;
  36. use Filament\Forms;
  37. use Filament\Forms\Form;
  38. use Filament\Notifications\Notification;
  39. use Filament\Resources\Resource;
  40. use Filament\Support\Enums\MaxWidth;
  41. use Filament\Tables;
  42. use Filament\Tables\Table;
  43. use Guava\FilamentClusters\Forms\Cluster;
  44. use Illuminate\Database\Eloquent\Builder;
  45. use Illuminate\Database\Eloquent\Collection;
  46. use Illuminate\Support\Carbon;
  47. use Illuminate\Support\Facades\Auth;
  48. class InvoiceResource extends Resource
  49. {
  50. protected static ?string $model = Invoice::class;
  51. public static function form(Form $form): Form
  52. {
  53. $company = Auth::user()->currentCompany;
  54. $settings = $company->defaultInvoice;
  55. return $form
  56. ->schema([
  57. DocumentHeaderSection::make('Invoice Header')
  58. ->defaultHeader($settings->header)
  59. ->defaultSubheader($settings->subheader),
  60. Forms\Components\Section::make('Invoice Details')
  61. ->schema([
  62. Forms\Components\Split::make([
  63. Forms\Components\Group::make([
  64. CreateClientSelect::make('client_id')
  65. ->label('Client')
  66. ->required()
  67. ->live()
  68. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  69. if (! $state) {
  70. return;
  71. }
  72. $currencyCode = Client::find($state)?->currency_code;
  73. if ($currencyCode) {
  74. $set('currency_code', $currencyCode);
  75. }
  76. }),
  77. CreateCurrencySelect::make('currency_code')
  78. ->disabled(function (?Invoice $record) {
  79. return $record?->hasPayments();
  80. }),
  81. ]),
  82. Forms\Components\Group::make([
  83. Forms\Components\TextInput::make('invoice_number')
  84. ->label('Invoice number')
  85. ->default(static fn () => Invoice::getNextDocumentNumber()),
  86. Forms\Components\TextInput::make('order_number')
  87. ->label('P.O/S.O Number'),
  88. Cluster::make([
  89. Forms\Components\DatePicker::make('date')
  90. ->label('Invoice date')
  91. ->live()
  92. ->default(now())
  93. ->disabled(function (?Invoice $record) {
  94. return $record?->hasPayments();
  95. })
  96. ->columnSpan(2)
  97. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  98. $date = $state;
  99. $dueDate = $get('due_date');
  100. if ($date && $dueDate && $date > $dueDate) {
  101. $set('due_date', $date);
  102. }
  103. // Update due date based on payment terms if selected
  104. $paymentTerms = $get('payment_terms');
  105. if ($date && $paymentTerms && $paymentTerms !== 'custom') {
  106. $terms = PaymentTerms::parse($paymentTerms);
  107. $set('due_date', Carbon::parse($date)->addDays($terms->getDays())->toDateString());
  108. }
  109. }),
  110. Forms\Components\Select::make('payment_terms')
  111. ->label('Payment terms')
  112. ->options(function () {
  113. return collect(PaymentTerms::cases())
  114. ->mapWithKeys(function (PaymentTerms $paymentTerm) {
  115. return [$paymentTerm->value => $paymentTerm->getLabel()];
  116. })
  117. ->put('custom', 'Custom')
  118. ->toArray();
  119. })
  120. ->selectablePlaceholder(false)
  121. ->default($settings->payment_terms->value)
  122. ->live()
  123. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  124. if (! $state || $state === 'custom') {
  125. return;
  126. }
  127. $date = $get('date');
  128. if ($date) {
  129. $terms = PaymentTerms::parse($state);
  130. $set('due_date', Carbon::parse($date)->addDays($terms->getDays())->toDateString());
  131. }
  132. }),
  133. ])
  134. ->label('Invoice date')
  135. ->columns(3),
  136. Forms\Components\DatePicker::make('due_date')
  137. ->label('Payment due')
  138. ->default(function () use ($settings) {
  139. return now()->addDays($settings->payment_terms->getDays());
  140. })
  141. ->minDate(static function (Forms\Get $get) {
  142. return $get('date') ?? now();
  143. })
  144. ->live()
  145. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  146. if (! $state) {
  147. return;
  148. }
  149. $invoiceDate = $get('date');
  150. $paymentTerms = $get('payment_terms');
  151. if (! $invoiceDate || $paymentTerms === 'custom' || ! $paymentTerms) {
  152. return;
  153. }
  154. $term = PaymentTerms::parse($paymentTerms);
  155. $expectedDueDate = Carbon::parse($invoiceDate)->addDays($term->getDays());
  156. if (! Carbon::parse($state)->isSameDay($expectedDueDate)) {
  157. $set('payment_terms', 'custom');
  158. }
  159. }),
  160. Forms\Components\Select::make('discount_method')
  161. ->label('Discount method')
  162. ->options(DocumentDiscountMethod::class)
  163. ->softRequired()
  164. ->default($settings->discount_method)
  165. ->afterStateUpdated(function ($state, Forms\Set $set) {
  166. $discountMethod = DocumentDiscountMethod::parse($state);
  167. if ($discountMethod->isPerDocument()) {
  168. $set('lineItems.*.salesDiscounts', []);
  169. }
  170. })
  171. ->live(),
  172. ])->grow(true),
  173. ])->from('md'),
  174. CustomTableRepeater::make('lineItems')
  175. ->hiddenLabel()
  176. ->relationship()
  177. ->saveRelationshipsUsing(null)
  178. ->dehydrated(true)
  179. ->reorderable()
  180. ->orderColumn('line_number')
  181. ->reorderAtStart()
  182. ->cloneable()
  183. ->addActionLabel('Add an item')
  184. ->headers(function (Forms\Get $get) use ($settings) {
  185. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  186. $headers = [
  187. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  188. ->width('30%'),
  189. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  190. ->width('10%'),
  191. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  192. ->width('10%'),
  193. ];
  194. if ($hasDiscounts) {
  195. $headers[] = Header::make('Adjustments')->width('30%');
  196. } else {
  197. $headers[] = Header::make('Taxes')->width('30%');
  198. }
  199. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  200. ->width('10%')
  201. ->align('right');
  202. return $headers;
  203. })
  204. ->schema([
  205. Forms\Components\Group::make([
  206. CreateOfferingSelect::make('offering_id')
  207. ->label('Item')
  208. ->hiddenLabel()
  209. ->placeholder('Select item')
  210. ->required()
  211. ->live()
  212. ->inlineSuffix()
  213. ->sellable()
  214. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state, ?DocumentLineItem $record) {
  215. $offeringId = $state;
  216. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  217. $isPerLineItem = $discountMethod->isPerLineItem();
  218. $existingTaxIds = [];
  219. $existingDiscountIds = [];
  220. if ($record) {
  221. $existingTaxIds = $record->salesTaxes()->pluck('adjustments.id')->toArray();
  222. if ($isPerLineItem) {
  223. $existingDiscountIds = $record->salesDiscounts()->pluck('adjustments.id')->toArray();
  224. }
  225. }
  226. $with = [
  227. 'salesTaxes' => static function ($query) use ($existingTaxIds) {
  228. $query->where(static function ($query) use ($existingTaxIds) {
  229. $query->where('status', AdjustmentStatus::Active)
  230. ->orWhereIn('adjustments.id', $existingTaxIds);
  231. });
  232. },
  233. ];
  234. if ($isPerLineItem) {
  235. $with['salesDiscounts'] = static function ($query) use ($existingDiscountIds) {
  236. $query->where(static function ($query) use ($existingDiscountIds) {
  237. $query->where('status', AdjustmentStatus::Active)
  238. ->orWhereIn('adjustments.id', $existingDiscountIds);
  239. });
  240. };
  241. }
  242. $offeringRecord = Offering::with($with)->find($offeringId);
  243. if (! $offeringRecord) {
  244. return;
  245. }
  246. $unitPrice = CurrencyConverter::convertCentsToFormatSimple($offeringRecord->price, 'USD');
  247. $set('description', $offeringRecord->description);
  248. $set('unit_price', $unitPrice);
  249. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  250. if ($isPerLineItem) {
  251. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  252. }
  253. }),
  254. Forms\Components\TextInput::make('description')
  255. ->placeholder('Enter item description')
  256. ->hiddenLabel(),
  257. ])->columnSpan(1),
  258. Forms\Components\TextInput::make('quantity')
  259. ->required()
  260. ->numeric()
  261. ->live()
  262. ->maxValue(9999999999.99)
  263. ->default(1),
  264. Forms\Components\TextInput::make('unit_price')
  265. ->hiddenLabel()
  266. ->money(useAffix: false)
  267. ->live()
  268. ->default(0),
  269. Forms\Components\Group::make([
  270. CreateAdjustmentSelect::make('salesTaxes')
  271. ->label('Taxes')
  272. ->hiddenLabel()
  273. ->placeholder('Select taxes')
  274. ->category(AdjustmentCategory::Tax)
  275. ->type(AdjustmentType::Sales)
  276. ->adjustmentsRelationship('salesTaxes')
  277. ->saveRelationshipsUsing(null)
  278. ->dehydrated(true)
  279. ->inlineSuffix()
  280. ->preload()
  281. ->multiple()
  282. ->live()
  283. ->searchable(),
  284. CreateAdjustmentSelect::make('salesDiscounts')
  285. ->label('Discounts')
  286. ->hiddenLabel()
  287. ->placeholder('Select discounts')
  288. ->category(AdjustmentCategory::Discount)
  289. ->type(AdjustmentType::Sales)
  290. ->adjustmentsRelationship('salesDiscounts')
  291. ->saveRelationshipsUsing(null)
  292. ->dehydrated(true)
  293. ->inlineSuffix()
  294. ->multiple()
  295. ->live()
  296. ->hidden(function (Forms\Get $get) {
  297. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  298. return $discountMethod->isPerDocument();
  299. })
  300. ->searchable(),
  301. ])->columnSpan(1),
  302. Forms\Components\Placeholder::make('total')
  303. ->hiddenLabel()
  304. ->extraAttributes(['class' => 'text-left sm:text-right'])
  305. ->content(function (Forms\Get $get) {
  306. $quantity = max((float) ($get('quantity') ?? 0), 0);
  307. $unitPrice = CurrencyConverter::isValidAmount($get('unit_price'), 'USD')
  308. ? CurrencyConverter::convertToFloat($get('unit_price'), 'USD')
  309. : 0;
  310. $salesTaxes = $get('salesTaxes') ?? [];
  311. $salesDiscounts = $get('salesDiscounts') ?? [];
  312. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  313. $subtotal = $quantity * $unitPrice;
  314. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  315. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  316. ->get()
  317. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  318. if ($adjustment->computation->isPercentage()) {
  319. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  320. } else {
  321. return $adjustment->getRawOriginal('rate');
  322. }
  323. });
  324. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  325. ->get()
  326. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  327. if ($adjustment->computation->isPercentage()) {
  328. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  329. } else {
  330. return $adjustment->getRawOriginal('rate');
  331. }
  332. });
  333. // Final total
  334. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  335. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  336. }),
  337. ]),
  338. DocumentTotals::make()
  339. ->type(DocumentType::Invoice),
  340. Forms\Components\Textarea::make('terms')
  341. ->default($settings->terms)
  342. ->columnSpanFull(),
  343. ]),
  344. DocumentFooterSection::make('Invoice Footer')
  345. ->defaultFooter($settings->footer),
  346. ]);
  347. }
  348. public static function table(Table $table): Table
  349. {
  350. return $table
  351. ->defaultSort('due_date')
  352. ->modifyQueryUsing(function (Builder $query, Tables\Contracts\HasTable $livewire) {
  353. if (property_exists($livewire, 'recurringInvoice')) {
  354. $recurringInvoiceId = $livewire->recurringInvoice;
  355. if (! empty($recurringInvoiceId)) {
  356. $query->where('recurring_invoice_id', $recurringInvoiceId);
  357. }
  358. }
  359. return $query;
  360. })
  361. ->columns([
  362. Columns::id(),
  363. Tables\Columns\TextColumn::make('status')
  364. ->badge()
  365. ->searchable(),
  366. Tables\Columns\TextColumn::make('due_date')
  367. ->label('Due')
  368. ->asRelativeDay()
  369. ->sortable()
  370. ->hideOnTabs(['draft']),
  371. Tables\Columns\TextColumn::make('date')
  372. ->date()
  373. ->sortable(),
  374. Tables\Columns\TextColumn::make('invoice_number')
  375. ->label('Number')
  376. ->searchable()
  377. ->description(function (Invoice $record) {
  378. return $record->source_type?->getLabel();
  379. })
  380. ->sortable(),
  381. Tables\Columns\TextColumn::make('client.name')
  382. ->sortable()
  383. ->searchable()
  384. ->hiddenOn(InvoicesRelationManager::class),
  385. Tables\Columns\TextColumn::make('total')
  386. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  387. ->sortable()
  388. ->toggleable()
  389. ->alignEnd(),
  390. Tables\Columns\TextColumn::make('amount_paid')
  391. ->label('Amount paid')
  392. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  393. ->sortable()
  394. ->alignEnd()
  395. ->showOnTabs(['unpaid']),
  396. Tables\Columns\TextColumn::make('amount_due')
  397. ->label('Amount due')
  398. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  399. ->sortable()
  400. ->alignEnd()
  401. ->hideOnTabs(['draft']),
  402. ])
  403. ->filters([
  404. Tables\Filters\SelectFilter::make('client')
  405. ->relationship('client', 'name')
  406. ->searchable()
  407. ->preload()
  408. ->hiddenOn(InvoicesRelationManager::class),
  409. Tables\Filters\SelectFilter::make('status')
  410. ->options(InvoiceStatus::class)
  411. ->multiple(),
  412. Tables\Filters\TernaryFilter::make('has_payments')
  413. ->label('Has payments')
  414. ->queries(
  415. true: fn (Builder $query) => $query->whereHas('payments'),
  416. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  417. ),
  418. Tables\Filters\SelectFilter::make('source_type')
  419. ->label('Source type')
  420. ->options([
  421. DocumentType::Estimate->value => DocumentType::Estimate->getLabel(),
  422. DocumentType::RecurringInvoice->value => DocumentType::RecurringInvoice->getLabel(),
  423. ])
  424. ->native(false)
  425. ->query(function (Builder $query, array $data) {
  426. $sourceType = $data['value'] ?? null;
  427. return match ($sourceType) {
  428. DocumentType::Estimate->value => $query->whereNotNull('estimate_id'),
  429. DocumentType::RecurringInvoice->value => $query->whereNotNull('recurring_invoice_id'),
  430. default => $query,
  431. };
  432. }),
  433. DateRangeFilter::make('date')
  434. ->fromLabel('From date')
  435. ->untilLabel('To date')
  436. ->indicatorLabel('Date'),
  437. DateRangeFilter::make('due_date')
  438. ->fromLabel('From due date')
  439. ->untilLabel('To due date')
  440. ->indicatorLabel('Due'),
  441. ])
  442. ->actions([
  443. Tables\Actions\ActionGroup::make([
  444. Tables\Actions\ActionGroup::make([
  445. Tables\Actions\EditAction::make()
  446. ->url(static fn (Invoice $record) => Pages\EditInvoice::getUrl(['record' => $record])),
  447. Tables\Actions\ViewAction::make()
  448. ->url(static fn (Invoice $record) => Pages\ViewInvoice::getUrl(['record' => $record])),
  449. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  450. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  451. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  452. Tables\Actions\Action::make('recordPayment')
  453. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  454. ->slideOver()
  455. ->modalWidth(MaxWidth::TwoExtraLarge)
  456. ->icon('heroicon-m-credit-card')
  457. ->visible(function (Invoice $record) {
  458. return $record->canRecordPayment();
  459. })
  460. ->mountUsing(function (Invoice $record, Form $form) {
  461. $form->fill([
  462. 'posted_at' => now(),
  463. 'amount' => abs($record->amount_due),
  464. ]);
  465. })
  466. ->databaseTransaction()
  467. ->successNotificationTitle('Payment recorded')
  468. ->form([
  469. Forms\Components\DatePicker::make('posted_at')
  470. ->label('Date'),
  471. Forms\Components\Grid::make()
  472. ->schema([
  473. Forms\Components\Select::make('bank_account_id')
  474. ->label('Account')
  475. ->required()
  476. ->live()
  477. ->options(function () {
  478. return BankAccount::query()
  479. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  480. ->select(['bank_accounts.id', 'accounts.name', 'accounts.currency_code'])
  481. ->get()
  482. ->mapWithKeys(function ($account) {
  483. $label = $account->name;
  484. if ($account->currency_code) {
  485. $label .= " ({$account->currency_code})";
  486. }
  487. return [$account->id => $label];
  488. })
  489. ->toArray();
  490. })
  491. ->searchable(),
  492. Forms\Components\TextInput::make('amount')
  493. ->label('Amount')
  494. ->required()
  495. ->money(fn (Invoice $record) => $record->currency_code)
  496. ->live(onBlur: true)
  497. ->helperText(function (Invoice $record, $state) {
  498. $invoiceCurrency = $record->currency_code;
  499. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  500. return null;
  501. }
  502. $amountDue = $record->amount_due;
  503. $amount = CurrencyConverter::convertToCents($state, 'USD');
  504. if ($amount <= 0) {
  505. return 'Please enter a valid positive amount';
  506. }
  507. if ($record->status === InvoiceStatus::Overpaid) {
  508. $newAmountDue = $amountDue + $amount;
  509. } else {
  510. $newAmountDue = $amountDue - $amount;
  511. }
  512. return match (true) {
  513. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  514. $newAmountDue === 0 => 'Invoice will be fully paid',
  515. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  516. };
  517. })
  518. ->rules([
  519. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  520. if (! CurrencyConverter::isValidAmount($value, 'USD')) {
  521. $fail('Please enter a valid amount');
  522. }
  523. },
  524. ]),
  525. ])->columns(2),
  526. Forms\Components\Placeholder::make('currency_conversion')
  527. ->label('Currency Conversion')
  528. ->content(function (Forms\Get $get, Invoice $record) {
  529. $amount = $get('amount');
  530. $bankAccountId = $get('bank_account_id');
  531. $invoiceCurrency = $record->currency_code;
  532. if (empty($amount) || empty($bankAccountId) || ! CurrencyConverter::isValidAmount($amount, 'USD')) {
  533. return null;
  534. }
  535. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  536. if (! $bankAccount) {
  537. return null;
  538. }
  539. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  540. // If currencies are the same, no conversion needed
  541. if ($invoiceCurrency === $bankCurrency) {
  542. return null;
  543. }
  544. // Convert amount from invoice currency to bank currency
  545. $amountInInvoiceCurrencyCents = CurrencyConverter::convertToCents($amount, 'USD');
  546. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  547. $amountInInvoiceCurrencyCents,
  548. $invoiceCurrency,
  549. $bankCurrency
  550. );
  551. $formattedBankAmount = CurrencyConverter::formatCentsToMoney($amountInBankCurrencyCents, $bankCurrency);
  552. return "Payment will be recorded as {$formattedBankAmount} in the bank account's currency ({$bankCurrency}).";
  553. })
  554. ->hidden(function (Forms\Get $get, Invoice $record) {
  555. $bankAccountId = $get('bank_account_id');
  556. if (empty($bankAccountId)) {
  557. return true;
  558. }
  559. $invoiceCurrency = $record->currency_code;
  560. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  561. if (! $bankAccount) {
  562. return true;
  563. }
  564. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  565. // Hide if currencies are the same
  566. return $invoiceCurrency === $bankCurrency;
  567. }),
  568. Forms\Components\Select::make('payment_method')
  569. ->label('Payment method')
  570. ->required()
  571. ->options(PaymentMethod::class),
  572. Forms\Components\Textarea::make('notes')
  573. ->label('Notes'),
  574. ])
  575. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  576. $record->recordPayment($data);
  577. $action->success();
  578. }),
  579. ])->dropdown(false),
  580. Tables\Actions\DeleteAction::make(),
  581. ]),
  582. ])
  583. ->bulkActions([
  584. Tables\Actions\BulkActionGroup::make([
  585. Tables\Actions\DeleteBulkAction::make(),
  586. ReplicateBulkAction::make()
  587. ->label('Replicate')
  588. ->modalWidth(MaxWidth::Large)
  589. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  590. ->successNotificationTitle('Invoices replicated successfully')
  591. ->failureNotificationTitle('Failed to replicate invoices')
  592. ->databaseTransaction()
  593. ->excludeAttributes([
  594. 'status',
  595. 'amount_paid',
  596. 'amount_due',
  597. 'created_by',
  598. 'updated_by',
  599. 'created_at',
  600. 'updated_at',
  601. 'invoice_number',
  602. 'date',
  603. 'due_date',
  604. 'approved_at',
  605. 'paid_at',
  606. 'last_sent_at',
  607. 'last_viewed_at',
  608. ])
  609. ->beforeReplicaSaved(function (Invoice $replica) {
  610. $replica->status = InvoiceStatus::Draft;
  611. $replica->invoice_number = Invoice::getNextDocumentNumber();
  612. $replica->date = now();
  613. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  614. })
  615. ->withReplicatedRelationships(['lineItems'])
  616. ->withExcludedRelationshipAttributes('lineItems', [
  617. 'subtotal',
  618. 'total',
  619. 'created_by',
  620. 'updated_by',
  621. 'created_at',
  622. 'updated_at',
  623. ]),
  624. Tables\Actions\BulkAction::make('approveDrafts')
  625. ->label('Approve')
  626. ->icon('heroicon-o-check-circle')
  627. ->databaseTransaction()
  628. ->successNotificationTitle('Invoices approved')
  629. ->failureNotificationTitle('Failed to Approve Invoices')
  630. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  631. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeApproved());
  632. if ($isInvalid) {
  633. Notification::make()
  634. ->title('Approval failed')
  635. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  636. ->persistent()
  637. ->danger()
  638. ->send();
  639. $action->cancel(true);
  640. }
  641. })
  642. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  643. $records->each(function (Invoice $record) {
  644. $record->approveDraft();
  645. });
  646. $action->success();
  647. }),
  648. Tables\Actions\BulkAction::make('markAsSent')
  649. ->label('Mark as sent')
  650. ->icon('heroicon-o-paper-airplane')
  651. ->databaseTransaction()
  652. ->successNotificationTitle('Invoices sent')
  653. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  654. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  655. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeMarkedAsSent());
  656. if ($isInvalid) {
  657. Notification::make()
  658. ->title('Sending failed')
  659. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  660. ->persistent()
  661. ->danger()
  662. ->send();
  663. $action->cancel(true);
  664. }
  665. })
  666. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  667. $records->each(function (Invoice $record) {
  668. $record->markAsSent();
  669. });
  670. $action->success();
  671. }),
  672. ]),
  673. ]);
  674. }
  675. public static function getPages(): array
  676. {
  677. return [
  678. 'index' => Pages\ListInvoices::route('/'),
  679. 'create' => Pages\CreateInvoice::route('/create'),
  680. 'view' => Pages\ViewInvoice::route('/{record}'),
  681. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  682. ];
  683. }
  684. public static function getWidgets(): array
  685. {
  686. return [
  687. Widgets\InvoiceOverview::class,
  688. ];
  689. }
  690. }