Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

MacroServiceProvider.php 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php
  2. namespace App\Providers;
  3. use Akaunting\Money\Currency;
  4. use Akaunting\Money\Money;
  5. use App\Enums\Accounting\AdjustmentComputation;
  6. use App\Enums\Setting\DateFormat;
  7. use App\Models\Accounting\AccountSubtype;
  8. use App\Models\Setting\Localization;
  9. use App\Services\CompanySettingsService;
  10. use App\Utilities\Accounting\AccountCode;
  11. use App\Utilities\Currency\CurrencyAccessor;
  12. use App\Utilities\Currency\CurrencyConverter;
  13. use BackedEnum;
  14. use Carbon\CarbonInterface;
  15. use Closure;
  16. use Filament\Actions\Exports\ExportColumn;
  17. use Filament\Forms\Components\DatePicker;
  18. use Filament\Forms\Components\Field;
  19. use Filament\Forms\Components\TextInput;
  20. use Filament\Infolists\Components\TextEntry;
  21. use Filament\Support\Contracts\HasLabel;
  22. use Filament\Support\Enums\IconPosition;
  23. use Filament\Support\RawJs;
  24. use Filament\Tables\Columns\TextColumn;
  25. use Filament\Tables\Contracts\HasTable;
  26. use Illuminate\Contracts\Support\Htmlable;
  27. use Illuminate\Support\Carbon;
  28. use Illuminate\Support\Collection;
  29. use Illuminate\Support\HtmlString;
  30. use Illuminate\Support\ServiceProvider;
  31. class MacroServiceProvider extends ServiceProvider
  32. {
  33. /**
  34. * Register services.
  35. */
  36. public function register(): void
  37. {
  38. //
  39. }
  40. /**
  41. * Bootstrap services.
  42. */
  43. public function boot(): void
  44. {
  45. Collection::macro('whereNot', function (callable | string $key, mixed $value = null): Collection {
  46. return $this->where($key, '!=', $value);
  47. });
  48. TextInput::macro('money', function (string | Closure | null $currency = null, bool $useAffix = true): static {
  49. $currency ??= CurrencyAccessor::getDefaultCurrency();
  50. if ($useAffix) {
  51. $this
  52. ->prefix(static function (TextInput $component) use ($currency) {
  53. $currency = $component->evaluate($currency);
  54. return currency($currency)->getPrefix();
  55. })
  56. ->suffix(static function (TextInput $component) use ($currency) {
  57. $currency = $component->evaluate($currency);
  58. return currency($currency)->getSuffix();
  59. });
  60. }
  61. $this->mask(RawJs::make('$money($input)'))
  62. ->afterStateHydrated(function (TextInput $component, ?int $state) {
  63. if (blank($state)) {
  64. return;
  65. }
  66. $formatted = CurrencyConverter::convertCentsToFormatSimple($state, 'USD');
  67. $component->state($formatted);
  68. })
  69. ->dehydrateStateUsing(function (?string $state): ?int {
  70. if (blank($state)) {
  71. return null;
  72. }
  73. // Remove thousand separators
  74. $cleaned = str_replace(',', '', $state);
  75. // If no decimal point, assume it's whole dollars (add .00)
  76. if (! str_contains($cleaned, '.')) {
  77. $cleaned .= '.00';
  78. }
  79. // Convert to float then to cents (integer)
  80. return (int) round((float) $cleaned * 100);
  81. });
  82. return $this;
  83. });
  84. TextInput::macro('rate', function (string | Closure | null $computation = null, string | Closure | null $currency = null, bool $showAffix = true): static {
  85. return $this
  86. ->when(
  87. $showAffix,
  88. fn (TextInput $component) => $component
  89. ->prefix(function (TextInput $component) use ($computation, $currency) {
  90. $evaluatedComputation = $component->evaluate($computation);
  91. $evaluatedCurrency = $component->evaluate($currency);
  92. return ratePrefix($evaluatedComputation, $evaluatedCurrency);
  93. })
  94. ->suffix(function (TextInput $component) use ($computation, $currency) {
  95. $evaluatedComputation = $component->evaluate($computation);
  96. $evaluatedCurrency = $component->evaluate($currency);
  97. return rateSuffix($evaluatedComputation, $evaluatedCurrency);
  98. })
  99. )
  100. ->mask(static function (TextInput $component) use ($computation, $currency) {
  101. $computation = $component->evaluate($computation);
  102. $currency = $component->evaluate($currency);
  103. $computationEnum = AdjustmentComputation::parse($computation);
  104. if ($computationEnum->isPercentage()) {
  105. return rateMask(computation: $computation);
  106. }
  107. return moneyMask($currency);
  108. })
  109. ->rule(static function (TextInput $component) use ($computation) {
  110. return static function (string $attribute, $value, Closure $fail) use ($computation, $component) {
  111. $computation = $component->evaluate($computation);
  112. $numericValue = (float) $value;
  113. if ($computation instanceof BackedEnum) {
  114. $computation = $computation->value;
  115. }
  116. if ($computation === 'percentage' || $computation === 'compound') {
  117. if ($numericValue < 0 || $numericValue > 100) {
  118. $fail(translate('The rate must be between 0 and 100.'));
  119. }
  120. } elseif ($computation === 'fixed' && $numericValue < 0) {
  121. $fail(translate('The rate must be greater than 0.'));
  122. }
  123. };
  124. });
  125. });
  126. TextColumn::macro('coloredDescription', function (string | Htmlable | Closure | null $description, string $color = 'danger') {
  127. $this->description(static function (TextColumn $column) use ($description, $color): Htmlable {
  128. $description = $column->evaluate($description);
  129. return new HtmlString("<span class='text-{$color}-700 dark:text-{$color}-400'>{$description}</span>");
  130. });
  131. return $this;
  132. });
  133. TextColumn::macro('hideOnTabs', function (array $tabs): static {
  134. $this->toggleable(isToggledHiddenByDefault: function (HasTable $livewire) use ($tabs) {
  135. return in_array($livewire->activeTab, $tabs);
  136. });
  137. return $this;
  138. });
  139. TextColumn::macro('showOnTabs', function (array $tabs): static {
  140. $this->toggleable(isToggledHiddenByDefault: function (HasTable $livewire) use ($tabs) {
  141. return ! in_array($livewire->activeTab, $tabs);
  142. });
  143. return $this;
  144. });
  145. TextColumn::macro('defaultDateFormat', function (): static {
  146. $localization = Localization::firstOrFail();
  147. $dateFormat = $localization->date_format->value ?? DateFormat::DEFAULT;
  148. $timezone = $localization->timezone ?? Carbon::now()->timezoneName;
  149. $this->date($dateFormat, $timezone);
  150. return $this;
  151. });
  152. DatePicker::macro('defaultDateFormat', function (): static {
  153. $localization = Localization::firstOrFail();
  154. $dateFormat = $localization->date_format->value ?? DateFormat::DEFAULT;
  155. $timezone = $localization->timezone ?? Carbon::now()->timezoneName;
  156. $this->displayFormat($dateFormat)
  157. ->timezone($timezone);
  158. return $this;
  159. });
  160. TextColumn::macro('currency', function (string | Closure | null $currency = null, ?bool $convert = null): static {
  161. $currency ??= CurrencyAccessor::getDefaultCurrency();
  162. $convert ??= false;
  163. $this->formatStateUsing(static function (TextColumn $column, $state) use ($currency, $convert): ?string {
  164. if (blank($state)) {
  165. return null;
  166. }
  167. $currency = $column->evaluate($currency);
  168. $convert = $column->evaluate($convert);
  169. return money($state, $currency, $convert)->format();
  170. });
  171. return $this;
  172. });
  173. TextEntry::macro('currency', function (string | Closure | null $currency = null, ?bool $convert = null): static {
  174. $currency ??= CurrencyAccessor::getDefaultCurrency();
  175. $convert ??= false;
  176. $this->formatStateUsing(static function (TextEntry $entry, $state) use ($currency, $convert): ?string {
  177. if (blank($state)) {
  178. return null;
  179. }
  180. $currency = $entry->evaluate($currency);
  181. $convert = $entry->evaluate($convert);
  182. return money($state, $currency, $convert)->format();
  183. });
  184. return $this;
  185. });
  186. TextColumn::macro('currencyWithConversion', function (string | Closure | null $currency = null, ?bool $convertFromCents = null): static {
  187. $currency ??= CurrencyAccessor::getDefaultCurrency();
  188. $convertFromCents ??= true;
  189. $this->formatStateUsing(static function (TextColumn $column, $state) use ($currency, $convertFromCents): ?string {
  190. if (blank($state)) {
  191. return null;
  192. }
  193. $currency = $column->evaluate($currency);
  194. $showCurrency = $currency !== CurrencyAccessor::getDefaultCurrency();
  195. if ($convertFromCents) {
  196. $balanceInCents = $state;
  197. } else {
  198. $balanceInCents = CurrencyConverter::convertToCents($state, $currency);
  199. }
  200. if ($balanceInCents < 0) {
  201. return '(' . CurrencyConverter::formatCentsToMoney(abs($balanceInCents), $currency, $showCurrency) . ')';
  202. }
  203. return CurrencyConverter::formatCentsToMoney($balanceInCents, $currency, $showCurrency);
  204. });
  205. $this->description(static function (TextColumn $column, $state) use ($currency, $convertFromCents): ?string {
  206. if (blank($state)) {
  207. return null;
  208. }
  209. $oldCurrency = $column->evaluate($currency);
  210. $newCurrency = CurrencyAccessor::getDefaultCurrency();
  211. if ($oldCurrency === $newCurrency) {
  212. return null;
  213. }
  214. if ($convertFromCents) {
  215. $balanceInCents = $state;
  216. } else {
  217. $balanceInCents = CurrencyConverter::convertToCents($state, $oldCurrency);
  218. }
  219. $convertedBalanceInCents = CurrencyConverter::convertBalance($balanceInCents, $oldCurrency, $newCurrency);
  220. if ($convertedBalanceInCents < 0) {
  221. return '(' . CurrencyConverter::formatCentsToMoney(abs($convertedBalanceInCents), $newCurrency, true) . ')';
  222. }
  223. return CurrencyConverter::formatCentsToMoney($convertedBalanceInCents, $newCurrency, true);
  224. });
  225. return $this;
  226. });
  227. TextEntry::macro('currencyWithConversion', function (string | Closure | null $currency = null): static {
  228. $currency ??= CurrencyAccessor::getDefaultCurrency();
  229. $this->formatStateUsing(static function (TextEntry $entry, $state) use ($currency): ?string {
  230. if (blank($state)) {
  231. return null;
  232. }
  233. $currency = $entry->evaluate($currency);
  234. return CurrencyConverter::formatToMoney($state, $currency);
  235. });
  236. $this->helperText(static function (TextEntry $entry, $state) use ($currency): ?string {
  237. if (blank($state)) {
  238. return null;
  239. }
  240. $oldCurrency = $entry->evaluate($currency);
  241. $newCurrency = CurrencyAccessor::getDefaultCurrency();
  242. if ($oldCurrency === $newCurrency) {
  243. return null;
  244. }
  245. $balanceInCents = CurrencyConverter::convertToCents($state, $oldCurrency);
  246. $convertedBalanceInCents = CurrencyConverter::convertBalance($balanceInCents, $oldCurrency, $newCurrency);
  247. return CurrencyConverter::formatCentsToMoney($convertedBalanceInCents, $newCurrency, true);
  248. });
  249. return $this;
  250. });
  251. Field::macro('validateAccountCode', function (string | Closure | null $subtype = null): static {
  252. $this
  253. ->rules([
  254. fn (Field $component): Closure => static function (string $attribute, $value, Closure $fail) use ($subtype, $component) {
  255. $subtype = $component->evaluate($subtype);
  256. $chartSubtype = AccountSubtype::find($subtype);
  257. $type = $chartSubtype->type;
  258. if (! AccountCode::isValidCode($value, $type)) {
  259. $message = AccountCode::getMessage($type);
  260. $fail($message);
  261. }
  262. },
  263. ]);
  264. return $this;
  265. });
  266. TextColumn::macro('rate', function (string | Closure | null $computation = null): static {
  267. $this->formatStateUsing(static function (TextColumn $column, $state) use ($computation): ?string {
  268. $computation = $column->evaluate($computation);
  269. return rateFormat(state: $state, computation: $computation);
  270. });
  271. return $this;
  272. });
  273. Field::macro('softRequired', function (): static {
  274. $this
  275. ->required()
  276. ->markAsRequired(false);
  277. return $this;
  278. });
  279. TextColumn::macro('asRelativeDay', function (?string $timezone = null): static {
  280. $this->formatStateUsing(function (TextColumn $column, mixed $state) use ($timezone) {
  281. if (blank($state)) {
  282. return null;
  283. }
  284. $date = Carbon::parse($state)
  285. ->setTimezone($timezone ?? $column->getTimezone());
  286. if ($date->isToday()) {
  287. return 'Today';
  288. }
  289. return $date->diffForHumans([
  290. 'options' => CarbonInterface::ONE_DAY_WORDS,
  291. ]);
  292. });
  293. return $this;
  294. });
  295. TextEntry::macro('asRelativeDay', function (?string $timezone = null): static {
  296. $this->formatStateUsing(function (TextEntry $entry, mixed $state) use ($timezone) {
  297. if (blank($state)) {
  298. return null;
  299. }
  300. $date = Carbon::parse($state)
  301. ->setTimezone($timezone ?? $entry->getTimezone());
  302. if ($date->isToday()) {
  303. return 'Today';
  304. }
  305. return $date->diffForHumans([
  306. 'options' => CarbonInterface::ONE_DAY_WORDS,
  307. ]);
  308. });
  309. return $this;
  310. });
  311. TextEntry::macro('link', function (bool $condition = true): static {
  312. if ($condition) {
  313. $this
  314. ->limit(50)
  315. ->openUrlInNewTab()
  316. ->icon('heroicon-o-arrow-top-right-on-square')
  317. ->iconColor('primary')
  318. ->iconPosition(IconPosition::After);
  319. }
  320. return $this;
  321. });
  322. Money::macro('swapAmountFor', function ($newCurrency) {
  323. $oldCurrency = $this->currency->getCurrency();
  324. $balanceInSubunits = $this->getAmount();
  325. $oldCurrencySubunit = currency($oldCurrency)->getSubunit();
  326. $newCurrencySubunit = currency($newCurrency)->getSubunit();
  327. $balanceInMajorUnits = $balanceInSubunits / $oldCurrencySubunit;
  328. $oldRate = currency($oldCurrency)->getRate();
  329. $newRate = currency($newCurrency)->getRate();
  330. $ratio = $newRate / $oldRate;
  331. $convertedBalanceInMajorUnits = $balanceInMajorUnits * $ratio;
  332. $roundedConvertedBalanceInMajorUnits = round($convertedBalanceInMajorUnits, currency($newCurrency)->getPrecision());
  333. $convertedBalanceInSubunits = $roundedConvertedBalanceInMajorUnits * $newCurrencySubunit;
  334. return (int) round($convertedBalanceInSubunits);
  335. });
  336. Money::macro('formatWithCode', function (bool $codeBefore = false) {
  337. $formatted = $this->format();
  338. $currencyCode = $this->currency->getCurrency();
  339. if ($codeBefore) {
  340. return $currencyCode . ' ' . $formatted;
  341. }
  342. return $formatted . ' ' . $currencyCode;
  343. });
  344. Currency::macro('getEntity', function () {
  345. $currencyCode = $this->getCurrency();
  346. $entity = config("money.currencies.{$currencyCode}.entity");
  347. return $entity ?? $currencyCode;
  348. });
  349. Currency::macro('getCodePrefix', function () {
  350. if ($this->isSymbolFirst()) {
  351. return '';
  352. }
  353. return ' ' . $this->getCurrency();
  354. });
  355. Currency::macro('getCodeSuffix', function () {
  356. if ($this->isSymbolFirst()) {
  357. return ' ' . $this->getCurrency();
  358. }
  359. return '';
  360. });
  361. Carbon::macro('toDefaultDateFormat', function () {
  362. $companyId = auth()->user()?->current_company_id;
  363. $dateFormat = CompanySettingsService::getDefaultDateFormat($companyId);
  364. $timezone = CompanySettingsService::getDefaultTimezone($companyId);
  365. return $this->setTimezone($timezone)->format($dateFormat);
  366. });
  367. ExportColumn::macro('money', function () {
  368. $this->formatStateUsing(static function ($state) {
  369. if (blank($state) || ! is_int($state)) {
  370. return 0.00;
  371. }
  372. return CurrencyConverter::convertCentsToFloat($state);
  373. });
  374. return $this;
  375. });
  376. ExportColumn::macro('date', function () {
  377. $this->formatStateUsing(static function ($state) {
  378. if (blank($state)) {
  379. return null;
  380. }
  381. try {
  382. return Carbon::parse($state)->toDateString();
  383. } catch (\Exception) {
  384. return null;
  385. }
  386. });
  387. return $this;
  388. });
  389. ExportColumn::macro('dateTime', function () {
  390. $this->formatStateUsing(static function ($state) {
  391. if (blank($state)) {
  392. return null;
  393. }
  394. try {
  395. return Carbon::parse($state)->toDateTimeString();
  396. } catch (\Exception) {
  397. return null;
  398. }
  399. });
  400. return $this;
  401. });
  402. ExportColumn::macro('enum', function () {
  403. $this->formatStateUsing(static function ($state) {
  404. if (blank($state)) {
  405. return null;
  406. }
  407. if (! ($state instanceof BackedEnum)) {
  408. return $state;
  409. }
  410. if ($state instanceof HasLabel) {
  411. return $state->getLabel();
  412. }
  413. return $state->value;
  414. });
  415. return $this;
  416. });
  417. }
  418. }