Skip to content

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.

feat: update and cancel subscription types

Brad Barbined1d78f4f664
diff --git a/apps/erp/app/hooks/usePermissions.tsx b/apps/erp/app/hooks/usePermissions.tsx
index ad48b78399..7a97da4418 100644
--- a/apps/erp/app/hooks/usePermissions.tsx
+++ b/apps/erp/app/hooks/usePermissions.tsx
@@ -12,7 +12,8 @@ export function usePermissions() {
}>(path.to.authenticatedRoot);
const {
- company: { id: companyId },
+ id: userId,
+ company: { id: companyId, ownerId },
} = useUser();
if (!isPermissions(data?.permissions) || !isRole(data?.role)) {
@@ -46,10 +47,15 @@ export function usePermissions() {
[data?.role]
);
+ const isOwner = useCallback(() => {
+ return ownerId === userId;
+ }, [ownerId, userId]);
+
return {
can,
has,
is,
+ isOwner,
};
}
diff --git a/apps/erp/app/hooks/useUser.tsx b/apps/erp/app/hooks/useUser.tsx
index 073d3bb878..63027f3f35 100644
--- a/apps/erp/app/hooks/useUser.tsx
+++ b/apps/erp/app/hooks/useUser.tsx
@@ -19,6 +19,7 @@ type Company = {
logoLight: string | null;
countryCode: string | null;
baseCurrencyCode: string;
+ ownerId: string;
};
type Groups = string[];
@@ -40,6 +41,7 @@ export function useUser(): User {
groups: unknown;
defaults: unknown;
}>(path.to.authenticatedRoot);
+
if (
data?.company &&
isCompany(data.company) &&
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 2b8fa8c9c2..ea3c86d545 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1379,7 +1379,6 @@ export async function upsertMakeMethodFromJobMethod(
userId: string;
}
) {
- console.log("upsertMakeMethodFromJobMethod", jobMethod);
const { error } = await client.functions.invoke("get-method", {
body: {
type: "jobMakeMethodToItem",
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index c82730f8a9..899863b185 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -80,8 +80,6 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
makeMethod: JobMakeMethod;
}>(path.to.jobMakeMethod(jobId, methodId!));
- console.log(materialRouteData);
-
const itemId =
materialRouteData?.makeMethod?.itemId ?? routeData?.job?.itemId;
const itemType =
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index bb579144c0..38529a77c5 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -382,16 +382,13 @@ export async function getWebhooks(
export async function insertCompany(
client: SupabaseClient<Database>,
company: z.infer<typeof companyValidator>,
- id?: string
+ ownerId?: string
) {
- if (id) {
- return client
- .from("company")
- .insert({ ...company, id })
- .select("id")
- .single();
- }
- return client.from("company").insert(company).select("id").single();
+ return client
+ .from("company")
+ .insert({ ...company, ownerId })
+ .select("id")
+ .single();
}
export async function updateCompanyPlan(
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index bfd3f86c7b..d60e749396 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -1,5 +1,6 @@
import {
LuBarcode,
+ LuCreditCard,
LuCrown,
LuFactory,
LuImage,
@@ -23,6 +24,13 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
role: "employee",
icon: <LuFactory />,
},
+ {
+ name: "Payment",
+ to: path.to.settingsPayment,
+ role: "employee",
+ icon: <LuCreditCard />,
+ requiresOwnership: true,
+ },
{
name: "Labels",
to: path.to.labelsSettings,
@@ -91,17 +99,19 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
},
];
-export default function usePurchasingSubmodules() {
+export default function useSettingsSubmodules() {
const permissions = usePermissions();
+
return {
groups: settingsRoutes
.filter((group) => {
const filteredRoutes = group.routes.filter((route) => {
- if (route.role) {
- return permissions.is(route.role);
- } else {
- return true;
+ // Check role permission
+ if (route.role && !permissions.is(route.role)) {
+ return false;
}
+
+ return true;
});
return filteredRoutes.length > 0;
@@ -109,11 +119,17 @@ export default function usePurchasingSubmodules() {
.map((group) => ({
...group,
routes: group.routes.filter((route) => {
- if (route.role) {
- return permissions.is(route.role);
- } else {
- return true;
+ // Check role permission
+ if (route.role && !permissions.is(route.role)) {
+ return false;
+ }
+
+ // Check ownership requirement
+ if (route.requiresOwnership && !permissions.isOwner()) {
+ return false;
}
+
+ return true;
}),
})),
};
diff --git a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
index 108aed6aee..598aea90eb 100644
--- a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
+++ b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
@@ -302,7 +302,7 @@ const EmployeesTable = memo(
}
renderActions={renderActions}
renderContextMenu={renderContextMenu}
- title="Employees"
+ title="Employee Accounts"
withSelectableRows={canEdit}
/>
{bulkEditDrawer.isOpen && (
diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.ts
index bef09c06b8..674fb10ed7 100644
--- a/apps/erp/app/modules/users/users.server.ts
+++ b/apps/erp/app/modules/users/users.server.ts
@@ -8,6 +8,7 @@ import {
} from "@carbon/auth/users.server";
import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
+import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";
import type { SupabaseClient } from "@supabase/supabase-js";
import { redirect } from "@vercel/remix";
import { getSupplierContact } from "~/modules/purchasing";
@@ -82,6 +83,7 @@ export async function acceptInvite(
user.data.id,
invite.data.permissions as Record<string, string[]>
),
+ updateSubscriptionQuantityForCompany(invite.data.companyId),
]);
if (activate.error) {
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index 6e6261824c..2689a9d7b9 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -79,8 +79,6 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
const { email } = validation.data;
const user = await getUserByEmail(email);
- console.log("User:", user);
-
if (user.data && user.data.active) {
const magicLink = await sendMagicLink(email);
diff --git a/apps/erp/app/routes/_public+/verify.tsx b/apps/erp/app/routes/_public+/verify.tsx
index 8b9ecadd4b..a2f1322ced 100644
--- a/apps/erp/app/routes/_public+/verify.tsx
+++ b/apps/erp/app/routes/_public+/verify.tsx
@@ -66,10 +66,8 @@ const ratelimit = new Ratelimit({
export async function action({ request }: ActionFunctionArgs): FormActionData {
assertIsPost(request);
const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
- console.log("IP address:", ip);
const { success } = await ratelimit.limit(ip);
- console.log("Rate limit success:", success);
if (!success) {
return json(
@@ -81,18 +79,15 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
const validation = await validator(verifyValidator).validate(
await request.formData()
);
- console.log("Validation result:", validation);
if (validation.error) {
return json(error(validation.error, "Invalid verification code"));
}
const { email, code, redirectTo } = validation.data;
- console.log("Form data:", { email, code, redirectTo });
// Verify the email code
const isCodeValid = await verifyEmailCode(email, code);
- console.log("Code validation result:", isCodeValid);
if (!isCodeValid) {
return json(
@@ -103,10 +98,8 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
// Create the user account with a temporary password
const temporaryPassword = crypto.randomBytes(16).toString("hex");
- console.log("Generated temporary password");
const user = await createEmailAuthAccount(email, temporaryPassword);
- console.log("User creation result:", user);
if (!user) {
return json(
@@ -117,7 +110,6 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
// Sign in the user to create an authentication session
const authSession = await signInWithEmail(email, temporaryPassword);
- console.log("Auth session result:", authSession);
if (!authSession) {
return json(
@@ -129,11 +121,9 @@ export async function action({ request }: ActionFunctionArgs): FormActionData {
const sessionCookie = await setAuthSession(request, {
authSession,
});
- console.log("Session cookie created");
// Set the authentication session
const onboardingUrl = redirectTo || path.to.onboarding.root;
- console.log("Redirecting to:", onboardingUrl);
return redirect(onboardingUrl, {
headers: [["Set-Cookie", sessionCookie]],
diff --git a/apps/erp/app/routes/onboarding+/company.tsx b/apps/erp/app/routes/onboarding+/company.tsx
index 59bfc71e47..2b969b4413 100644
--- a/apps/erp/app/routes/onboarding+/company.tsx
+++ b/apps/erp/app/routes/onboarding+/company.tsx
@@ -101,7 +101,7 @@ export async function action({ request }: ActionFunctionArgs) {
} else {
if (!companyId) {
const [companyInsert] = await Promise.all([
- insertCompany(serviceRole, data),
+ insertCompany(serviceRole, data, userId),
]);
if (companyInsert.error) {
console.error(companyInsert.error);
diff --git a/apps/erp/app/routes/x+/settings+/company.new.tsx b/apps/erp/app/routes/x+/settings+/company.new.tsx
index 5e4c63624f..10dc7916ee 100644
--- a/apps/erp/app/routes/x+/settings+/company.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/company.new.tsx
@@ -30,7 +30,7 @@ export async function action({ request }: ActionFunctionArgs) {
const client = getCarbonServiceRole();
- const companyInsert = await insertCompany(client, validation.data);
+ const companyInsert = await insertCompany(client, validation.data, userId);
if (companyInsert.error) {
console.error(companyInsert.error);
throw new Error("Fatal: failed to insert company");
diff --git a/apps/erp/app/routes/x+/settings+/company.tsx b/apps/erp/app/routes/x+/settings+/company.tsx
index 067d1dc512..12ebbc1a72 100644
--- a/apps/erp/app/routes/x+/settings+/company.tsx
+++ b/apps/erp/app/routes/x+/settings+/company.tsx
@@ -1,20 +1,32 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
import {
+ SelectControlled,
+ ValidatedForm,
+ validationError,
+ validator,
+} from "@carbon/form";
+import {
+ Button,
Card,
CardContent,
CardDescription,
+ CardFooter,
CardHeader,
CardTitle,
Heading,
ScrollArea,
+ Status,
VStack,
} from "@carbon/react";
-import type { ActionFunctionArgs } from "@vercel/remix";
+import { Form, useLoaderData } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import { useRouteData } from "~/hooks";
+import { useState } from "react";
+import { z } from "zod";
+import { Submit } from "~/components/Form";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import type { Company as CompanyType } from "~/modules/settings";
import {
CompanyForm,
@@ -29,13 +41,115 @@ export const handle: Handle = {
to: path.to.company,
};
+const transferOwnershipValidator = z.object({
+ intent: z.literal("transfer-ownership"),
+ newOwnerId: z.string().min(1, { message: "New owner is required" }),
+});
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings",
+ });
+
+ // Get company plan and usage data for payment section
+ const companyPlan = await client
+ .from("companyPlan")
+ .select(
+ `
+ *,
+ plan:planId (
+ name,
+ userBasedPricing,
+ tasksLimit,
+ aiTokensLimit
+ )
+ `
+ )
+ .eq("id", companyId)
+ .single();
+
+ const companyUsage = await client
+ .from("companyUsage")
+ .select("*")
+ .eq("companyId", companyId)
+ .single();
+
+ const userToCompany = await client
+ .from("userToCompany")
+ .select("userId")
+ .eq("companyId", companyId)
+ .eq("role", "employee");
+
+ const userIds = userToCompany.data?.map((utc) => utc.userId) || [];
+
+ const employees =
+ userIds.length > 0
+ ? await client
+ .from("user")
+ .select(
+ `
+ id,
+ firstName,
+ lastName,
+ fullName,
+ email
+ `
+ )
+ .in("id", userIds)
+ : { data: [], error: null };
+
+ return json({
+ plan: companyPlan.data,
+ usage: companyUsage.data,
+ employees: employees.data || [],
+ });
+}
+
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
update: "settings",
});
const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "transfer-ownership") {
+ const validation = await validator(transferOwnershipValidator).validate(
+ formData
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+ const { newOwnerId } = validation.data;
+
+ try {
+ const updateResult = await client
+ .from("company")
+ .update({ ownerId: newOwnerId })
+ .eq("id", companyId);
+
+ if (updateResult.error) {
+ throw new Error(updateResult.error.message);
+ }
+
+ return json(
+ {},
+ await flash(
+ request,
+ success("Company ownership has been transferred successfully")
+ )
+ );
+ } catch (err) {
+ console.error("Failed to transfer ownership:", err);
+ return json(
+ {},
+ await flash(request, error("Failed to transfer ownership"))
+ );
+ }
+ }
+
+ // Handle company form updates
const validation = await validator(companyValidator).validate(formData);
if (validation.error) {
@@ -56,6 +170,11 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function Company() {
+ const { plan, usage, employees } = useLoaderData<typeof loader>();
+ const { isOwner } = usePermissions();
+ const { id: userId } = useUser();
+ const [ownerId, setOwnerId] = useState<string | null>(userId);
+
const routeData = useRouteData<{ company: CompanyType }>(
path.to.authenticatedRoot
);
@@ -97,7 +216,139 @@ export default function Company() {
<CompanyForm company={initialValues} />
</CardContent>
</Card>
+
+ {isOwner() && (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>Manage Subscription</CardTitle>
+ <CardDescription>
+ Manage your subscription and billing information
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={4}>
+ <div className="grid grid-cols-2 gap-4 w-full">
+ <div>
+ <h4 className="font-medium">Plan</h4>
+ <Status color="blue">
+ {plan?.plan?.name || "No active plan"}
+ </Status>
+ </div>
+ <div>
+ <h4 className="font-medium">Status</h4>
+
+ <SubscriptionStatus
+ status={plan?.stripeSubscriptionStatus || "Unknown"}
+ />
+ </div>
+ </div>
+
+ {usage && (
+ <div className="grid grid-cols-3 gap-4 pt-4 border-t">
+ <div>
+ <h4 className="font-medium">Users</h4>
+ <p className="text-sm text-muted-foreground">
+ {usage.users} / {plan?.usersLimit || "∞"}
+ </p>
+ </div>
+ <div>
+ <h4 className="font-medium">Tasks</h4>
+ <p className="text-sm text-muted-foreground">
+ {usage.tasks.toLocaleString()} /{" "}
+ {plan?.tasksLimit?.toLocaleString() || "∞"}
+ </p>
+ </div>
+ <div>
+ <h4 className="font-medium">AI Tokens</h4>
+ <p className="text-sm text-muted-foreground">
+ {usage.aiTokens.toLocaleString()} /{" "}
+ {plan?.aiTokensLimit?.toLocaleString() || "∞"}
+ </p>
+ </div>
+ </div>
+ )}
+ </VStack>
+ </CardContent>
+ <CardFooter>
+ <Form method="post" action={path.to.settingsPayment}>
+ <input type="hidden" name="intent" value="billing-portal" />
+ <Button type="submit">Manage Subscription</Button>
+ </Form>
+ </CardFooter>
+ </Card>
+
+ <ValidatedForm validator={transferOwnershipValidator} method="post">
+ <Card>
+ <CardHeader>
+ <CardTitle>Manage Ownership</CardTitle>
+ <CardDescription>
+ Transfer ownership of this company to another user
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={4}>
+ <p className="text-sm text-muted-foreground">
+ As the company owner, you can transfer ownership to
+ another employee. This will give them full access to
+ billing and administrative settings.
+ </p>
+ {employees.length > 0 ? (
+ <>
+ <input
+ type="hidden"
+ name="intent"
+ value="transfer-ownership"
+ />
+ <div className="grid grid-cols-2 gap-4 w-full">
+ <SelectControlled
+ name="newOwnerId"
+ label="New Owner"
+ placeholder="Select a new owner"
+ value={ownerId || undefined}
+ onChange={(value) => {
+ if (value?.value) {
+ setOwnerId(value.value);
+ }
+ }}
+ options={employees.map((employee) => ({
+ label: employee.fullName || employee.email,
+ value: employee.id,
+ }))}
+ />
+ </div>
+ </>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ No other employees found. Add employees to enable
+ ownership transfer.
+ </p>
+ )}
+ </VStack>
+ </CardContent>
+ <CardFooter>
+ <Submit isDisabled={ownerId === userId}>
+ Transfer Ownership
+ </Submit>
+ </CardFooter>
+ </Card>
+ </ValidatedForm>
+ </>
+ )}
</VStack>
</ScrollArea>
);
}
+
+function SubscriptionStatus({ status }: { status: string }) {
+ switch (status) {
+ case "Active":
+ return <Status color="green">Active</Status>;
+ case "Inactive":
+ return <Status color="orange">Inactive</Status>;
+ case "Cancelled":
+ return <Status color="red">Cancelled</Status>;
+ default:
+ return <Status color="gray">Unknown</Status>;
+ }
+}
diff --git a/apps/erp/app/routes/x+/settings+/payment.tsx b/apps/erp/app/routes/x+/settings+/payment.tsx
new file mode 100644
index 0000000000..a8dc5b5deb
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/payment.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { getBillingPortalRedirectUrl } from "@carbon/stripe/stripe.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Payment",
+ to: path.to.settingsPayment,
+};
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId } = await requirePermissions(request, {
+ update: "settings",
+ });
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "billing-portal") {
+ try {
+ const billingPortalUrl = await getBillingPortalRedirectUrl({ companyId });
+ return redirect(billingPortalUrl, 301);
+ } catch (err) {
+ console.error("Failed to get billing portal URL:", err);
+ return json(
+ {},
+ await flash(request, error("Failed to access billing portal"))
+ );
+ }
+ }
+
+ return json({}, await flash(request, error("Invalid intent")));
+}
+
+// This route now only handles actions - UI is in the company route
+export default function PaymentSettings() {
+ return null;
+}
diff --git a/apps/erp/app/types/index.ts b/apps/erp/app/types/index.ts
index cd0fd6d9fa..bbc05e5554 100644
--- a/apps/erp/app/types/index.ts
+++ b/apps/erp/app/types/index.ts
@@ -14,6 +14,7 @@ export type Authenticated<T> = T & {
role?: Role;
permission?: string;
internal?: boolean;
+ requiresOwnership?: boolean;
};
export type AuthenticatedRouteGroup = {
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index f914029961..b4037efd1e 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -341,6 +341,7 @@ export const path = {
company: `${x}/settings/company`,
companySwitch: (companyId: string) =>
generatePath(`${x}/settings/company/switch/${companyId}`),
+ settingsPayment: `${x}/settings/payment`,
configurationParameter: (itemId: string) =>
generatePath(`${x}/part/${itemId}/parameter`),
configurationParameterGroup: (itemId: string) =>
diff --git a/packages/auth/src/services/users.server.ts b/packages/auth/src/services/users.server.ts
index 698a72bb20..c71a593716 100644
--- a/packages/auth/src/services/users.server.ts
+++ b/packages/auth/src/services/users.server.ts
@@ -1,5 +1,6 @@
import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
+import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getCarbonServiceRole } from "../lib/supabase";
import type { Permission, Result } from "../types";
@@ -202,6 +203,8 @@ export async function deactivateUser(
.eq("companyId", companyId)
.single();
+ let result: Result;
+
if (userToCompany.error) {
// maybe they are invited but not added to the company yet
const user = await serviceRole
@@ -224,25 +227,32 @@ export async function deactivateUser(
}
if (invite.data?.role === "customer") {
- return deactivateCustomer(serviceRole, userId, companyId);
+ result = await deactivateCustomer(serviceRole, userId, companyId);
} else if (invite.data?.role === "employee") {
- return deactivateEmployee(serviceRole, userId, companyId);
+ result = await deactivateEmployee(serviceRole, userId, companyId);
} else if (invite.data?.role === "supplier") {
- return deactivateSupplier(serviceRole, userId, companyId);
+ result = await deactivateSupplier(serviceRole, userId, companyId);
+ } else {
+ throw new Error("Invalid user role");
+ }
+ } else {
+ if (userToCompany.data?.role === "customer") {
+ result = await deactivateCustomer(serviceRole, userId, companyId);
+ } else if (userToCompany.data?.role === "employee") {
+ result = await deactivateEmployee(serviceRole, userId, companyId);
+ } else if (userToCompany.data?.role === "supplier") {
+ result = await deactivateSupplier(serviceRole, userId, companyId);
} else {
throw new Error("Invalid user role");
}
}
- if (userToCompany.data?.role === "customer") {
- return deactivateCustomer(serviceRole, userId, companyId);
- } else if (userToCompany.data?.role === "employee") {
- return deactivateEmployee(serviceRole, userId, companyId);
- } else if (userToCompany.data?.role === "supplier") {
- return deactivateSupplier(serviceRole, userId, companyId);
- } else {
- throw new Error("Invalid user role");
+ // Update Stripe subscription quantity after successful deactivation
+ if (result && result.success) {
+ await updateSubscriptionQuantityForCompany(companyId);
}
+
+ return result;
}
export async function deactivateSupplier(
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 99f19e26b2..f789abe605 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -13653,6 +13653,12 @@ export default {
{
$ref: "#/parameters/rowFilter.companies.logoLight",
},
+ {
+ $ref: "#/parameters/rowFilter.companies.slackChannel",
+ },
+ {
+ $ref: "#/parameters/rowFilter.companies.ownerId",
+ },
{
$ref: "#/parameters/rowFilter.companies.userId",
},
@@ -63949,6 +63955,14 @@ export default {
format: "text",
type: "string",
},
+ slackChannel: {
+ format: "text",
+ type: "string",
+ },
+ ownerId: {
+ format: "text",
+ type: "string",
+ },
userId: {
description:
"Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -72850,7 +72864,7 @@ export default {
type: "string",
},
stripeSubscriptionStatus: {
- default: "active",
+ default: "Active",
format: "text",
type: "string",
},
@@ -89541,6 +89555,18 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.companies.slackChannel": {
+ name: "slackChannel",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.companies.ownerId": {
+ name: "ownerId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.companies.userId": {
name: "userId",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 4829f3acd6..c8aae26e89 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -35063,9 +35063,11 @@ export type Database = {
logoLight: string | null
logoLightIcon: string | null
name: string | null
+ ownerId: string | null
phone: string | null
postalCode: string | null
role: Database["public"]["Enums"]["role"] | null
+ slackChannel: string | null
stateProvince: string | null
taxId: string | null
updatedBy: string | null
@@ -38509,14 +38511,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -39854,14 +39856,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 4829f3acd6..c8aae26e89 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -35063,9 +35063,11 @@ export type Database = {
logoLight: string | null
logoLightIcon: string | null
name: string | null
+ ownerId: string | null
phone: string | null
postalCode: string | null
role: Database["public"]["Enums"]["role"] | null
+ slackChannel: string | null
stateProvince: string | null
taxId: string | null
updatedBy: string | null
@@ -38509,14 +38511,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -39854,14 +39856,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/migrations/20250619100940_billing.sql b/packages/database/supabase/migrations/20250619100940_billing.sql
index ebf4e1557c..bfb6eb99f7 100644
--- a/packages/database/supabase/migrations/20250619100940_billing.sql
+++ b/packages/database/supabase/migrations/20250619100940_billing.sql
@@ -3,6 +3,20 @@ ALTER TABLE "user" ALTER COLUMN "firstName" SET DEFAULT '';
ALTER TABLE "user" ALTER COLUMN "lastName" SET DEFAULT '';
ALTER TABLE "user" ADD COLUMN "acknowledgedUniversity" BOOLEAN NOT NULL DEFAULT FALSE;
+DROP VIEW IF EXISTS "companies";
+CREATE OR REPLACE VIEW "companies" WITH(SECURITY_INVOKER=true) AS
+ SELECT DISTINCT
+ c.*,
+ uc.*,
+ et.name AS "employeeType"
+ FROM "userToCompany" uc
+ INNER JOIN "company" c
+ ON c.id = uc."companyId"
+ LEFT JOIN "employee" e
+ ON e.id = uc."userId" AND e."companyId" = uc."companyId"
+ LEFT JOIN "employeeType" et
+ ON et.id = e."employeeTypeId";
+
ALTER POLICY "Users can view other users from their same company" ON "user" USING (
id = auth.uid()::text OR
"id" IN (
@@ -95,7 +109,7 @@ CREATE TABLE "companyPlan" (
"subscriptionStartDate" TIMESTAMP WITH TIME ZONE NOT NULL,
"stripeCustomerId" TEXT,
"stripeSubscriptionId" TEXT,
- "stripeSubscriptionStatus" TEXT NOT NULL DEFAULT 'active',
+ "stripeSubscriptionStatus" TEXT NOT NULL DEFAULT 'Active',
"trialPeriodEndsAt" TIMESTAMP WITH TIME ZONE,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
diff --git a/packages/documents/src/email/components/Logo.tsx b/packages/documents/src/email/components/Logo.tsx
index b08da06ba3..5d7d4fc17a 100644
--- a/packages/documents/src/email/components/Logo.tsx
+++ b/packages/documents/src/email/components/Logo.tsx
@@ -8,7 +8,7 @@ export function Logo() {
width="auto"
height="45"
alt="Carbon"
- className="my-0 mx-auto block"
+ className="mb-4 mx-auto block"
/>
</Section>
);
diff --git a/packages/stripe/src/stripe.server.ts b/packages/stripe/src/stripe.server.ts
index f2bbc683eb..8422253224 100644
--- a/packages/stripe/src/stripe.server.ts
+++ b/packages/stripe/src/stripe.server.ts
@@ -219,7 +219,7 @@ export async function getBillingPortalRedirectUrl({
const portalSession = await stripe.billingPortal.sessions.create({
customer: customerId,
- return_url: `${getAppUrl()}/settings`,
+ return_url: `${getAppUrl()}/x/settings/company`,
});
if (!portalSession.url) {
@@ -234,10 +234,9 @@ async function upsertCompanyPlan(
companyPlan: {
companyId: string;
priceId: string;
- status?: "active" | "inactive";
+ status?: "Active" | "Inactive" | "Canceled";
stripeCustomerId?: string;
stripeSubscriptionId?: string;
- stripeSubscriptionStatus?: string;
subscriptionStartDate?: string;
}
) {
@@ -256,7 +255,7 @@ async function upsertCompanyPlan(
usersLimit: 10, // Default value as defined in the migration
subscriptionStartDate:
companyPlan.subscriptionStartDate || new Date().toISOString(),
- stripeSubscriptionStatus: companyPlan.stripeSubscriptionStatus,
+ stripeSubscriptionStatus: companyPlan.status,
stripeCustomerId: companyPlan.stripeCustomerId,
stripeSubscriptionId: companyPlan.stripeSubscriptionId,
};
@@ -327,8 +326,45 @@ export async function processStripeEvent({
console.error("Error processing webhook:", error);
throw new Error("Stripe webhook handler failed");
}
- } else {
- console.log("unhandled event", { eventType });
+ } else if (eventType === "customer.subscription.updated") {
+ const data = event.data.object as Stripe.Subscription;
+ const { customer } = data;
+
+ if (typeof customer !== "string") {
+ throw new Error("Stripe webhook handler failed");
+ }
+
+ console.log("customer.subscription.updated", customer);
+
+ try {
+ await syncStripeDataToKV(customer);
+ } catch (error) {
+ console.error("Error processing webhook:", error);
+ throw new Error("Stripe webhook handler failed");
+ }
+ } else if (eventType === "customer.subscription.deleted") {
+ const data = event.data.object as Stripe.Subscription;
+ const { customer } = data;
+
+ if (typeof customer !== "string") {
+ throw new Error("Stripe webhook handler failed");
+ }
+
+ try {
+ const serviceRole = await getCarbonServiceRole();
+ const key = `stripe:customer:${customer}`;
+
+ await Promise.all([
+ redis.del(key),
+ serviceRole
+ .from("companyPlan")
+ .delete()
+ .eq("stripeCustomerId", customer),
+ ]);
+ } catch (error) {
+ console.error("Error processing webhook:", error);
+ throw new Error("Stripe webhook handler failed");
+ }
}
}
@@ -392,9 +428,11 @@ export async function syncStripeDataToKV(
const companyPlanData = {
companyId,
priceId: subData.priceId,
- status: ["active", "trialing"].includes(subData.status)
- ? ("active" as const)
- : ("inactive" as const),
+ status: (subData.cancelAtPeriodEnd
+ ? "Canceled"
+ : ["active", "trialing"].includes(subData.status)
+ ? "Active"
+ : "Inactive") as "Active" | "Inactive" | "Canceled",
stripeCustomerId: customerId,
stripeSubscriptionId: subData.subscriptionId,
stripeSubscriptionStatus: subData.status,
@@ -403,7 +441,7 @@ export async function syncStripeDataToKV(
).toISOString(),
};
- const [_, companyPlan] = await Promise.all([
+ const [, companyPlan] = await Promise.all([
redis.set(key, subData),
upsertCompanyPlan(await getCarbonServiceRole(), companyPlanData),
]);
@@ -429,3 +467,84 @@ export async function updateActiveUsers({
quantity: activeUsers,
});
}
+
+export async function updateSubscriptionQuantityForCompany(companyId: string) {
+ try {
+ const serviceRole = getCarbonServiceRole();
+
+ // Get company plan with plan details
+ const companyPlanResult = await serviceRole
+ .from("companyPlan")
+ .select(
+ `
+ stripeSubscriptionId,
+ plan!inner(
+ userBasedPricing
+ )
+ `
+ )
+ .eq("id", companyId)
+ .single();
+
+ if (companyPlanResult.error || !companyPlanResult.data) {
+ console.log(`No company plan found for company ${companyId}`);
+ return;
+ }
+
+ const { stripeSubscriptionId, plan } = companyPlanResult.data;
+
+ // Only update if userBasedPricing is true and we have a subscription
+ if (!plan?.userBasedPricing || !stripeSubscriptionId) {
+ return;
+ }
+
+ // Count active users
+ const activeUsersResult = await serviceRole
+ .from("userToCompany")
+ .select("userId", { count: "exact", head: true })
+ .eq("companyId", companyId);
+
+ if (activeUsersResult.error) {
+ console.error(
+ `Failed to count active users for company ${companyId}:`,
+ activeUsersResult.error
+ );
+ return;
+ }
+
+ const activeUserCount = activeUsersResult.count || 0;
+
+ // Get the subscription from Stripe to find the subscription item
+ const subscription = await stripe.subscriptions.retrieve(
+ stripeSubscriptionId
+ );
+
+ if (
+ !subscription ||
+ !subscription.items ||
+ subscription.items.data.length === 0
+ ) {
+ console.error(
+ `No subscription items found for subscription ${stripeSubscriptionId}`
+ );
+ return;
+ }
+
+ // Update the quantity on the first subscription item
+ const subscriptionItemId = subscription.items.data[0].id;
+
+ await stripe.subscriptionItems.update(subscriptionItemId, {
+ quantity: activeUserCount,
+ });
+
+ console.log(
+ `Updated Stripe subscription ${stripeSubscriptionId} quantity to ${activeUserCount} for company ${companyId}`
+ );
+ } catch (error) {
+ // Log error but don't throw - we don't want to block user operations
+ console.error(
+ `Failed to update Stripe subscription quantity for company ${companyId}:`,
+ error
+ );
+ }
+}