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.

RecurringInvoiceResource.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Enums\Accounting\DocumentDiscountMethod;
  4. use App\Enums\Accounting\DocumentType;
  5. use App\Enums\Setting\PaymentTerms;
  6. use App\Filament\Company\Resources\Sales\RecurringInvoiceResource\Pages;
  7. use App\Filament\Forms\Components\CreateCurrencySelect;
  8. use App\Filament\Forms\Components\DocumentTotals;
  9. use App\Models\Accounting\Adjustment;
  10. use App\Models\Accounting\RecurringInvoice;
  11. use App\Models\Common\Client;
  12. use App\Models\Common\Offering;
  13. use App\Utilities\Currency\CurrencyAccessor;
  14. use App\Utilities\Currency\CurrencyConverter;
  15. use App\Utilities\RateCalculator;
  16. use Awcodes\TableRepeater\Components\TableRepeater;
  17. use Awcodes\TableRepeater\Header;
  18. use Filament\Forms;
  19. use Filament\Forms\Components\FileUpload;
  20. use Filament\Forms\Form;
  21. use Filament\Resources\Resource;
  22. use Filament\Support\Enums\MaxWidth;
  23. use Filament\Tables;
  24. use Filament\Tables\Table;
  25. use Illuminate\Support\Facades\Auth;
  26. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  27. class RecurringInvoiceResource extends Resource
  28. {
  29. protected static ?string $model = RecurringInvoice::class;
  30. public static function form(Form $form): Form
  31. {
  32. $company = Auth::user()->currentCompany;
  33. return $form
  34. ->schema([
  35. Forms\Components\Section::make('Invoice Header')
  36. ->collapsible()
  37. ->collapsed()
  38. ->schema([
  39. Forms\Components\Split::make([
  40. Forms\Components\Group::make([
  41. FileUpload::make('logo')
  42. ->openable()
  43. ->maxSize(1024)
  44. ->localizeLabel()
  45. ->visibility('public')
  46. ->disk('public')
  47. ->directory('logos/document')
  48. ->imageResizeMode('contain')
  49. ->imageCropAspectRatio('3:2')
  50. ->panelAspectRatio('3:2')
  51. ->maxWidth(MaxWidth::ExtraSmall)
  52. ->panelLayout('integrated')
  53. ->removeUploadedFileButtonPosition('center bottom')
  54. ->uploadButtonPosition('center bottom')
  55. ->uploadProgressIndicatorPosition('center bottom')
  56. ->getUploadedFileNameForStorageUsing(
  57. static fn (TemporaryUploadedFile $file): string => (string) str($file->getClientOriginalName())
  58. ->prepend(Auth::user()->currentCompany->id . '_'),
  59. )
  60. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/gif']),
  61. ]),
  62. Forms\Components\Group::make([
  63. Forms\Components\TextInput::make('header')
  64. ->default(fn () => $company->defaultInvoice->header),
  65. Forms\Components\TextInput::make('subheader')
  66. ->default(fn () => $company->defaultInvoice->subheader),
  67. Forms\Components\View::make('filament.forms.components.company-info')
  68. ->viewData([
  69. 'company_name' => $company->name,
  70. 'company_address' => $company->profile->address,
  71. 'company_city' => $company->profile->city?->name,
  72. 'company_state' => $company->profile->state?->name,
  73. 'company_zip' => $company->profile->zip_code,
  74. 'company_country' => $company->profile->state?->country->name,
  75. ]),
  76. ])->grow(true),
  77. ])->from('md'),
  78. ]),
  79. Forms\Components\Section::make('Invoice Details')
  80. ->schema([
  81. Forms\Components\Split::make([
  82. Forms\Components\Group::make([
  83. Forms\Components\Select::make('client_id')
  84. ->relationship('client', 'name')
  85. ->preload()
  86. ->searchable()
  87. ->required()
  88. ->live()
  89. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  90. if (! $state) {
  91. return;
  92. }
  93. $currencyCode = Client::find($state)?->currency_code;
  94. if ($currencyCode) {
  95. $set('currency_code', $currencyCode);
  96. }
  97. }),
  98. CreateCurrencySelect::make('currency_code'),
  99. ]),
  100. Forms\Components\Group::make([
  101. Forms\Components\Placeholder::make('invoice_number')
  102. ->label('Invoice Number')
  103. ->content('Auto-generated'),
  104. Forms\Components\TextInput::make('order_number')
  105. ->label('P.O/S.O Number'),
  106. Forms\Components\Placeholder::make('date')
  107. ->label('Invoice Date')
  108. ->content('Auto-generated'),
  109. Forms\Components\Select::make('payment_terms')
  110. ->label('Payment Due')
  111. ->options(PaymentTerms::class)
  112. ->softRequired()
  113. ->default($company->defaultInvoice->payment_terms)
  114. ->live(),
  115. Forms\Components\Select::make('discount_method')
  116. ->label('Discount Method')
  117. ->options(DocumentDiscountMethod::class)
  118. ->selectablePlaceholder(false)
  119. ->default(DocumentDiscountMethod::PerLineItem)
  120. ->afterStateUpdated(function ($state, Forms\Set $set) {
  121. $discountMethod = DocumentDiscountMethod::parse($state);
  122. if ($discountMethod->isPerDocument()) {
  123. $set('lineItems.*.salesDiscounts', []);
  124. }
  125. })
  126. ->live(),
  127. ])->grow(true),
  128. ])->from('md'),
  129. TableRepeater::make('lineItems')
  130. ->relationship()
  131. ->saveRelationshipsUsing(null)
  132. ->dehydrated(true)
  133. ->headers(function (Forms\Get $get) {
  134. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  135. $headers = [
  136. Header::make('Items')->width($hasDiscounts ? '15%' : '20%'),
  137. Header::make('Description')->width($hasDiscounts ? '25%' : '30%'), // Increase when no discounts
  138. Header::make('Quantity')->width('10%'),
  139. Header::make('Price')->width('10%'),
  140. Header::make('Taxes')->width($hasDiscounts ? '15%' : '20%'), // Increase when no discounts
  141. ];
  142. if ($hasDiscounts) {
  143. $headers[] = Header::make('Discounts')->width('15%');
  144. }
  145. $headers[] = Header::make('Amount')->width('10%')->align('right');
  146. return $headers;
  147. })
  148. ->schema([
  149. Forms\Components\Select::make('offering_id')
  150. ->relationship('sellableOffering', 'name')
  151. ->preload()
  152. ->searchable()
  153. ->required()
  154. ->live()
  155. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  156. $offeringId = $state;
  157. $offeringRecord = Offering::with(['salesTaxes', 'salesDiscounts'])->find($offeringId);
  158. if ($offeringRecord) {
  159. $set('description', $offeringRecord->description);
  160. $set('unit_price', $offeringRecord->price);
  161. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  162. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  163. if ($discountMethod->isPerLineItem()) {
  164. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  165. }
  166. }
  167. }),
  168. Forms\Components\TextInput::make('description'),
  169. Forms\Components\TextInput::make('quantity')
  170. ->required()
  171. ->numeric()
  172. ->live()
  173. ->default(1),
  174. Forms\Components\TextInput::make('unit_price')
  175. ->hiddenLabel()
  176. ->numeric()
  177. ->live()
  178. ->default(0),
  179. Forms\Components\Select::make('salesTaxes')
  180. ->relationship('salesTaxes', 'name')
  181. ->saveRelationshipsUsing(null)
  182. ->dehydrated(true)
  183. ->preload()
  184. ->multiple()
  185. ->live()
  186. ->searchable(),
  187. Forms\Components\Select::make('salesDiscounts')
  188. ->relationship('salesDiscounts', 'name')
  189. ->saveRelationshipsUsing(null)
  190. ->dehydrated(true)
  191. ->preload()
  192. ->multiple()
  193. ->live()
  194. ->hidden(function (Forms\Get $get) {
  195. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  196. return $discountMethod->isPerDocument();
  197. })
  198. ->searchable(),
  199. Forms\Components\Placeholder::make('total')
  200. ->hiddenLabel()
  201. ->extraAttributes(['class' => 'text-left sm:text-right'])
  202. ->content(function (Forms\Get $get) {
  203. $quantity = max((float) ($get('quantity') ?? 0), 0);
  204. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  205. $salesTaxes = $get('salesTaxes') ?? [];
  206. $salesDiscounts = $get('salesDiscounts') ?? [];
  207. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  208. $subtotal = $quantity * $unitPrice;
  209. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  210. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  211. ->get()
  212. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  213. if ($adjustment->computation->isPercentage()) {
  214. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  215. } else {
  216. return $adjustment->getRawOriginal('rate');
  217. }
  218. });
  219. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  220. ->get()
  221. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  222. if ($adjustment->computation->isPercentage()) {
  223. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  224. } else {
  225. return $adjustment->getRawOriginal('rate');
  226. }
  227. });
  228. // Final total
  229. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  230. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  231. }),
  232. ]),
  233. DocumentTotals::make()
  234. ->type(DocumentType::Invoice),
  235. Forms\Components\Textarea::make('terms')
  236. ->columnSpanFull(),
  237. ]),
  238. Forms\Components\Section::make('Invoice Footer')
  239. ->collapsible()
  240. ->collapsed()
  241. ->schema([
  242. Forms\Components\Textarea::make('footer')
  243. ->columnSpanFull(),
  244. ]),
  245. ]);
  246. }
  247. public static function table(Table $table): Table
  248. {
  249. return $table
  250. ->columns([
  251. //
  252. ])
  253. ->filters([
  254. //
  255. ])
  256. ->actions([
  257. Tables\Actions\EditAction::make(),
  258. ])
  259. ->bulkActions([
  260. Tables\Actions\BulkActionGroup::make([
  261. Tables\Actions\DeleteBulkAction::make(),
  262. ]),
  263. ]);
  264. }
  265. public static function getRelations(): array
  266. {
  267. return [
  268. //
  269. ];
  270. }
  271. public static function getPages(): array
  272. {
  273. return [
  274. 'index' => Pages\ListRecurringInvoices::route('/'),
  275. 'create' => Pages\CreateRecurringInvoice::route('/create'),
  276. 'view' => Pages\ViewRecurringInvoice::route('/{record}'),
  277. 'edit' => Pages\EditRecurringInvoice::route('/{record}/edit'),
  278. ];
  279. }
  280. }