Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add logic for updating quote exchange rate
Rob Carringtone7c43f2b1b32
diff --git a/apps/carbon/app/components/Form/ExchangeRate.tsx b/apps/carbon/app/components/Form/ExchangeRate.tsxindex 0a98f7b730..6bba53b1e6 100644--- a/apps/carbon/app/components/Form/ExchangeRate.tsx+++ b/apps/carbon/app/components/Form/ExchangeRate.tsx@@ -27,7 +27,7 @@ const ExchangeRate: React.FC<ExchangeRateProps> = ({() =>new Intl.DateTimeFormat(locale, {dateStyle: "medium",- timeZone: "UTC",+ timeStyle: "short",}),[locale]);@@ -48,9 +48,7 @@ const ExchangeRate: React.FC<ExchangeRateProps> = ({<TooltipTrigger tabIndex={-1}><LuInfo className="w-4 h-4" /></TooltipTrigger>- <TooltipContent>- Last updated on: {formattedDate}- </TooltipContent>+ <TooltipContent>Last updated: {formattedDate}</TooltipContent></Tooltip>)}</HStack>diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.tsindex 68988ab5d4..3332c790ea 100644--- a/apps/carbon/app/modules/sales/sales.service.ts+++ b/apps/carbon/app/modules/sales/sales.service.ts@@ -6,6 +6,7 @@ import { getEmployeeJob } from "~/modules/people";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";+import { getCurrencyByCode } from "../accounting";import type {customerAccountingValidator,customerContactValidator,@@ -1346,6 +1347,22 @@ export async function updateSalesRFQLineOrder(return Promise.all(updatePromises);}+export async function updateQuoteExchangeRate(+ client: SupabaseClient<Database>,+ data: {+ id: string;+ exchangeRate: number;+ }+) {+ const update = {+ id: data.id,+ exchangeRate: data.exchangeRate,+ exchangeRateUpdatedAt: new Date().toISOString(),+ };++ return client.from("quote").update(update).eq("id", update.id);+}+export async function updateQuoteFavorite(client: SupabaseClient<Database>,args: {@@ -1510,6 +1527,21 @@ export async function upsertQuote(const { shippingMethodId, shippingTermId } = customerShipping.data;+ if (quote.currencyCode) {+ const currency = await getCurrencyByCode(+ client,+ quote.companyId,+ quote.currencyCode+ );+ if (currency.data) {+ quote.exchangeRate = currency.data.exchangeRate ?? undefined;+ quote.exchangeRateUpdatedAt = new Date().toISOString();+ }+ } else {+ quote.exchangeRate = 1;+ quote.exchangeRateUpdatedAt = new Date().toISOString();+ }+const locationId = employee?.data?.locationId ?? null;const insert = await client.from("quote")@@ -1562,6 +1594,28 @@ export async function upsertQuote(return insert;} else {+ // Only update the exchange rate if the currency code has changed+ const existingQuote = await client+ .from("quote")+ .select("companyId, currencyCode")+ .eq("id", quote.id)+ .single();++ if (existingQuote.error) return existingQuote;++ const { companyId, currencyCode } = existingQuote.data;++ if (quote.currencyCode && currencyCode !== quote.currencyCode) {+ const currency = await getCurrencyByCode(+ client,+ companyId,+ quote.currencyCode+ );+ if (currency.data) {+ quote.exchangeRate = currency.data.exchangeRate ?? undefined;+ quote.exchangeRateUpdatedAt = new Date().toISOString();+ }+ }return client.from("quote").update({diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsxindex 01a7520d9a..32a50ba0db 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx@@ -11,6 +11,7 @@ import {cn,toast,} from "@carbon/react";+import { useFetcher } from "@remix-run/react";import { useState } from "react";import { flushSync } from "react-dom";import type { z } from "zod";@@ -28,8 +29,9 @@ import {Submit,} from "~/components/Form";import ExchangeRate from "~/components/Form/ExchangeRate";-import { usePermissions } from "~/hooks";+import { usePermissions, useUser } from "~/hooks";import { quoteValidator } from "~/modules/sales";+import { path } from "~/utils/path";type QuoteFormValues = z.infer<typeof quoteValidator>;@@ -40,6 +42,7 @@ type QuoteFormProps = {const QuoteForm = ({ initialValues }: QuoteFormProps) => {const permissions = usePermissions();const { carbon } = useCarbon();+ const { company } = useUser();const [customer, setCustomer] = useState<{id: string | undefined;currencyCode: string | undefined;@@ -51,6 +54,8 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {const isDisabled = initialValues?.status !== "Draft";const isEditing = initialValues.id !== undefined;+ const exchangeRateFetcher = useFetcher<{ exchangeRate: number }>();+const onCustomerChange = async (newValue: {value: string | undefined;@@ -168,16 +173,27 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {}}}/>- {isEditing && (- <ExchangeRate- name="exchangeRate"- exchangeRateUpdatedAt={initialValues.exchangeRateUpdatedAt}- isReadOnly- onRefresh={() => {- console.log("refresh");- }}- />- )}+ {isEditing &&+ customer.currencyCode !== company.baseCurrencyCode && (+ <ExchangeRate+ name="exchangeRate"+ exchangeRateUpdatedAt={initialValues.exchangeRateUpdatedAt}+ isReadOnly+ onRefresh={() => {+ const formData = new FormData();+ formData.append(+ "currencyCode",+ customer.currencyCode ?? ""+ );+ exchangeRateFetcher.submit(formData, {+ method: "post",+ action: path.to.quoteExchangeRate(+ initialValues.id ?? ""+ ),+ });+ }}+ />+ )}<CustomFormFields table="quote" /></div>diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.exchange-rate.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.exchange-rate.tsxnew file mode 100644index 0000000000..3c42464ced--- /dev/null+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.exchange-rate.tsx@@ -0,0 +1,39 @@+import { assertIsPost, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { redirect, type ActionFunctionArgs } from "@vercel/remix";+import { getCurrencyByCode } from "~/modules/accounting";+import { updateQuoteExchangeRate } from "~/modules/sales";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ create: "sales",+ });++ const { quoteId } = params;+ if (!quoteId) throw new Error("Could not find quoteId");++ const formData = await request.formData();+ const currencyCode = formData.get("currencyCode") as string;+ if (!currencyCode) throw new Error("Could not find currencyCode");++ const currency = await getCurrencyByCode(client, companyId, currencyCode);+ if (currency.error || !currency.data.exchangeRate)+ throw new Error("Could not find currency");++ const update = await updateQuoteExchangeRate(client, {+ id: quoteId,+ exchangeRate: currency.data.exchangeRate,+ });++ if (update.error) {+ throw new Error("Could not update exchange rate");+ }++ return redirect(+ path.to.quoteDetails(quoteId),+ await flash(request, success("Successfully updated exchange rate"))+ );+}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex 31c9018ad0..e18ec36162 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -634,6 +634,8 @@ export const path = {`${x}/quote/${quoteId}/lines/${lineId}/assembly/${assemblyId}`),quoteDetails: (id: string) => generatePath(`${x}/quote/${id}/details`),+ quoteExchangeRate: (id: string) =>+ generatePath(`${x}/quote/${id}/exchange-rate`),quoteExternalDocuments: (id: string) =>generatePath(`${x}/quote/${id}/external`),quoteFavorite: `${x}/sales/quotes/favorite`,