Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

MacroServiceProvider.php 17KB

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