2024-04-20 14:07:06 +02:00
|
|
|
import { Controller } from "@hotwired/stimulus";
|
|
|
|
import { CurrenciesService } from "services/currencies_service";
|
|
|
|
|
|
|
|
// Connects to data-controller="money-field"
|
|
|
|
// when currency select change, update the input value with the correct placeholder and step
|
|
|
|
export default class extends Controller {
|
2024-07-16 14:08:24 -04:00
|
|
|
static targets = ["amount", "currency", "symbol"];
|
2025-07-09 22:28:07 -04:00
|
|
|
static values = { syncCurrency: Boolean };
|
2024-04-20 14:07:06 +02:00
|
|
|
|
2024-07-16 14:08:24 -04:00
|
|
|
handleCurrencyChange(e) {
|
|
|
|
const selectedCurrency = e.target.value;
|
2024-04-20 14:07:06 +02:00
|
|
|
this.updateAmount(selectedCurrency);
|
2025-07-09 22:28:07 -04:00
|
|
|
|
|
|
|
if (this.syncCurrencyValue) {
|
|
|
|
this.syncOtherMoneyFields(selectedCurrency);
|
|
|
|
}
|
2024-04-20 14:07:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
updateAmount(currency) {
|
2024-10-14 23:09:27 +02:00
|
|
|
new CurrenciesService().get(currency).then((currency) => {
|
2024-07-16 14:08:24 -04:00
|
|
|
this.amountTarget.step = currency.step;
|
|
|
|
|
2024-10-14 23:09:27 +02:00
|
|
|
if (Number.isFinite(this.amountTarget.value)) {
|
|
|
|
this.amountTarget.value = Number.parseFloat(
|
|
|
|
this.amountTarget.value,
|
|
|
|
).toFixed(currency.default_precision);
|
2024-07-16 14:08:24 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
this.symbolTarget.innerText = currency.symbol;
|
2024-04-20 14:07:06 +02:00
|
|
|
});
|
|
|
|
}
|
2025-07-09 22:28:07 -04:00
|
|
|
|
|
|
|
syncOtherMoneyFields(selectedCurrency) {
|
|
|
|
// Find the form this money field belongs to
|
|
|
|
const form = this.element.closest("form");
|
|
|
|
if (!form) return;
|
|
|
|
|
|
|
|
// Find all other money field controllers in the same form
|
|
|
|
const allMoneyFields = form.querySelectorAll('[data-controller~="money-field"]');
|
|
|
|
|
|
|
|
allMoneyFields.forEach(field => {
|
|
|
|
// Skip the current field
|
|
|
|
if (field === this.element) return;
|
|
|
|
|
|
|
|
// Get the controller instance
|
|
|
|
const controller = this.application.getControllerForElementAndIdentifier(field, "money-field");
|
|
|
|
if (!controller) return;
|
|
|
|
|
|
|
|
// Update the currency select if it exists
|
|
|
|
if (controller.hasCurrencyTarget) {
|
|
|
|
controller.currencyTarget.value = selectedCurrency;
|
|
|
|
controller.updateAmount(selectedCurrency);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2024-10-14 23:09:27 +02:00
|
|
|
}
|