import Workflow, { UniqueActivity } from "@entity-access/entity-access/dist/workflows/Workflow.js"; import SocialMailContext from "../../../model/SocialMailContext.js"; import Inject from "@entity-access/entity-access/dist/di/di.js"; import EmailAddressService from "../../../services/EmailAddressService.js"; import TagService from "../../../services/tags/TagService.js"; import WebClientService from "../../../services/client/WebClientService.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; export default class CreateChannelWorkflow extends Workflow<{ mailboxID, domainID, authorName: string, authorEmail: string, addSubscribers: string}> { async run() { await this.create(); } @UniqueActivity async create( @Inject db?: SocialMailContext, @Inject eas?: EmailAddressService, @Inject ts?: TagService, @Inject wcs?: WebClientService, ) { const { mailboxID, authorEmail, authorName, domainID } = this.input; let { addSubscribers} = this.input; addSubscribers ??= ""; const folderTagID = await ts.getSystemTagID("Contacts"); const domain = await db.domains.statements.select({}, { domainID }); const emails = [ authorEmail, ... addSubscribers.split(/[\,\;]/g).map((x) => x.trim()).filter((x) => x)]; const domainName = domain.name; const suffix = "@"+ domainName; let firstSenderID = null; for (const email of emails) { let emailAddressID = await eas.getId(email, authorName); if (domain) { // check if user exists already.. const hID = await eas.getHostedMailboxByAddress(email); if (!hID && email.endsWith(suffix)) { // create a mailbox... const mb = db.mailboxes.add({ domainID, mailboxID: emailAddressID }); await db.saveChanges(); emailAddressID = mb.mailboxID; } firstSenderID ??= emailAddressID; } await db.mailboxContacts.statements.insert({ mailboxID, emailAddressID, folderTagID, isOwner: true }); } // send welcome email.... db.verifyFilters = false; let htmlBody = await (await wcs.getUIPackageInfo()) .downloadText("/content/emails/welcome-post/welcome-post.html"); htmlBody = htmlBody.replaceAll("$DOMAIN_NAME$", domainName); const now = DateTime.now; db.emails.add({ senderName: authorName, senderID: firstSenderID, subject: `Welcome to the ${domainName}`, recipients: [ db.emailRecipients.add({ emailAddressID: mailboxID, type: "to" }) ], htmlBody, dateReceived: now, dateCreated: now, dateSent: now, received: true, status: "scheduled" }); await db.saveChanges(); } }