Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

MacroServiceProvider.php 18KB

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