powr-sdk-api 4.18.1 → 4.19.1

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.
@@ -14,7 +14,8 @@ const {
14
14
  const {
15
15
  parseFeedbackCreate,
16
16
  parseFeedbackStatus,
17
- feedbackSummary
17
+ feedbackSummary,
18
+ ringFeedback
18
19
  } = require("../utils/feedback");
19
20
  async function callerIsAdmin(db, req) {
20
21
  var _req$user, _req$user2;
@@ -121,12 +122,14 @@ router.post("/", async (req, res) => {
121
122
  };
122
123
  const db = await getDb();
123
124
  const result = await db.collection("powrFeedback").insertOne(doc);
125
+ const saved = {
126
+ ...doc,
127
+ _id: result.insertedId
128
+ };
129
+ await ringFeedback(db, saved);
124
130
  return res.status(201).json({
125
131
  success: true,
126
- data: feedbackSummary({
127
- ...doc,
128
- _id: result.insertedId
129
- })
132
+ data: feedbackSummary(saved)
130
133
  });
131
134
  } catch (error) {
132
135
  console.error("POST /feedback", error);
@@ -10,6 +10,76 @@ const {
10
10
  const {
11
11
  verifyToken
12
12
  } = require("../middleware/jwtToken");
13
+ const {
14
+ emitActivity
15
+ } = require("../managers/activities");
16
+ function normalizeNotifyUserIds(value) {
17
+ if (!value) return [];
18
+ const raw = Array.isArray(value) ? value : String(value).split(/[,\s]+/);
19
+ return [...new Set(raw.map(id => String(id || "").trim()).filter(Boolean))].slice(0, 100);
20
+ }
21
+ async function resolveFormNotifyUserIds(db, projectId, formDoc, actorId) {
22
+ let userIds = normalizeNotifyUserIds(formDoc && formDoc.notifyUserIds);
23
+ if (userIds.length === 0 && projectId) {
24
+ const profiles = await db.collection("profiles").find({
25
+ projectId: String(projectId),
26
+ access: 100
27
+ }, {
28
+ projection: {
29
+ userId: 1
30
+ }
31
+ }).limit(100).toArray();
32
+ userIds = [...new Set((profiles || []).map(p => p && p.userId != null ? String(p.userId).trim() : "").filter(Boolean))];
33
+ }
34
+ const actor = actorId ? String(actorId).trim() : "";
35
+ const filtered = actor ? userIds.filter(id => id !== actor) : userIds;
36
+ return filtered.length > 0 ? filtered : userIds;
37
+ }
38
+ async function emitFormSubmittedActivity(db, {
39
+ projectId,
40
+ formName,
41
+ studentFormData,
42
+ submittedFormId
43
+ }) {
44
+ if (!projectId || !formName) return null;
45
+ const formDoc = await db.collection("powrForm").findOne({
46
+ formName,
47
+ projectId
48
+ }, {
49
+ projection: {
50
+ formTitle: 1,
51
+ formName: 1,
52
+ notifyUserIds: 1
53
+ }
54
+ });
55
+ const titleText = String(formDoc && formDoc.formTitle || studentFormData && studentFormData.formTitle || formName).trim();
56
+ const actorId = studentFormData && studentFormData.userId ? String(studentFormData.userId).trim() : null;
57
+ const respondent = String(studentFormData && (studentFormData.respondent_name || studentFormData.person_name || studentFormData.name || studentFormData.whatsapp || studentFormData.email) || "Someone").trim();
58
+ const userIds = await resolveFormNotifyUserIds(db, projectId, formDoc, actorId);
59
+ const notify = userIds.length > 0 ? {
60
+ userIds,
61
+ title: `New form response: ${titleText}`.slice(0, 140),
62
+ body: `${respondent} submitted ${titleText}.`.slice(0, 2000),
63
+ link: "/powr-admin",
64
+ projectId: String(projectId)
65
+ } : null;
66
+ return emitActivity({
67
+ projectId: String(projectId),
68
+ action: "form_submitted",
69
+ userId: actorId || null,
70
+ targetType: "form",
71
+ targetId: submittedFormId ? String(submittedFormId) : String(formName),
72
+ metadata: {
73
+ source: "powr-forms",
74
+ formName: String(formName),
75
+ formTitle: titleText,
76
+ respondent
77
+ },
78
+ notify
79
+ }, {
80
+ getDb: async () => db
81
+ });
82
+ }
13
83
  const upload = multer({
14
84
  storage: multer.memoryStorage(),
15
85
  fileFilter: function (req, file, cb) {
@@ -116,6 +186,14 @@ router.post('/studentform', async (req, res) => {
116
186
  submittedAt: new Date()
117
187
  };
118
188
  const formResult = await studentsFormCollection.insertOne(studentFormData);
189
+ emitFormSubmittedActivity(db, {
190
+ projectId,
191
+ formName,
192
+ studentFormData,
193
+ submittedFormId: formResult.insertedId
194
+ }).catch(err => {
195
+ console.error("form_submitted activity emit failed:", err && err.message ? err.message : err);
196
+ });
119
197
  res.status(201).json({
120
198
  success: true,
121
199
  message: 'Student form submitted successfully',
@@ -185,6 +263,9 @@ async function createPowrForm(formData, projectId, res) {
185
263
  }
186
264
  const finalFormData = {
187
265
  ...formData,
266
+ ...(formData.notifyUserIds !== undefined ? {
267
+ notifyUserIds: normalizeNotifyUserIds(formData.notifyUserIds)
268
+ } : {}),
188
269
  projectId: projectId,
189
270
  createdAt: new Date()
190
271
  };
@@ -253,7 +334,8 @@ router.put('/update-form/:formName', verifyToken, async (req, res) => {
253
334
  formId,
254
335
  description,
255
336
  imageUrl,
256
- fields
337
+ fields,
338
+ notifyUserIds
257
339
  } = req.body;
258
340
  if (!(formTitle !== null && formTitle !== void 0 && formTitle.trim()) || !(formId !== null && formId !== void 0 && formId.trim())) {
259
341
  return res.status(400).json({
@@ -285,6 +367,9 @@ router.put('/update-form/:formName', verifyToken, async (req, res) => {
285
367
  description: (description === null || description === void 0 ? void 0 : description.trim()) || '',
286
368
  imageUrl: (imageUrl === null || imageUrl === void 0 ? void 0 : imageUrl.trim()) || '',
287
369
  fields,
370
+ ...(notifyUserIds !== undefined ? {
371
+ notifyUserIds: normalizeNotifyUserIds(notifyUserIds)
372
+ } : {}),
288
373
  updatedAt: new Date()
289
374
  };
290
375
  await powrFormCollection.updateOne({
@@ -360,4 +445,7 @@ router.get("/submissions/:formId", verifyToken, async (req, res) => {
360
445
  });
361
446
  }
362
447
  });
363
- module.exports = router;
448
+ module.exports = router;
449
+ module.exports.emitFormSubmittedActivity = emitFormSubmittedActivity;
450
+ module.exports.resolveFormNotifyUserIds = resolveFormNotifyUserIds;
451
+ module.exports.normalizeNotifyUserIds = normalizeNotifyUserIds;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+
3
+ jest.mock("../services/mongo", () => ({
4
+ getDb: jest.fn()
5
+ }));
6
+ jest.mock("../middleware/jwtToken", () => ({
7
+ verifyToken: (req, res, next) => next()
8
+ }));
9
+ const {
10
+ emitFormSubmittedActivity,
11
+ resolveFormNotifyUserIds,
12
+ normalizeNotifyUserIds
13
+ } = require("./forms");
14
+ describe("forms Pulse notification helpers", () => {
15
+ const projectId = "6ab230fd53c20550171ac98b";
16
+ const admin1 = "6893ec11c19c093a5bf21720";
17
+ const admin2 = "6893ec11c19c093a5bf21721";
18
+ const submitter = "6893ec11c19c093a5bf21722";
19
+ it("normalizes notifyUserIds from array or comma string", () => {
20
+ expect(normalizeNotifyUserIds([admin1, " ", admin2, admin1])).toEqual([admin1, admin2]);
21
+ expect(normalizeNotifyUserIds(`${admin1}, ${admin2}`)).toEqual([admin1, admin2]);
22
+ });
23
+ it("falls back to project access=100 admins when notifyUserIds is empty", async () => {
24
+ const db = {
25
+ collection(name) {
26
+ expect(name).toBe("profiles");
27
+ return {
28
+ find(filter) {
29
+ expect(filter).toEqual({
30
+ projectId,
31
+ access: 100
32
+ });
33
+ return {
34
+ limit: () => ({
35
+ toArray: async () => [{
36
+ userId: admin1
37
+ }, {
38
+ userId: admin2
39
+ }]
40
+ })
41
+ };
42
+ }
43
+ };
44
+ }
45
+ };
46
+ const ids = await resolveFormNotifyUserIds(db, projectId, {}, submitter);
47
+ expect(ids).toEqual([admin1, admin2]);
48
+ });
49
+ it("emits form_submitted activity with notify payload", async () => {
50
+ const insertedActivities = [];
51
+ const db = {
52
+ collection(name) {
53
+ if (name === "powrForm") {
54
+ return {
55
+ findOne: async () => ({
56
+ formName: "kundli-test",
57
+ formTitle: "Kundli Test Data",
58
+ notifyUserIds: [admin1]
59
+ })
60
+ };
61
+ }
62
+ if (name === "activities") {
63
+ return {
64
+ insertOne: async doc => {
65
+ insertedActivities.push(doc);
66
+ return {
67
+ insertedId: "act123"
68
+ };
69
+ }
70
+ };
71
+ }
72
+ throw new Error(`Unexpected collection ${name}`);
73
+ }
74
+ };
75
+ const res = await emitFormSubmittedActivity(db, {
76
+ projectId,
77
+ formName: "kundli-test",
78
+ submittedFormId: "sub123",
79
+ studentFormData: {
80
+ userId: submitter,
81
+ respondent_name: "Vishwajeet",
82
+ whatsapp: "+919999999999"
83
+ }
84
+ });
85
+ expect(res.insertedId).toBe("act123");
86
+ expect(insertedActivities).toHaveLength(1);
87
+ expect(insertedActivities[0].action).toBe("form_submitted");
88
+ expect(insertedActivities[0].targetType).toBe("form");
89
+ expect(insertedActivities[0].metadata).toEqual({
90
+ source: "powr-forms",
91
+ formName: "kundli-test",
92
+ formTitle: "Kundli Test Data",
93
+ respondent: "Vishwajeet"
94
+ });
95
+ });
96
+ });
@@ -41,6 +41,95 @@ function parseFeedbackStatus(body) {
41
41
  }
42
42
  return status;
43
43
  }
44
+ const ADMIN_ORIGINS = {
45
+ "678db163f70e70f6056b2c38": "https://urbanstall.app",
46
+ "678db178f70e70f6056b2c3d": "https://excelrs.dev",
47
+ "6a266d9ed1945234e550241d": "https://rasoi.lawazia.tech",
48
+ "6921a93a3442a87a29e343a3": "https://marketiq.lawazia.tech",
49
+ "67feef40059e70e9cf0db96b": "https://spriny.lawazia.tech",
50
+ "688ff878af20e61d802124e7": "https://ampy.lawazia.tech",
51
+ "6a4796c08fd806f0476f87c0": "https://earn.urbanstall.app",
52
+ "69144e04dff7d83475e3ab71": "https://win.urbanstall.app",
53
+ "6a9c4e083a27d813e2d80ec9": "https://employee.lawazia.tech",
54
+ "6a438583e5075411f5dd15e0": "https://office.lawazia.tech",
55
+ "6ac697da9a9acc3bc53d66fa": "https://testflight.lawazia.tech",
56
+ "6ab5e57fde1ce4f47861257f": "https://data.lawazia.tech",
57
+ "6ac36a6c24c482d7d4644948": "https://mobility.lawazia.tech"
58
+ };
59
+ function feedbackAdminLink(projectId) {
60
+ const origin = ADMIN_ORIGINS[String(projectId || "").trim()];
61
+ if (!origin) return "/powr-admin";
62
+ return `${origin}/powr-admin`;
63
+ }
64
+ function adminIdsFromProfiles(profiles, actorId) {
65
+ const actor = String(actorId || "").trim();
66
+ const ids = [...new Set((profiles || []).map(row => row && row.userId != null ? String(row.userId).trim() : "").filter(Boolean))];
67
+ const others = actor ? ids.filter(id => id !== actor) : ids;
68
+ return others.length > 0 ? others : ids;
69
+ }
70
+ async function loadFeedbackAdminIds(db, projectId, actorId) {
71
+ const project = String(projectId || "").trim();
72
+ if (!project) return [];
73
+ const profiles = await db.collection("profiles").find({
74
+ projectId: project,
75
+ access: {
76
+ $in: [100, "100"]
77
+ }
78
+ }, {
79
+ projection: {
80
+ userId: 1
81
+ }
82
+ }).limit(100).toArray();
83
+ return adminIdsFromProfiles(profiles, actorId);
84
+ }
85
+ function feedbackNotify({
86
+ projectId,
87
+ title,
88
+ kind,
89
+ createdByName,
90
+ userIds
91
+ }) {
92
+ const who = String(createdByName || "").trim() || "Someone";
93
+ const label = kind === "other" ? "Domain" : "Tech";
94
+ return {
95
+ userIds,
96
+ title: "New feedback",
97
+ body: `${who} · ${label} · ${String(title || "").trim()}`.slice(0, 2000),
98
+ link: feedbackAdminLink(projectId),
99
+ projectId: String(projectId)
100
+ };
101
+ }
102
+ async function ringFeedback(db, doc, deps = {}) {
103
+ try {
104
+ const projectId = String(doc.projectId || "").trim();
105
+ const noteId = doc._id != null ? String(doc._id) : "";
106
+ if (!projectId || !noteId) return null;
107
+ const userIds = await loadFeedbackAdminIds(db, projectId, doc.createdBy);
108
+ if (!userIds.length) return null;
109
+ const emitActivity = deps.emitActivity || require("../managers/activities").emitActivity;
110
+ return await emitActivity({
111
+ projectId,
112
+ action: "feedback_filed",
113
+ userId: doc.createdBy ? String(doc.createdBy) : null,
114
+ targetType: "feedback",
115
+ targetId: noteId,
116
+ notify: feedbackNotify({
117
+ projectId,
118
+ title: doc.title,
119
+ kind: doc.kind,
120
+ createdByName: doc.createdByName,
121
+ userIds
122
+ })
123
+ }, {
124
+ getDb: async () => db,
125
+ fetchImpl: deps.fetchImpl,
126
+ env: deps.env
127
+ });
128
+ } catch (error) {
129
+ console.error("feedback pulse", error instanceof Error ? error.message : "failed");
130
+ return null;
131
+ }
132
+ }
44
133
  function feedbackSummary(row) {
45
134
  return {
46
135
  _id: String(row._id),
@@ -60,5 +149,10 @@ module.exports = {
60
149
  STATUSES,
61
150
  parseFeedbackCreate,
62
151
  parseFeedbackStatus,
63
- feedbackSummary
152
+ feedbackSummary,
153
+ feedbackAdminLink,
154
+ adminIdsFromProfiles,
155
+ loadFeedbackAdminIds,
156
+ feedbackNotify,
157
+ ringFeedback
64
158
  };
@@ -3,7 +3,10 @@
3
3
  const {
4
4
  parseFeedbackCreate,
5
5
  parseFeedbackStatus,
6
- feedbackSummary
6
+ feedbackSummary,
7
+ feedbackAdminLink,
8
+ adminIdsFromProfiles,
9
+ ringFeedback
7
10
  } = require("./feedback");
8
11
  describe("parseFeedbackCreate", () => {
9
12
  it("keeps title, note, and kind", () => {
@@ -52,4 +55,84 @@ describe("feedbackSummary", () => {
52
55
  expect(row.kind).toBe("other");
53
56
  expect(row.createdByName).toBe("Ravi");
54
57
  });
58
+ });
59
+ describe("feedback pulse", () => {
60
+ const projectId = "6a4796c08fd806f0476f87c0";
61
+ const admin = "6893ec11c19c093a5bf21720";
62
+ const sender = "6893ec11c19c093a5bf21722";
63
+ it("opens that app's admin page", () => {
64
+ expect(feedbackAdminLink(projectId)).toBe("https://earn.urbanstall.app/powr-admin");
65
+ expect(feedbackAdminLink("unknown")).toBe("/powr-admin");
66
+ });
67
+ it("rings other admins, and the sender only when they are the only admin", () => {
68
+ expect(adminIdsFromProfiles([{
69
+ userId: admin
70
+ }, {
71
+ userId: sender
72
+ }], sender)).toEqual([admin]);
73
+ expect(adminIdsFromProfiles([{
74
+ userId: sender
75
+ }], sender)).toEqual([sender]);
76
+ });
77
+ it("emits a Pulse notify and still returns when the ring fails", async () => {
78
+ const db = {
79
+ collection(name) {
80
+ expect(name).toBe("profiles");
81
+ return {
82
+ find() {
83
+ return {
84
+ limit: () => ({
85
+ toArray: async () => [{
86
+ userId: admin
87
+ }]
88
+ })
89
+ };
90
+ }
91
+ };
92
+ }
93
+ };
94
+ const emitted = [];
95
+ const result = await ringFeedback(db, {
96
+ _id: "note1",
97
+ projectId,
98
+ title: "Banner size",
99
+ kind: "app",
100
+ createdBy: sender,
101
+ createdByName: "Ravi"
102
+ }, {
103
+ emitActivity: async event => {
104
+ emitted.push(event);
105
+ return {
106
+ insertedId: "act1"
107
+ };
108
+ }
109
+ });
110
+ expect(result.insertedId).toBe("act1");
111
+ expect(emitted[0].action).toBe("feedback_filed");
112
+ expect(emitted[0].notify.userIds).toEqual([admin]);
113
+ expect(emitted[0].notify.title).toBe("New feedback");
114
+ expect(emitted[0].notify.body).toBe("Ravi · Tech · Banner size");
115
+ expect(emitted[0].notify.link).toBe("https://earn.urbanstall.app/powr-admin");
116
+ const quiet = await ringFeedback({
117
+ collection() {
118
+ return {
119
+ find: () => ({
120
+ limit: () => ({
121
+ toArray: async () => []
122
+ })
123
+ })
124
+ };
125
+ }
126
+ }, {
127
+ _id: "note2",
128
+ projectId,
129
+ title: "Quiet",
130
+ createdBy: sender
131
+ }, {
132
+ emitActivity: async () => {
133
+ throw new Error("should not emit");
134
+ }
135
+ });
136
+ expect(quiet).toBeNull();
137
+ });
55
138
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.18.1",
3
+ "version": "4.19.1",
4
4
  "description": "Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",