您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RecurringInvoiceResource.php 19KB

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