@avakado.ai/schemas 1.1.27 → 1.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/enums.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  // Generated by scripts/emit-types.mjs. Run `npm run types` after a schema change.
2
2
 
3
- export { CAMPAIGN_STATUS, CONVERSATION_PRIORITY, CONVERSATION_STATUS, CURRENT_SUBSCRIPTION_STATUSES, LEDGER_CATEGORY, LEDGER_DIRECTIONS, LEDGER_SOURCE_TYPES, LEDGER_STATUSES, OAUTH_GRANT_MODES, PAYMENT_STATUS, PENDING_CHANGE_TYPES, SUBSCRIPTION_STATUS, TASK_REFERENCE_TYPES, TASK_STATUS, TASK_TYPES } from "./types.js";
3
+ export { CAMPAIGN_STATUS, CONVERSATION_PRIORITY, CONVERSATION_STATUS, CURRENT_SUBSCRIPTION_STATUSES, EXOTEL_WEBHOOK_EVENTS, INSTAGRAM_WEBHOOK_EVENTS, LEDGER_CATEGORY, LEDGER_DIRECTIONS, LEDGER_SOURCE_TYPES, LEDGER_STATUSES, OAUTH_GRANT_MODES, PAYMENT_STATUS, PENDING_CHANGE_TYPES, SUBSCRIPTION_STATUS, TASK_REFERENCE_TYPES, TASK_STATUS, TASK_TYPES, TELEGRAM_WEBHOOK_EVENTS, WEBHOOK_TRIGGERS, WHATSAPP_CALL_EVENTS, WHATSAPP_CALL_STATUSES, WHATSAPP_MESSAGE_STATUSES, WORKFLOW_TRIGGERS } from "./types.js";
package/models.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  // Generated by scripts/emit-types.mjs. Run `npm run types` after a schema change.
2
2
 
3
- export { Action, AgentModel, AmountSchema, Api, ApiAuthenticationSchema, ApiAuthenticators, BillingLog, Business, BusinessSchema, CallSession, Campaign, CampaignSchema, Channel, ChannelCapabilityDefaults, Collection, Conversation, ConversationSchema, Data, DemonstrationModel, Lead, LeadTemplate, Log, Message, MessageSession, Notification, OAuthAuthorizationCode, OAuthClient, OAuthRefreshToken, OAuthRevokedJti, Payment, PaymentSchema, Plan, Providers, RoleScopes, ScopesEnum, Subscription, SubscriptionSchema, Task, TaskSchema, Template, Ticket, TriggerTemplate, UsageLog, UsageLogSchema, User, Workflow, WorkflowLogs } from "./types.js";
3
+ export { Action, AgentModel, AmountSchema, Api, ApiAuthenticationSchema, ApiAuthenticators, BillingLog, Business, BusinessSchema, CallSession, Campaign, CampaignSchema, Channel, ChannelCapabilityDefaults, Collection, Conversation, ConversationSchema, CronJob, Data, DemonstrationModel, Lead, LeadTemplate, Log, Message, MessageSession, Notification, OAuthAuthorizationCode, OAuthClient, OAuthRefreshToken, OAuthRevokedJti, Payment, PaymentSchema, Plan, Providers, RoleScopes, ScopesEnum, Subscription, SubscriptionSchema, Task, TaskSchema, Template, Ticket, TriggerTemplate, UsageLog, UsageLogSchema, User, Workflow, WorkflowLogs } from "./types.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avakado.ai/schemas",
3
- "version": "1.1.27",
3
+ "version": "1.1.29",
4
4
  "description": "Canonical Mongo schemas, models, enums and index declarations shared by the Avakado services.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -7,7 +7,34 @@ export const LEAD_STATUS = ["new", "contacted", "qualified", "converted", "lost"
7
7
  export const CONVERSATION_STATUS = ["open", "pending", "snoozed", "completed", "closed", "archived", "spam"];
8
8
  export const CAMPAIGN_STATUS = ["pending", "active", "completed", "failed", "partial"];
9
9
  export const TASK_STATUS = ["pending", "in-progress", "completed", "failed", "skipped"];
10
- export const WORKFLOW_TRIGGERS = [...LEAD_STATUS.map(status => `lead_${status}`), ...CONVERSATION_STATUS.map(status => `conversation_${status}`), ...CAMPAIGN_STATUS.map(status => `campaign_${status}`), ...TASK_STATUS.map(status => `task_${status}`)];
10
+
11
+ // Webhook events the channel adapters publish. Names are `{channel}_{event}`.
12
+ // Descriptions and sample payloads live on TriggerTemplate documents, not here.
13
+ export const WHATSAPP_MESSAGE_STATUSES = ["sent", "delivered", "read", "played", "failed", "deleted"];
14
+ export const WHATSAPP_CALL_EVENTS = ["connect", "terminate", "recording"];
15
+ export const WHATSAPP_CALL_STATUSES = ["ringing", "accepted", "rejected", "completed", "failed"];
16
+ export const INSTAGRAM_WEBHOOK_EVENTS = ["message", "postback", "read", "delivery", "reaction"];
17
+ export const TELEGRAM_WEBHOOK_EVENTS = ["message", "message_edited", "callback"];
18
+ export const EXOTEL_WEBHOOK_EVENTS = ["cancelled", "completed", "busy", "no_answer", "failed"];
19
+
20
+ export const WEBHOOK_TRIGGERS = [
21
+ "whatsapp_message",
22
+ "whatsapp_reaction",
23
+ ...WHATSAPP_MESSAGE_STATUSES.map((status) => `whatsapp_message_${status}`),
24
+ ...WHATSAPP_CALL_EVENTS.map((event) => `whatsapp_call_${event}`),
25
+ ...WHATSAPP_CALL_STATUSES.map((status) => `whatsapp_call_${status}`),
26
+ ...INSTAGRAM_WEBHOOK_EVENTS.map((event) => `instagram_${event}`),
27
+ ...TELEGRAM_WEBHOOK_EVENTS.map((event) => `telegram_${event}`),
28
+ ...EXOTEL_WEBHOOK_EVENTS.map((event) => `exotel_${event}`),
29
+ ];
30
+
31
+ export const WORKFLOW_TRIGGERS = [
32
+ ...LEAD_STATUS.map((status) => `lead_${status}`),
33
+ ...CONVERSATION_STATUS.map((status) => `conversation_${status}`),
34
+ ...CAMPAIGN_STATUS.map((status) => `campaign_${status}`),
35
+ ...TASK_STATUS.map((status) => `task_${status}`),
36
+ ...WEBHOOK_TRIGGERS,
37
+ ];
11
38
  export const CONVERSATION_PRIORITY = ["low", "normal", "high", "urgent"];
12
39
  export const SUBSCRIPTION_STATUS = [
13
40
  "created",
package/src/index.js CHANGED
@@ -3,6 +3,7 @@ export * from "./models/index.js";
3
3
  export * from "./enums/index.js";
4
4
  export * from "./media.js";
5
5
  export { configureSchemas, defineModel, getSchemaConfig } from "./runtime.js";
6
+ export { publishWorkflowTrigger, WORKFLOW_TRIGGER_TOPIC } from "./statusTrigger.js";
6
7
  export {
7
8
  CHAT_SESSION_MS,
8
9
  WHATSAPP_CALL_CALLBACK_MS,
@@ -0,0 +1,26 @@
1
+ import { Schema } from "mongoose";
2
+ import { defineModel } from "../runtime.js";
3
+
4
+ const CronJobSchema = new Schema({
5
+ _id: { type: String },
6
+ name: { type: String, required: true },
7
+ scheduleType: { type: String, enum: ["cron", "once"], default: "once" },
8
+ schedule: String,
9
+ runAt: Date,
10
+ type: { type: String, enum: ["shell", "http"], required: true },
11
+ command: String,
12
+ url: String,
13
+ method: { type: String, default: "GET" },
14
+ headers: String,
15
+ params: String,
16
+ body: String,
17
+ enabled: { type: Boolean, default: true },
18
+ lastRun: Date,
19
+ lastStatus: String,
20
+ miscIds: { type: Schema.Types.Mixed, default: () => ({}) },
21
+ createdAt: { type: Date, default: Date.now },
22
+ });
23
+
24
+ CronJobSchema.index({ scheduleType: 1, enabled: 1, runAt: 1 });
25
+
26
+ export const CronJob = defineModel("CronJob", CronJobSchema, "CronJobs");
@@ -9,6 +9,7 @@ export { User, ScopesEnum, RoleScopes } from "./User.js";
9
9
  export { AgentModel } from "./Agent.js";
10
10
  export { Channel, ChannelCapabilityDefaults } from "./Channels.js";
11
11
  export { CallSession } from "./CallSessions.js";
12
+ export { CronJob } from "./CronJob.js";
12
13
  export { Plan } from "./Plans.js";
13
14
  export { Api, Providers } from "./ExternalServiceProviders.js";
14
15
  export { Template } from "./market.js";
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { CAMPAIGN_STATUS, CONVERSATION_STATUS, LEAD_STATUS, TASK_STATUS } from "./enums/index.js";
2
+ import { CAMPAIGN_STATUS, CONVERSATION_STATUS, LEAD_STATUS, TASK_STATUS, WORKFLOW_TRIGGERS } from "./enums/index.js";
3
3
  import { Workflow } from "./models/Workflow.js";
4
4
  import { requireDep } from "./runtime.js";
5
5
 
@@ -130,23 +130,55 @@ async function messagesForActiveWorkflows(messages) {
130
130
  return publishable;
131
131
  }
132
132
 
133
- async function publishStatusChanges(changes) {
134
- const messages = await messagesForActiveWorkflows(changes.map(statusTriggerMessage).filter(Boolean));
135
- if (!messages.length) return;
136
- const sendKafkaMessage = requireDep("sendKafkaMessage", "workflow status trigger");
137
- for (let i = 0; i < messages.length; i += BATCH_SIZE) {
138
- const batch = messages.slice(i, i + BATCH_SIZE);
133
+ async function publishTriggerMessages(messages) {
134
+ const publishable = await messagesForActiveWorkflows(messages);
135
+ if (!publishable.length) return;
136
+ const sendKafkaMessage = requireDep("sendKafkaMessage", "workflow trigger");
137
+ for (let i = 0; i < publishable.length; i += BATCH_SIZE) {
138
+ const batch = publishable.slice(i, i + BATCH_SIZE);
139
139
  try {
140
140
  await sendKafkaMessage({ topic: WORKFLOW_TRIGGER_TOPIC, messages: batch, acks: -1 });
141
141
  } catch (error) {
142
142
  console.error(
143
- `@avakado.ai/schemas: failed to publish ${batch.length} workflow status trigger(s) on ${WORKFLOW_TRIGGER_TOPIC}`,
143
+ `@avakado.ai/schemas: failed to publish ${batch.length} workflow trigger(s) on ${WORKFLOW_TRIGGER_TOPIC}`,
144
144
  error?.message || error
145
145
  );
146
146
  }
147
147
  }
148
148
  }
149
149
 
150
+ async function publishStatusChanges(changes) {
151
+ await publishTriggerMessages(changes.map(statusTriggerMessage).filter(Boolean));
152
+ }
153
+
154
+ export async function publishWorkflowTrigger({ trigger, businessId, payload = {}, entity } = {}) {
155
+ if (typeof trigger !== "string" || !WORKFLOW_TRIGGERS.includes(trigger)) return;
156
+ const resolvedBusinessId = businessId == null || businessId === "" ? "" : String(businessId?._id ?? businessId);
157
+ if (!resolvedBusinessId) return;
158
+ let bodyPayload = {};
159
+ try {
160
+ bodyPayload = JSON.parse(JSON.stringify(payload ?? {}));
161
+ } catch {
162
+ bodyPayload = {};
163
+ }
164
+ const eventId = randomUUID();
165
+ await publishTriggerMessages([{
166
+ key: resolvedBusinessId,
167
+ value: JSON.stringify({
168
+ eventId,
169
+ businessId: resolvedBusinessId,
170
+ trigger,
171
+ payload: bodyPayload,
172
+ }),
173
+ headers: {
174
+ eventId,
175
+ businessId: resolvedBusinessId,
176
+ trigger,
177
+ entity: entity || trigger.split("_")[0],
178
+ },
179
+ }]);
180
+ }
181
+
150
182
  function writeApplied(result) {
151
183
  if (result == null || typeof result !== "object") return false;
152
184
  if ("matchedCount" in result || "modifiedCount" in result || "upsertedCount" in result) {
@@ -0,0 +1,3 @@
1
+ // Generated by scripts/emit-types.mjs. Run `npm run types` after a schema change.
2
+
3
+ export { CronJob } from "../../types.js";
package/types.d.ts CHANGED
@@ -235,6 +235,25 @@ export interface ConversationMethods {
235
235
  updateStatus(status?: any): Promise<any>;
236
236
  }
237
237
 
238
+ export interface CronJob {
239
+ _id: string;
240
+ name: string;
241
+ scheduleType?: "cron" | "once";
242
+ schedule?: string;
243
+ runAt?: Date;
244
+ type: "shell" | "http";
245
+ command?: string;
246
+ url?: string;
247
+ method?: string;
248
+ headers?: string;
249
+ params?: string;
250
+ body?: string;
251
+ enabled?: boolean;
252
+ lastRun?: Date;
253
+ lastStatus?: string;
254
+ miscIds?: any;
255
+ createdAt?: Date;
256
+ }
238
257
 
239
258
  export interface DemonstrationModel {
240
259
  transcripts?: any;
@@ -659,6 +678,8 @@ export const Collection: Model<Collection, {}, {}> & CollectionStatics;
659
678
 
660
679
  export const Conversation: Model<Conversation, {}, ConversationMethods>;
661
680
 
681
+ export const CronJob: Model<CronJob, {}, {}>;
682
+
662
683
  export const DemonstrationModel: Model<DemonstrationModel, {}, {}>;
663
684
 
664
685
  export const Lead: Model<Lead, {}, {}>;
@@ -741,3 +762,23 @@ export const TASK_STATUS: readonly ["pending", "in-progress", "completed", "fail
741
762
 
742
763
  export const TASK_TYPES: readonly ["quick", "webhook"];
743
764
 
765
+ export const WHATSAPP_MESSAGE_STATUSES: readonly ["sent", "delivered", "read", "played", "failed", "deleted"];
766
+
767
+ export const WHATSAPP_CALL_EVENTS: readonly ["connect", "terminate", "recording"];
768
+
769
+ export const WHATSAPP_CALL_STATUSES: readonly ["ringing", "accepted", "rejected", "completed", "failed"];
770
+
771
+ export const INSTAGRAM_WEBHOOK_EVENTS: readonly ["message", "postback", "read", "delivery", "reaction"];
772
+
773
+ export const TELEGRAM_WEBHOOK_EVENTS: readonly ["message", "message_edited", "callback"];
774
+
775
+ export const EXOTEL_WEBHOOK_EVENTS: readonly ["cancelled", "completed", "busy", "no_answer", "failed"];
776
+
777
+ export const WEBHOOK_TRIGGERS: readonly string[];
778
+
779
+ export const WORKFLOW_TRIGGERS: readonly string[];
780
+
781
+ export const WORKFLOW_TRIGGER_TOPIC: "workflow-execution-trigger";
782
+
783
+ export function publishWorkflowTrigger(params?: { trigger?: string; businessId?: any; payload?: any; entity?: string }): Promise<void>;
784
+