saleor-apps-redis_apl/apps/crm/src/modules/mailchimp/mailchimp-audience.router.ts

101 lines
2.8 KiB
TypeScript
Raw Normal View History

Introduce CRM App (#292) * Add template Cleanup Update queries Basic mailchimp client Add Oauth flow remove next auth * Auth flow, mailchimp button * Basic layouts * session saver for appbridge * ideas drop * basic iframe flow * iframe flow - with post message * saving token in backend * saving token in backend * Extracted settings manager * Refactor audience router * Remove old macaw ui * Nav and layout * display lists and wip add customer * Metadata updater * Allow iframe to NOT have app layout * Add segment coming soon * App layout * Add removing config button * Add iframe * Fix postmessages * Display lists * webhook settings * Connect webhook * remove comment * batch customer adding client * Update macaw * Fetching customers component * Add bulk sync * add temp ts-ignore until macaw is fixed * Improve ui * redesign * Extract sections * Redesign mailchimp login * Refactor sections * Extract mailchimp list picker * Add name mapping * WIP tags, extracted colocated queries to folders * Wip - not working CustomerUpdated subs * Add instructions * Fix webhook config state * Add external links * envs * Protected Oauth handler * Fix instructions * Squash some todos * Instructions update with gql * empty trygger * Add env validation * Fix error message * Update macaw and remove todos * Add metadata manager test * Replace Mailchimp enum to lowercase * Update oauth routes * Fix typo * Add loader to removing config box * Update labeler to include CRM app * Apply suggestions from CR * Fix linter
2023-04-06 07:26:56 +00:00
import { router } from "../trpc/trpc-server";
import { protectedClientProcedure } from "../trpc/protected-client-procedure";
Introduce CRM App (#292) * Add template Cleanup Update queries Basic mailchimp client Add Oauth flow remove next auth * Auth flow, mailchimp button * Basic layouts * session saver for appbridge * ideas drop * basic iframe flow * iframe flow - with post message * saving token in backend * saving token in backend * Extracted settings manager * Refactor audience router * Remove old macaw ui * Nav and layout * display lists and wip add customer * Metadata updater * Allow iframe to NOT have app layout * Add segment coming soon * App layout * Add removing config button * Add iframe * Fix postmessages * Display lists * webhook settings * Connect webhook * remove comment * batch customer adding client * Update macaw * Fetching customers component * Add bulk sync * add temp ts-ignore until macaw is fixed * Improve ui * redesign * Extract sections * Redesign mailchimp login * Refactor sections * Extract mailchimp list picker * Add name mapping * WIP tags, extracted colocated queries to folders * Wip - not working CustomerUpdated subs * Add instructions * Fix webhook config state * Add external links * envs * Protected Oauth handler * Fix instructions * Squash some todos * Instructions update with gql * empty trygger * Add env validation * Fix error message * Update macaw and remove todos * Add metadata manager test * Replace Mailchimp enum to lowercase * Update oauth routes * Fix typo * Add loader to removing config box * Update labeler to include CRM app * Apply suggestions from CR * Fix linter
2023-04-06 07:26:56 +00:00
import { MailchimpClientOAuth } from "./mailchimp-client";
import { MailchimpConfigSettingsManager } from "./mailchimp-config-settings-manager";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { createLogger } from "@saleor/apps-shared";
Introduce CRM App (#292) * Add template Cleanup Update queries Basic mailchimp client Add Oauth flow remove next auth * Auth flow, mailchimp button * Basic layouts * session saver for appbridge * ideas drop * basic iframe flow * iframe flow - with post message * saving token in backend * saving token in backend * Extracted settings manager * Refactor audience router * Remove old macaw ui * Nav and layout * display lists and wip add customer * Metadata updater * Allow iframe to NOT have app layout * Add segment coming soon * App layout * Add removing config button * Add iframe * Fix postmessages * Display lists * webhook settings * Connect webhook * remove comment * batch customer adding client * Update macaw * Fetching customers component * Add bulk sync * add temp ts-ignore until macaw is fixed * Improve ui * redesign * Extract sections * Redesign mailchimp login * Refactor sections * Extract mailchimp list picker * Add name mapping * WIP tags, extracted colocated queries to folders * Wip - not working CustomerUpdated subs * Add instructions * Fix webhook config state * Add external links * envs * Protected Oauth handler * Fix instructions * Squash some todos * Instructions update with gql * empty trygger * Add env validation * Fix error message * Update macaw and remove todos * Add metadata manager test * Replace Mailchimp enum to lowercase * Update oauth routes * Fix typo * Add loader to removing config box * Update labeler to include CRM app * Apply suggestions from CR * Fix linter
2023-04-06 07:26:56 +00:00
const AddContactSchema = z.object({
listId: z.string().min(1),
contact: z.object({
email: z.string().email().min(2),
}),
});
const BulkAddContactsSchema = z.object({
contacts: z.array(
z.object({
email: z.string().email().min(2),
firstName: z.string().optional(),
lastName: z.string().optional(),
tags: z.array(z.string()).optional(),
})
),
listId: z.string().min(1),
});
const mailchimpAudienceRouter = router({
getLists: protectedClientProcedure.query(async ({ ctx }) => {
const config = await new MailchimpConfigSettingsManager(ctx.apiClient).getConfig();
/**
* TODO extract mailchimp API readiness shared class
*/
if (!config) {
throw new TRPCError({
code: "FORBIDDEN",
cause: "MAILCHIMP_CONFIG_NOT_FOUND",
message: "Couldnt restore saved Mailchimp config",
});
}
const logger = createLogger({
context: "mailchimpConfigRouter",
saleorApiUrl: ctx.saleorApiUrl,
});
const mailchimpClient = new MailchimpClientOAuth(config.dc, config.token);
const listsResponseOrError = await mailchimpClient.fetchLists();
logger.trace(listsResponseOrError, "Fetched lists");
if ("lists" in listsResponseOrError) {
return listsResponseOrError.lists.map((l) => ({
id: l.id,
name: l.name,
members: l.stats.member_count,
}));
}
throw new Error("Failed fetching lists from Mailchimp");
}),
bulkAddContacts: protectedClientProcedure
.input(BulkAddContactsSchema)
.mutation(async ({ ctx, input }) => {
const logger = createLogger({
context: "mailchimpConfigRouter.bulkAddContacts",
saleorApiUrl: ctx.saleorApiUrl,
});
const config = await new MailchimpConfigSettingsManager(ctx.apiClient).getConfig();
logger.debug("Fetched config from metadata");
if (!config) {
logger.warn("Config not found");
throw new TRPCError({
code: "FORBIDDEN",
cause: "MAILCHIMP_CONFIG_NOT_FOUND",
message: "Couldnt restore saved Mailchimp config",
});
}
const mailchimpClient = new MailchimpClientOAuth(config.dc, config.token);
logger.debug(input, "Will bulk add contacts to Mailchimp");
await mailchimpClient.batchAddContacts(input.listId, input.contacts);
}),
});
export const MailchimpAudienceRouter = {
router: mailchimpAudienceRouter,
input: {
AddContactSchema,
},
};