Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support auto reply handling #1663

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 56 additions & 12 deletions __test__/testbed-preparation/core.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import type {
Assignment,
Campaign,
CampaignContact,
InteractionStep,
Message,
Organization,
User
} from "@spoke/spoke-codegen";
import faker from "faker";
import AuthHasher from "passport-local-authenticate";
import type { PoolClient } from "pg";

import type { Assignment } from "../../src/api/assignment";
import type { Campaign } from "../../src/api/campaign";
import type { CampaignContact } from "../../src/api/campaign-contact";
import type { InteractionStep } from "../../src/api/interaction-step";
import type { Message } from "../../src/api/message";
import type { Organization } from "../../src/api/organization";
import { UserRoleType } from "../../src/api/organization-membership";
import type { User } from "../../src/api/user";
import { DateTime } from "../../src/lib/datetime";
import type {
AssignmentRecord,
AutoReplyTriggerRecord,
CampaignContactRecord,
CampaignRecord,
InteractionStepRecord,
Expand Down Expand Up @@ -388,7 +391,7 @@ export const createMessage = async (
.then(({ rows: [message] }) => message);

export interface CreateCompleteCampaignOptions {
organization?: CreateOrganizationOptions;
organization?: CreateOrganizationOptions & { id: number };
campaign?: Omit<CreateCampaignOptions, "organizationId">;
texters?: number | CreateTexterOptions[];
contacts?: number | Omit<CreateCampaignContactOptions, "campaignId">[];
Expand All @@ -398,10 +401,10 @@ export const createCompleteCampaign = async (
client: PoolClient,
options: CreateCompleteCampaignOptions
) => {
const organization = await createOrganization(
client,
options.organization ?? {}
);
const optOrg = options.organization;
const organization = optOrg?.id
? { id: optOrg?.id }
: await createOrganization(client, options.organization ?? {});

const campaign = await createCampaign(client, {
...(options.campaign ?? {}),
Expand Down Expand Up @@ -524,3 +527,44 @@ export const createQuestionResponse = async (
[options.value, options.campaignContactId, options.interactionStepId]
)
.then(({ rows: [questionResponse] }) => questionResponse);

export type CreateAutoReplyTriggerOptions = {
token: string;
interactionStepId: number;
};

export const createAutoReplyTrigger = async (
client: PoolClient,
options: CreateAutoReplyTriggerOptions
) =>
client
.query<AutoReplyTriggerRecord>(
`
insert into public.auto_reply_trigger (token, interaction_step_id)
values ($1, $2)
returning *
`,
[options.token, options.interactionStepId]
)
.then(({ rows: [trigger] }) => trigger);

export const assignContacts = async (
client: PoolClient,
assignmentId: number,
campaignId: number,
count: number
) => {
await client.query(
`
update campaign_contact
set assignment_id = $1
where id in (
select id from campaign_contact
where campaign_id = $2
and assignment_id is null
limit $3
)
`,
[assignmentId, campaignId, count]
);
};
2 changes: 2 additions & 0 deletions libs/gql-schema/campaign-contact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ export const schema = `
messageStatus: String!
assignmentId: String
updatedAt: Date!
autoReplyEligible: Boolean!

tags: [CampaignContactTag!]!
}

Expand Down
2 changes: 2 additions & 0 deletions libs/gql-schema/interaction-step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const schema = `
scriptOptions: [String]!
answerOption: String
parentInteractionId: String
autoReplyTokens: [String]
isDeleted: Boolean
answerActions: String
questionResponse(campaignContactId: String): QuestionResponse
Expand All @@ -18,6 +19,7 @@ export const schema = `
scriptOptions: [String]!
answerOption: String
answerActions: String
autoReplyTokens: [String]
parentInteractionId: String
isDeleted: Boolean
createdAt: Date
Expand Down
1 change: 1 addition & 0 deletions libs/gql-schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,7 @@ const rootSchema = `
bulkOptOut(organizationId: String!, csvFile: Upload, numbersList: String): Int!
bulkOptIn(organizationId: String!, csvFile: Upload, numbersList: String): Int!
exportOptOuts(organizationId: String!, campaignIds: [String!]): Boolean!
markForManualReply(campaignContactId: String!): CampaignContact!
}

schema {
Expand Down
7 changes: 7 additions & 0 deletions libs/spoke-codegen/src/graphql/message-sending.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,10 @@ mutation SendMessage($message: MessageInput!, $campaignContactId: String!) {
}
}
}

mutation MarkForManualReply($campaignContactId: String!) {
markForManualReply(campaignContactId: $campaignContactId) {
id
autoReplyEligible
}
}
73 changes: 73 additions & 0 deletions migrations/20230806003928_support-auto-replies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = function up(knex) {
return knex.schema
.createTable("auto_reply_trigger", (table) => {
table.increments("id");
table.text("token").notNullable();
table.integer("interaction_step_id").notNullable();
table.foreign("interaction_step_id").references("interaction_step.id");
table.timestamp("created_at").notNull().defaultTo(knex.fn.now());
table.timestamp("updated_at").notNull().defaultTo(knex.fn.now());
table.unique(["interaction_step_id", "token"]);
})
.raw(
`
create or replace function auto_reply_trigger_before_insert() returns trigger as $$
begin
if exists(
select 1 from auto_reply_trigger
where token = NEW.token
and interaction_step_id in (
select id from interaction_step child_steps
where parent_interaction_id = (
select parent_interaction_id from interaction_step
where id = NEW.interaction_step_id
)
)
and interaction_step_id <> NEW.id
) then
raise exception 'Each interaction step can only have 1 child step assigned to any particular auto reply token';
end if;

return NEW;
end;
$$ language plpgsql;

create trigger _500_auto_reply_trigger_insert
before insert
on auto_reply_trigger
for each row
execute procedure auto_reply_trigger_before_insert();

create trigger _500_auto_reply_trigger_updated_at
before update
on public.auto_reply_trigger
for each row
execute procedure universal_updated_at();
`
)
.alterTable("campaign_contact", (table) => {
table.boolean("auto_reply_eligible").notNullable().defaultTo(false);
})
.alterTable("campaign_contact", (table) => {
table
.boolean("auto_reply_eligible")
.notNullable()
.defaultTo(true)
.alter();
});
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = function down(knex) {
return knex.schema
.dropTable("auto_reply_trigger")
.alterTable("campaign_contact", (table) => {
table.dropColumn("auto_reply_eligible");
});
};
Loading