Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | 82x 4x 4x 1x 3x 2x 2x 1x 1x 2x 2x 3x 3x 4x 4x 2x 2x 2x 2x 3x 3x 3x 2x 3x 3x 3x 3x 1x 3x 3x 3x 2x 3x 3x 3x 3x 2x 1x 1x 1x 4x 4x | import { eq, and, sql, desc, inArray } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../../db/schema";
import type {
WaCampaign,
NewWaCampaign,
WaCampaignRecipient,
NewWaCampaignRecipient,
} from "../../db/schema";
export type WaCampaignFilters = {
status?: string;
};
export class WaCampaignsDal {
constructor(private db: DrizzleD1Database<typeof schema>) {}
async findAll(
filters: WaCampaignFilters = {},
offset = 0,
limit = 50,
): Promise<WaCampaign[]> {
const query = this.db
.select()
.from(schema.waCampaigns)
.orderBy(desc(schema.waCampaigns.dateCreated))
.limit(limit)
.offset(offset);
if (filters.status) {
return query.where(eq(schema.waCampaigns.status, filters.status as WaCampaign["status"]));
}
return query;
}
async findById(id: number): Promise<WaCampaign | undefined> {
const result = await this.db
.select()
.from(schema.waCampaigns)
.where(eq(schema.waCampaigns.id, id))
.limit(1);
return result[0];
}
async create(data: NewWaCampaign): Promise<WaCampaign> {
const result = await this.db
.insert(schema.waCampaigns)
.values(data)
.returning();
return result[0];
}
async update(
id: number,
data: Partial<WaCampaign>,
): Promise<WaCampaign | undefined> {
const result = await this.db
.update(schema.waCampaigns)
.set({ ...data, dateUpdated: new Date() })
.where(eq(schema.waCampaigns.id, id))
.returning();
return result[0];
}
/**
* Atomically transition campaign status.
* Returns true if the row was updated (i.e. it was in expectedStatus).
*/
async atomicStatusTransition(
id: number,
expectedStatus: string,
newStatus: string,
): Promise<boolean> {
const result = await this.db
.update(schema.waCampaigns)
.set({
status: newStatus as WaCampaign["status"],
dateUpdated: new Date(),
})
.where(
and(
eq(schema.waCampaigns.id, id),
eq(
schema.waCampaigns.status,
expectedStatus as WaCampaign["status"],
),
),
)
.returning({ id: schema.waCampaigns.id });
return result.length > 0;
}
async count(filters: WaCampaignFilters = {}): Promise<number> {
const query = this.db
.select({ count: sql<number>`count(*)` })
.from(schema.waCampaigns);
if (filters.status) {
const result = await query.where(
eq(schema.waCampaigns.status, filters.status as WaCampaign["status"]),
);
return result[0]?.count ?? 0;
}
const result = await query;
return result[0]?.count ?? 0;
}
async countByStatus(status: string): Promise<number> {
const result = await this.db
.select({ count: sql<number>`count(*)` })
.from(schema.waCampaigns)
.where(eq(schema.waCampaigns.status, status as WaCampaign["status"]));
return result[0]?.count ?? 0;
}
async addRecipients(
recipients: NewWaCampaignRecipient[],
): Promise<void> {
if (recipients.length === 0) return;
// Insert in batches of 100 to avoid hitting D1 limits
for (let i = 0; i < recipients.length; i += 100) {
const batch = recipients.slice(i, i + 100);
await this.db
.insert(schema.waCampaignRecipients)
.values(batch);
}
}
async getRecipients(
campaignId: number,
filters: { status?: string } = {},
offset = 0,
limit = 50,
): Promise<WaCampaignRecipient[]> {
const conditions = [
eq(schema.waCampaignRecipients.campaignId, campaignId),
];
if (filters.status) {
conditions.push(
eq(schema.waCampaignRecipients.status, filters.status as WaCampaignRecipient["status"]),
);
}
return this.db
.select()
.from(schema.waCampaignRecipients)
.where(and(...conditions))
.limit(limit)
.offset(offset);
}
async getRecipientCount(campaignId: number): Promise<number> {
const result = await this.db
.select({ count: sql<number>`count(*)` })
.from(schema.waCampaignRecipients)
.where(eq(schema.waCampaignRecipients.campaignId, campaignId));
return result[0]?.count ?? 0;
}
async getPendingRecipients(
campaignId: number,
limit: number,
): Promise<WaCampaignRecipient[]> {
return this.db
.select()
.from(schema.waCampaignRecipients)
.where(
and(
eq(schema.waCampaignRecipients.campaignId, campaignId),
eq(schema.waCampaignRecipients.status, "pending"),
),
)
.limit(limit);
}
async updateRecipientStatus(
id: number,
status: string,
wamid?: string,
errorCode?: string,
): Promise<void> {
const updateData: Record<string, unknown> = {
status,
dateUpdated: new Date(),
};
if (wamid) updateData.wamid = wamid;
if (errorCode) updateData.errorCode = errorCode;
await this.db
.update(schema.waCampaignRecipients)
.set(updateData)
.where(eq(schema.waCampaignRecipients.id, id));
}
async updateRecipientStatusBatch(
ids: number[],
status: string,
): Promise<void> {
if (ids.length === 0) return;
await this.db
.update(schema.waCampaignRecipients)
.set({
status: status as WaCampaignRecipient["status"],
dateUpdated: new Date(),
})
.where(inArray(schema.waCampaignRecipients.id, ids));
}
async completeIfDone(campaignId: number): Promise<void> {
await this.db
.update(schema.waCampaigns)
.set({
status: "completed" as WaCampaign["status"],
dateUpdated: new Date(),
})
.where(
and(
eq(schema.waCampaigns.id, campaignId),
eq(schema.waCampaigns.status, "sending" as WaCampaign["status"]),
sql`${schema.waCampaigns.statsSent} + ${schema.waCampaigns.statsFailed} >= ${schema.waCampaigns.statsTotal}`,
),
);
}
async updateRecipientStatusByWamid(
wamid: string,
status: string,
): Promise<void> {
await this.db
.update(schema.waCampaignRecipients)
.set({ status: status as WaCampaignRecipient["status"], dateUpdated: new Date() })
.where(eq(schema.waCampaignRecipients.wamid, wamid));
}
async incrementStat(
campaignId: number,
field:
| "statsSent"
| "statsDelivered"
| "statsRead"
| "statsFailed",
): Promise<void> {
const column = schema.waCampaigns[field];
await this.db
.update(schema.waCampaigns)
.set({
[field]: sql`${column} + 1`,
dateUpdated: new Date(),
})
.where(eq(schema.waCampaigns.id, campaignId));
}
}
|