powr-sdk-api 4.22.2 → 4.23.0

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.
@@ -17,7 +17,9 @@ const injectProjectId = (options = {}) => {
17
17
  return (req, res, next) => {
18
18
  try {
19
19
  // Skip validation for excluded paths
20
- if (req.path === "/scheduler/tick" || excludePaths.some(path => req.path.startsWith(path))) {
20
+ // Ads are one pool on the host. A portal does not send a project id to draw one.
21
+ const sharedAds = req.path === "/ads" || req.path.startsWith("/ads/");
22
+ if (req.path === "/scheduler/tick" || sharedAds || excludePaths.some(path => req.path.startsWith(path))) {
21
23
  req.projectId = req.query && req.query.projectId || req.body && req.body.projectId || null;
22
24
  return next();
23
25
  }
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+
3
+ const express = require("express");
4
+ const router = express.Router();
5
+ const {
6
+ getDb
7
+ } = require("../services/mongo");
8
+ const {
9
+ verifyTokenOrServiceKey
10
+ } = require("../middleware/serviceKey");
11
+ const {
12
+ callerIsAdmin
13
+ } = require("../utils/track");
14
+ const {
15
+ COLLECTION,
16
+ parseAdCreate,
17
+ parseAdPatch,
18
+ asId,
19
+ publicCard,
20
+ staffCard,
21
+ drawAd
22
+ } = require("../utils/ads");
23
+ let indexReady = null;
24
+ function ensureIndex(db) {
25
+ if (!indexReady) {
26
+ indexReady = db.collection(COLLECTION).createIndex({
27
+ hidden: 1,
28
+ showCount: 1,
29
+ lastShownAt: 1
30
+ }, {
31
+ name: "live_turns"
32
+ }).catch(error => {
33
+ indexReady = null;
34
+ console.error("ads index:", error.message);
35
+ });
36
+ }
37
+ return indexReady;
38
+ }
39
+ async function requireAdmin(db, req, res) {
40
+ if (req.serviceCall) return true;
41
+ if (!req.user) {
42
+ res.status(401).json({
43
+ success: false,
44
+ message: "Sign in required."
45
+ });
46
+ return false;
47
+ }
48
+ if (!(await callerIsAdmin(db, req))) {
49
+ res.status(403).json({
50
+ success: false,
51
+ message: "Access denied."
52
+ });
53
+ return false;
54
+ }
55
+ return true;
56
+ }
57
+ function fail(res, error, label) {
58
+ const status = error.statusCode || 500;
59
+ if (status >= 500) console.error(label, error.message);
60
+ return res.status(status).json({
61
+ success: false,
62
+ message: status >= 500 ? "Something went wrong." : error.message
63
+ });
64
+ }
65
+
66
+ /** One ad any portal can show. No project, no coin. */
67
+ router.get("/draw", async (req, res) => {
68
+ try {
69
+ const db = await getDb();
70
+ await ensureIndex(db);
71
+ const row = await drawAd(db);
72
+ return res.json({
73
+ success: true,
74
+ data: publicCard(row)
75
+ });
76
+ } catch (error) {
77
+ return fail(res, error, "GET /ads/draw");
78
+ }
79
+ });
80
+ router.get("/", verifyTokenOrServiceKey, async (req, res) => {
81
+ try {
82
+ const db = await getDb();
83
+ if (!(await requireAdmin(db, req, res))) return;
84
+ await ensureIndex(db);
85
+ const rows = await db.collection(COLLECTION).find({}).sort({
86
+ createdAt: -1
87
+ }).limit(200).toArray();
88
+ return res.json({
89
+ success: true,
90
+ count: rows.length,
91
+ data: rows.map(staffCard)
92
+ });
93
+ } catch (error) {
94
+ return fail(res, error, "GET /ads");
95
+ }
96
+ });
97
+ router.post("/", verifyTokenOrServiceKey, async (req, res) => {
98
+ try {
99
+ const fields = parseAdCreate(req.body || {});
100
+ const db = await getDb();
101
+ if (!(await requireAdmin(db, req, res))) return;
102
+ await ensureIndex(db);
103
+ const now = new Date();
104
+ const doc = {
105
+ picture: fields.picture,
106
+ title: fields.title,
107
+ tagline: fields.tagline,
108
+ description: fields.description,
109
+ brand: fields.brand,
110
+ brandIcon: fields.brandIcon,
111
+ brandLink: fields.brandLink,
112
+ offer: fields.offer,
113
+ cta: fields.cta,
114
+ link: fields.link,
115
+ hidden: false,
116
+ showCount: 0,
117
+ lastShownAt: null,
118
+ createdAt: now,
119
+ updatedAt: now
120
+ };
121
+ const result = await db.collection(COLLECTION).insertOne(doc);
122
+ return res.status(201).json({
123
+ success: true,
124
+ data: staffCard({
125
+ ...doc,
126
+ _id: result.insertedId
127
+ })
128
+ });
129
+ } catch (error) {
130
+ return fail(res, error, "POST /ads");
131
+ }
132
+ });
133
+ router.patch("/:id", verifyTokenOrServiceKey, async (req, res) => {
134
+ const oid = asId(req.params.id);
135
+ if (!oid) return res.status(400).json({
136
+ success: false,
137
+ message: "Invalid ad id."
138
+ });
139
+ try {
140
+ const patch = parseAdPatch(req.body || {});
141
+ const db = await getDb();
142
+ if (!(await requireAdmin(db, req, res))) return;
143
+ const now = new Date();
144
+ const raw = await db.collection(COLLECTION).findOneAndUpdate({
145
+ _id: oid
146
+ }, {
147
+ $set: {
148
+ ...patch,
149
+ updatedAt: now
150
+ }
151
+ }, {
152
+ returnDocument: "after"
153
+ });
154
+ const row = raw && raw.value ? raw.value : raw;
155
+ if (!row || !row._id) {
156
+ return res.status(404).json({
157
+ success: false,
158
+ message: "Ad not found."
159
+ });
160
+ }
161
+ return res.json({
162
+ success: true,
163
+ data: staffCard(row)
164
+ });
165
+ } catch (error) {
166
+ return fail(res, error, "PATCH /ads/:id");
167
+ }
168
+ });
169
+ module.exports = router;
@@ -40,6 +40,7 @@ const tasksRoutes = require('./tasks');
40
40
  const preferencesRoutes = require('./preferences');
41
41
  const schedulerRoutes = require('./scheduler');
42
42
  const postsRoutes = require('./posts');
43
+ const adsRoutes = require('./ads');
43
44
 
44
45
  // Synchronous router creation
45
46
  const createPowrRoutes = (options = {}) => {
@@ -75,6 +76,8 @@ const createPowrRoutes = (options = {}) => {
75
76
  router.use('/tools', verifyToken, toolsRoutes);
76
77
  router.use('/tasks', verifyToken, tasksRoutes);
77
78
  router.use('/scheduler', verifyTokenOrServiceKey, schedulerRoutes);
79
+ // Draw is public. Create, list, and hide check the token on those routes.
80
+ router.use('/ads', adsRoutes);
78
81
  // Public reads stay open. Writer and editor routes check the token themselves.
79
82
  router.use('/posts', postsRoutes);
80
83
  return router;
@@ -9,7 +9,7 @@ const {
9
9
  getDb
10
10
  } = require("../services/mongo");
11
11
  const {
12
- isPageviewAdmin
12
+ callerIsAdmin
13
13
  } = require("../utils/track");
14
14
  const {
15
15
  COLLECTION,
@@ -23,38 +23,6 @@ const {
23
23
  fireTarget,
24
24
  runDue
25
25
  } = require("../utils/scheduler");
26
- async function callerIsAdmin(db, req) {
27
- var _req$user, _req$user2;
28
- const rawId = String(((_req$user = req.user) === null || _req$user === void 0 ? void 0 : _req$user.powrId) || "");
29
- let profileAccess;
30
- let userAccess;
31
- if (rawId.length === 24 && ObjectId.isValid(rawId)) {
32
- const oid = new ObjectId(rawId);
33
- const [profile, user] = await Promise.all([db.collection("profiles").findOne({
34
- userId: {
35
- $in: [oid, rawId]
36
- },
37
- projectId: String(req.projectId || "")
38
- }, {
39
- projection: {
40
- access: 1
41
- }
42
- }), db.collection("users").findOne({
43
- _id: oid
44
- }, {
45
- projection: {
46
- access: 1
47
- }
48
- })]);
49
- if (profile) profileAccess = profile.access;
50
- if (user) userAccess = user.access;
51
- }
52
- return isPageviewAdmin({
53
- jwtAccess: (_req$user2 = req.user) === null || _req$user2 === void 0 ? void 0 : _req$user2.access,
54
- profileAccess,
55
- userAccess
56
- });
57
- }
58
26
  async function requireActor(db, req, res) {
59
27
  if (req.serviceCall) return true;
60
28
  if (!req.user) {
@@ -12,41 +12,9 @@ const {
12
12
  PAGEVIEW_TTL_SECONDS,
13
13
  PAGEVIEW_LIST_LIMIT,
14
14
  buildPageview,
15
- isPageviewAdmin,
16
- recentPageviewFilter
15
+ recentPageviewFilter,
16
+ callerIsAdmin
17
17
  } = require("../utils/track");
18
- async function callerIsAdmin(db, req) {
19
- var _req$user, _req$user2;
20
- const rawId = String(((_req$user = req.user) === null || _req$user === void 0 ? void 0 : _req$user.powrId) || "");
21
- let profileAccess;
22
- let userAccess;
23
- if (rawId.length === 24 && ObjectId.isValid(rawId)) {
24
- const oid = new ObjectId(rawId);
25
- const [profile, user] = await Promise.all([db.collection("profiles").findOne({
26
- userId: {
27
- $in: [oid, rawId]
28
- },
29
- projectId: String(req.projectId || "")
30
- }, {
31
- projection: {
32
- access: 1
33
- }
34
- }), db.collection("users").findOne({
35
- _id: oid
36
- }, {
37
- projection: {
38
- access: 1
39
- }
40
- })]);
41
- if (profile) profileAccess = profile.access;
42
- if (user) userAccess = user.access;
43
- }
44
- return isPageviewAdmin({
45
- jwtAccess: (_req$user2 = req.user) === null || _req$user2 === void 0 ? void 0 : _req$user2.access,
46
- profileAccess,
47
- userAccess
48
- });
49
- }
50
18
  let indexesPromise = null;
51
19
  function ensurePageviewIndexes(db) {
52
20
  if (!indexesPromise) {
@@ -0,0 +1,271 @@
1
+ "use strict";
2
+
3
+ const {
4
+ ObjectId
5
+ } = require("mongodb");
6
+ const COLLECTION = "powrAds";
7
+ const MAX_TITLE = 70;
8
+ const MAX_TAGLINE = 120;
9
+ const MAX_DESCRIPTION = 600;
10
+ const MAX_BRAND = 40;
11
+ const MAX_OFFER = 40;
12
+ const MAX_CTA = 30;
13
+ const MAX_URL = 500;
14
+ function reject(message, statusCode = 400) {
15
+ const error = new Error(message);
16
+ error.statusCode = statusCode;
17
+ throw error;
18
+ }
19
+ function cleanText(value) {
20
+ return typeof value === "string" ? value.trim() : "";
21
+ }
22
+ function httpsUrl(value, name, {
23
+ required
24
+ } = {}) {
25
+ const text = cleanText(value);
26
+ if (!text) {
27
+ if (required) reject(`${name} is required.`);
28
+ return "";
29
+ }
30
+ if (text.length > MAX_URL) reject(`${name} is too long.`);
31
+ let url;
32
+ try {
33
+ url = new URL(text);
34
+ } catch (error) {
35
+ reject(`${name} must be an https link.`);
36
+ }
37
+ if (url.protocol !== "https:") reject(`${name} must be an https link.`);
38
+ return url.toString();
39
+ }
40
+ function bounded(value, name, max, {
41
+ required
42
+ } = {}) {
43
+ const text = cleanText(value);
44
+ if (!text) {
45
+ if (required) reject(`${name} is required.`);
46
+ return "";
47
+ }
48
+ if (text.length > max) reject(`${name} must be ${max} characters or fewer.`);
49
+ return text;
50
+ }
51
+
52
+ /** Title, or the older single line when a caller has not split it yet. */
53
+ function parseTitle(source) {
54
+ const hasTitle = Object.prototype.hasOwnProperty.call(source, "title");
55
+ const text = hasTitle ? cleanText(source.title) : cleanText(source.line);
56
+ if (!text) reject("Title is required.");
57
+ if (text.length > MAX_TITLE) reject(`Title must be ${MAX_TITLE} characters or fewer.`);
58
+ return text;
59
+ }
60
+
61
+ /**
62
+ * Tagline is the short line. Description is the optional longer text.
63
+ * An older caller that sent only a short description keeps that text as the tagline.
64
+ */
65
+ function parseCopy(source) {
66
+ const hasTagline = Object.prototype.hasOwnProperty.call(source, "tagline");
67
+ const tagline = hasTagline ? bounded(source.tagline, "Tagline", MAX_TAGLINE) : "";
68
+ const description = bounded(source.description, "Description", MAX_DESCRIPTION);
69
+ if (!hasTagline && description && description.length <= MAX_TAGLINE) {
70
+ return {
71
+ tagline: description,
72
+ description: ""
73
+ };
74
+ }
75
+ return {
76
+ tagline,
77
+ description
78
+ };
79
+ }
80
+ function parseOffer(source) {
81
+ return {
82
+ offer: bounded(source.offer, "Offer", MAX_OFFER),
83
+ brandIcon: httpsUrl(source.brandIcon, "Brand icon"),
84
+ brandLink: httpsUrl(source.brandLink, "Brand link")
85
+ };
86
+ }
87
+
88
+ /** Create body. Square picture, title, tagline, optional description, brand, offer, and links. */
89
+ function parseAdCreate(body) {
90
+ const source = body && typeof body === "object" ? body : {};
91
+ return {
92
+ picture: httpsUrl(source.picture, "Picture", {
93
+ required: true
94
+ }),
95
+ title: parseTitle(source),
96
+ ...parseCopy(source),
97
+ brand: bounded(source.brand, "Brand", MAX_BRAND),
98
+ ...parseOffer(source),
99
+ cta: bounded(source.cta, "Call to action", MAX_CTA),
100
+ link: httpsUrl(source.link, "Link")
101
+ };
102
+ }
103
+
104
+ /** Patch body. At least one field. */
105
+ function parseAdPatch(body) {
106
+ const source = body && typeof body === "object" ? body : {};
107
+ const patch = {};
108
+ if (Object.prototype.hasOwnProperty.call(source, "picture")) {
109
+ patch.picture = httpsUrl(source.picture, "Picture", {
110
+ required: true
111
+ });
112
+ }
113
+ if (Object.prototype.hasOwnProperty.call(source, "title") || Object.prototype.hasOwnProperty.call(source, "line")) {
114
+ patch.title = parseTitle(source);
115
+ }
116
+ if (Object.prototype.hasOwnProperty.call(source, "tagline") || Object.prototype.hasOwnProperty.call(source, "description")) {
117
+ const copy = parseCopy(source);
118
+ if (Object.prototype.hasOwnProperty.call(source, "tagline")) patch.tagline = copy.tagline;
119
+ if (Object.prototype.hasOwnProperty.call(source, "description")) {
120
+ patch.description = copy.description;
121
+ if (!Object.prototype.hasOwnProperty.call(source, "tagline") && copy.tagline) patch.tagline = copy.tagline;
122
+ }
123
+ }
124
+ if (Object.prototype.hasOwnProperty.call(source, "brand")) {
125
+ patch.brand = bounded(source.brand, "Brand", MAX_BRAND);
126
+ }
127
+ if (Object.prototype.hasOwnProperty.call(source, "offer")) {
128
+ patch.offer = bounded(source.offer, "Offer", MAX_OFFER);
129
+ }
130
+ if (Object.prototype.hasOwnProperty.call(source, "brandIcon")) {
131
+ patch.brandIcon = httpsUrl(source.brandIcon, "Brand icon");
132
+ }
133
+ if (Object.prototype.hasOwnProperty.call(source, "brandLink")) {
134
+ patch.brandLink = httpsUrl(source.brandLink, "Brand link");
135
+ }
136
+ if (Object.prototype.hasOwnProperty.call(source, "cta")) {
137
+ patch.cta = bounded(source.cta, "Call to action", MAX_CTA);
138
+ }
139
+ if (Object.prototype.hasOwnProperty.call(source, "link")) {
140
+ patch.link = httpsUrl(source.link, "Link");
141
+ }
142
+ if (Object.prototype.hasOwnProperty.call(source, "hidden")) {
143
+ if (typeof source.hidden !== "boolean") reject("Hidden must be true or false.");
144
+ patch.hidden = source.hidden;
145
+ }
146
+ if (!Object.keys(patch).length) reject("Nothing to change.");
147
+ return patch;
148
+ }
149
+ function asId(value) {
150
+ const id = String(value || "");
151
+ if (!ObjectId.isValid(id) || id.length !== 24) return null;
152
+ return new ObjectId(id);
153
+ }
154
+ function shownTime(value) {
155
+ if (!value) return 0;
156
+ const time = new Date(value).getTime();
157
+ return Number.isFinite(time) ? time : 0;
158
+ }
159
+
160
+ /** Fewest shows first. On a tie, the one shown longer ago. */
161
+ function compareAds(a, b) {
162
+ const shows = (Number(a && a.showCount) || 0) - (Number(b && b.showCount) || 0);
163
+ if (shows) return shows;
164
+ const at = shownTime(a && a.lastShownAt) - shownTime(b && b.lastShownAt);
165
+ if (at) return at;
166
+ return String(a && a._id || "").localeCompare(String(b && b._id || ""));
167
+ }
168
+ function copyOf(row) {
169
+ const tagline = cleanText(row && row.tagline);
170
+ const description = cleanText(row && row.description);
171
+ if (tagline) return {
172
+ tagline,
173
+ description
174
+ };
175
+ return {
176
+ tagline: description,
177
+ description: ""
178
+ };
179
+ }
180
+ function publicCard(row) {
181
+ if (!row) return null;
182
+ const copy = copyOf(row);
183
+ const card = {
184
+ id: String(row._id),
185
+ picture: row.picture,
186
+ title: row.title || row.line || ""
187
+ };
188
+ if (copy.tagline) card.tagline = copy.tagline;
189
+ if (copy.description) card.description = copy.description;
190
+ if (row.brand) card.brand = row.brand;
191
+ if (row.brandIcon) card.brandIcon = row.brandIcon;
192
+ if (row.brandLink) card.brandLink = row.brandLink;
193
+ if (row.offer) card.offer = row.offer;
194
+ if (row.cta) card.cta = row.cta;
195
+ if (row.link) card.link = row.link;
196
+ return card;
197
+ }
198
+ function staffCard(row) {
199
+ const copy = copyOf(row);
200
+ return {
201
+ id: String(row._id),
202
+ picture: row.picture,
203
+ title: row.title || row.line || "",
204
+ tagline: copy.tagline,
205
+ description: copy.description,
206
+ brand: row.brand || "",
207
+ brandIcon: row.brandIcon || "",
208
+ brandLink: row.brandLink || "",
209
+ offer: row.offer || "",
210
+ cta: row.cta || "",
211
+ link: row.link || "",
212
+ hidden: row.hidden === true,
213
+ showCount: Number(row.showCount) || 0,
214
+ lastShownAt: row.lastShownAt || null,
215
+ createdAt: row.createdAt || null
216
+ };
217
+ }
218
+ function updatedDoc(raw) {
219
+ if (!raw) return null;
220
+ if (raw.value) return raw.value;
221
+ if (raw._id) return raw;
222
+ return null;
223
+ }
224
+
225
+ /**
226
+ * One live ad for any portal. Increments the show count.
227
+ * Hidden rows stay out. The pool is not split by project.
228
+ */
229
+ async function drawAd(db, now = new Date()) {
230
+ const rows = await db.collection(COLLECTION).find({
231
+ hidden: {
232
+ $ne: true
233
+ }
234
+ }).limit(200).toArray();
235
+ if (!rows.length) return null;
236
+ rows.sort(compareAds);
237
+ const winner = rows[0];
238
+ const raw = await db.collection(COLLECTION).findOneAndUpdate({
239
+ _id: winner._id,
240
+ hidden: {
241
+ $ne: true
242
+ }
243
+ }, {
244
+ $inc: {
245
+ showCount: 1
246
+ },
247
+ $set: {
248
+ lastShownAt: now,
249
+ updatedAt: now
250
+ }
251
+ }, {
252
+ returnDocument: "after"
253
+ });
254
+ return updatedDoc(raw);
255
+ }
256
+ module.exports = {
257
+ COLLECTION,
258
+ MAX_TITLE,
259
+ MAX_TAGLINE,
260
+ MAX_DESCRIPTION,
261
+ MAX_BRAND,
262
+ MAX_OFFER,
263
+ MAX_CTA,
264
+ parseAdCreate,
265
+ parseAdPatch,
266
+ asId,
267
+ compareAds,
268
+ publicCard,
269
+ staffCard,
270
+ drawAd
271
+ };
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+
3
+ const {
4
+ ObjectId
5
+ } = require("mongodb");
6
+ const {
7
+ parseAdCreate,
8
+ parseAdPatch,
9
+ compareAds,
10
+ publicCard,
11
+ drawAd
12
+ } = require("./ads");
13
+ describe("parseAdCreate", () => {
14
+ it("keeps a square picture, title, tagline, an optional description, brand, and link", () => {
15
+ expect(parseAdCreate({
16
+ picture: "https://cdn.example/ad.jpg",
17
+ title: " Lunch thali ",
18
+ tagline: " Open today, twelve to three. ",
19
+ description: " Rice, dal, and two vegetables. ",
20
+ brand: " Ambika ",
21
+ offer: " ₹120 ",
22
+ brandIcon: "https://cdn.example/icon.jpg",
23
+ brandLink: "https://urbanstall.app/stall/ambika",
24
+ cta: " Order now ",
25
+ link: "https://urbanstall.app/stall/ambika"
26
+ })).toEqual({
27
+ picture: "https://cdn.example/ad.jpg",
28
+ title: "Lunch thali",
29
+ tagline: "Open today, twelve to three.",
30
+ description: "Rice, dal, and two vegetables.",
31
+ brand: "Ambika",
32
+ offer: "₹120",
33
+ brandIcon: "https://cdn.example/icon.jpg",
34
+ brandLink: "https://urbanstall.app/stall/ambika",
35
+ cta: "Order now",
36
+ link: "https://urbanstall.app/stall/ambika"
37
+ });
38
+ });
39
+ it("reads a short description with no tagline as the tagline", () => {
40
+ expect(parseAdCreate({
41
+ picture: "https://cdn.example/ad.jpg",
42
+ title: "Lunch thali",
43
+ description: "Open today, twelve to three."
44
+ })).toEqual({
45
+ picture: "https://cdn.example/ad.jpg",
46
+ title: "Lunch thali",
47
+ tagline: "Open today, twelve to three.",
48
+ description: "",
49
+ brand: "",
50
+ offer: "",
51
+ brandIcon: "",
52
+ brandLink: "",
53
+ cta: "",
54
+ link: ""
55
+ });
56
+ });
57
+ it("reads an older single line as the title", () => {
58
+ expect(parseAdCreate({
59
+ picture: "https://cdn.example/ad.jpg",
60
+ line: "Lunch thali"
61
+ })).toEqual({
62
+ picture: "https://cdn.example/ad.jpg",
63
+ title: "Lunch thali",
64
+ tagline: "",
65
+ description: "",
66
+ brand: "",
67
+ offer: "",
68
+ brandIcon: "",
69
+ brandLink: "",
70
+ cta: "",
71
+ link: ""
72
+ });
73
+ });
74
+ it("allows a missing link and ignores a coin or a price", () => {
75
+ expect(parseAdCreate({
76
+ picture: "https://cdn.example/ad.jpg",
77
+ title: "Open today",
78
+ reward: 2,
79
+ priceRupees: 2500,
80
+ projectId: "abc"
81
+ })).toEqual({
82
+ picture: "https://cdn.example/ad.jpg",
83
+ title: "Open today",
84
+ tagline: "",
85
+ description: "",
86
+ brand: "",
87
+ offer: "",
88
+ brandIcon: "",
89
+ brandLink: "",
90
+ cta: "",
91
+ link: ""
92
+ });
93
+ });
94
+ it("refuses a call to action longer than 30 characters", () => {
95
+ expect(() => parseAdCreate({
96
+ picture: "https://cdn.example/ad.jpg",
97
+ title: "Lunch thali",
98
+ cta: "Walk in and ask for the lunch thali"
99
+ })).toThrow("30");
100
+ });
101
+ it("refuses a picture that is not https", () => {
102
+ expect(() => parseAdCreate({
103
+ picture: "http://cdn.example/ad.jpg",
104
+ title: "Open today"
105
+ })).toThrow("https");
106
+ });
107
+ it("refuses an empty title", () => {
108
+ expect(() => parseAdCreate({
109
+ picture: "https://cdn.example/ad.jpg",
110
+ title: " "
111
+ })).toThrow("Title is required.");
112
+ });
113
+ });
114
+ describe("parseAdPatch", () => {
115
+ it("accepts hide", () => {
116
+ expect(parseAdPatch({
117
+ hidden: true
118
+ })).toEqual({
119
+ hidden: true
120
+ });
121
+ });
122
+ it("refuses an empty patch", () => {
123
+ expect(() => parseAdPatch({})).toThrow("Nothing to change.");
124
+ });
125
+ });
126
+ describe("compareAds", () => {
127
+ it("puts the fewer shows first, then the one shown longer ago", () => {
128
+ const quiet = {
129
+ _id: "b",
130
+ showCount: 1,
131
+ lastShownAt: new Date("2026-11-01T00:00:00.000Z")
132
+ };
133
+ const fresh = {
134
+ _id: "a",
135
+ showCount: 0,
136
+ lastShownAt: null
137
+ };
138
+ const busy = {
139
+ _id: "c",
140
+ showCount: 4,
141
+ lastShownAt: new Date("2026-11-19T00:00:00.000Z")
142
+ };
143
+ const olderTie = {
144
+ _id: "d",
145
+ showCount: 1,
146
+ lastShownAt: new Date("2026-10-01T00:00:00.000Z")
147
+ };
148
+ expect([busy, quiet, fresh, olderTie].sort(compareAds).map(row => row._id)).toEqual(["a", "d", "b", "c"]);
149
+ });
150
+ });
151
+ describe("publicCard", () => {
152
+ it("leaves the show count and the project off the card", () => {
153
+ expect(publicCard({
154
+ _id: "ad1",
155
+ picture: "https://cdn.example/ad.jpg",
156
+ title: "Lunch",
157
+ tagline: "Open today",
158
+ description: "Rice, dal, and two vegetables.",
159
+ brand: "Ambika",
160
+ offer: "₹120",
161
+ brandIcon: "https://cdn.example/icon.jpg",
162
+ brandLink: "https://urbanstall.app/",
163
+ line: "old",
164
+ link: "",
165
+ showCount: 9,
166
+ projectId: "nope"
167
+ })).toEqual({
168
+ id: "ad1",
169
+ picture: "https://cdn.example/ad.jpg",
170
+ title: "Lunch",
171
+ tagline: "Open today",
172
+ description: "Rice, dal, and two vegetables.",
173
+ brand: "Ambika",
174
+ offer: "₹120",
175
+ brandIcon: "https://cdn.example/icon.jpg",
176
+ brandLink: "https://urbanstall.app/"
177
+ });
178
+ });
179
+ it("keeps a call to action when one was written", () => {
180
+ expect(publicCard({
181
+ _id: "ad2",
182
+ picture: "https://cdn.example/ad.jpg",
183
+ title: "Lunch",
184
+ cta: "Order now",
185
+ link: "https://urbanstall.app/"
186
+ })).toMatchObject({
187
+ cta: "Order now",
188
+ link: "https://urbanstall.app/"
189
+ });
190
+ });
191
+ });
192
+ describe("drawAd", () => {
193
+ it("shows the quiet ad and counts that show", async () => {
194
+ const now = new Date("2026-11-20T02:00:00.000Z");
195
+ const loud = new ObjectId();
196
+ const quiet = new ObjectId();
197
+ const rows = [{
198
+ _id: loud,
199
+ picture: "https://cdn.example/loud.jpg",
200
+ line: "Loud",
201
+ link: "",
202
+ hidden: false,
203
+ showCount: 3,
204
+ lastShownAt: now
205
+ }, {
206
+ _id: quiet,
207
+ picture: "https://cdn.example/quiet.jpg",
208
+ line: "Quiet",
209
+ link: "https://example.com",
210
+ hidden: false,
211
+ showCount: 0,
212
+ lastShownAt: null
213
+ }, {
214
+ _id: new ObjectId(),
215
+ picture: "https://cdn.example/hidden.jpg",
216
+ line: "Hidden",
217
+ link: "",
218
+ hidden: true,
219
+ showCount: 0,
220
+ lastShownAt: null
221
+ }];
222
+ const col = {
223
+ find(filter) {
224
+ const matched = rows.filter(row => filter.hidden.$ne ? row.hidden !== true : true);
225
+ return {
226
+ limit() {
227
+ return this;
228
+ },
229
+ async toArray() {
230
+ return matched.map(row => ({
231
+ ...row
232
+ }));
233
+ }
234
+ };
235
+ },
236
+ async findOneAndUpdate(filter, update) {
237
+ const row = rows.find(item => String(item._id) === String(filter._id) && item.hidden !== true);
238
+ if (!row) return null;
239
+ row.showCount += update.$inc.showCount;
240
+ Object.assign(row, update.$set);
241
+ return {
242
+ ...row
243
+ };
244
+ }
245
+ };
246
+ const db = {
247
+ collection: () => col
248
+ };
249
+ const drawn = await drawAd(db, now);
250
+ expect(String(drawn._id)).toBe(String(quiet));
251
+ expect(drawn.showCount).toBe(1);
252
+ expect(drawn.lastShownAt).toBe(now);
253
+ const again = await drawAd(db, now);
254
+ expect(String(again._id)).toBe(String(quiet));
255
+ expect(rows.find(row => String(row._id) === String(loud)).showCount).toBe(3);
256
+ expect(rows.find(row => row.hidden).showCount).toBe(0);
257
+ });
258
+ it("returns null when every ad is hidden", async () => {
259
+ const col = {
260
+ find() {
261
+ return {
262
+ limit() {
263
+ return this;
264
+ },
265
+ async toArray() {
266
+ return [];
267
+ }
268
+ };
269
+ },
270
+ async findOneAndUpdate() {
271
+ throw new Error("should not update");
272
+ }
273
+ };
274
+ expect(await drawAd({
275
+ collection: () => col
276
+ })).toBe(null);
277
+ });
278
+ });
@@ -1,5 +1,11 @@
1
1
  "use strict";
2
2
 
3
+ const {
4
+ ObjectId
5
+ } = require("mongodb");
6
+ const {
7
+ getPhoneLookupVariants
8
+ } = require("./phone");
3
9
  const PAGEVIEW_TTL_SECONDS = 30 * 24 * 60 * 60;
4
10
  const PAGEVIEW_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
5
11
  const PAGEVIEW_LIST_LIMIT = 200;
@@ -161,12 +167,63 @@ function recentPageviewFilter(projectId, now = new Date()) {
161
167
  }
162
168
  };
163
169
  }
170
+ async function powrIdForCaller(db, user) {
171
+ const rawId = String((user === null || user === void 0 ? void 0 : user.powrId) || "");
172
+ if (rawId.length === 24 && ObjectId.isValid(rawId)) return rawId;
173
+ const phone = String((user === null || user === void 0 ? void 0 : user.phoneNumber) || "").trim();
174
+ if (!phone || phone.includes("@")) return "";
175
+ const variants = getPhoneLookupVariants(phone);
176
+ if (!variants.length) return "";
177
+ const found = await db.collection("users").findOne({
178
+ phoneNumber: {
179
+ $in: variants
180
+ }
181
+ }, {
182
+ projection: {
183
+ _id: 1
184
+ }
185
+ });
186
+ return found && found._id ? String(found._id) : "";
187
+ }
188
+ async function callerIsAdmin(db, req) {
189
+ const rawId = await powrIdForCaller(db, req && req.user);
190
+ let profileAccess;
191
+ let userAccess;
192
+ if (rawId.length === 24 && ObjectId.isValid(rawId)) {
193
+ const oid = new ObjectId(rawId);
194
+ const projectId = String(req && req.projectId || "");
195
+ const [profile, user] = await Promise.all([db.collection("profiles").findOne({
196
+ userId: {
197
+ $in: [oid, rawId]
198
+ },
199
+ projectId
200
+ }, {
201
+ projection: {
202
+ access: 1
203
+ }
204
+ }), db.collection("users").findOne({
205
+ _id: oid
206
+ }, {
207
+ projection: {
208
+ access: 1
209
+ }
210
+ })]);
211
+ if (profile) profileAccess = profile.access;
212
+ if (user) userAccess = user.access;
213
+ }
214
+ return isPageviewAdmin({
215
+ jwtAccess: req && req.user ? req.user.access : undefined,
216
+ profileAccess,
217
+ userAccess
218
+ });
219
+ }
164
220
  module.exports = {
165
221
  PAGEVIEW_TTL_SECONDS,
166
222
  PAGEVIEW_LIST_LIMIT,
167
223
  PAGEVIEW_LIST_FIELDS,
168
224
  buildPageview,
169
225
  isPageviewAdmin,
226
+ callerIsAdmin,
170
227
  summarizeVisitors,
171
228
  recentPageviewFilter
172
229
  };
@@ -4,6 +4,7 @@ const {
4
4
  buildPageview,
5
5
  PAGEVIEW_TTL_SECONDS,
6
6
  isPageviewAdmin,
7
+ callerIsAdmin,
7
8
  summarizeVisitors,
8
9
  recentPageviewFilter
9
10
  } = require("./track");
@@ -88,6 +89,69 @@ describe("isPageviewAdmin", () => {
88
89
  })).toBe(false);
89
90
  });
90
91
  });
92
+ describe("callerIsAdmin", () => {
93
+ const project = "678db163f70e70f6056b2c38";
94
+ const sandeep = "6893ec11c19c093a5bf21720";
95
+ function dbFor({
96
+ phone,
97
+ access
98
+ }) {
99
+ return {
100
+ collection(name) {
101
+ return {
102
+ async findOne(query) {
103
+ if (name === "users" && query.phoneNumber) {
104
+ const hit = query.phoneNumber.$in.includes(phone);
105
+ return hit ? {
106
+ _id: sandeep
107
+ } : null;
108
+ }
109
+ if (name === "users" && String(query._id) === sandeep) return {
110
+ _id: sandeep,
111
+ access
112
+ };
113
+ if (name === "profiles") return {
114
+ access
115
+ };
116
+ return null;
117
+ }
118
+ };
119
+ }
120
+ };
121
+ }
122
+ it("treats a phone-only login as the Powr profile for that project", async () => {
123
+ const allowed = await callerIsAdmin(dbFor({
124
+ phone: "+919800000000",
125
+ access: 100
126
+ }), {
127
+ projectId: project,
128
+ user: {
129
+ phoneNumber: "+919800000000"
130
+ }
131
+ });
132
+ expect(allowed).toBe(true);
133
+ const denied = await callerIsAdmin(dbFor({
134
+ phone: "+919800000000",
135
+ access: 500
136
+ }), {
137
+ projectId: project,
138
+ user: {
139
+ phoneNumber: "+919800000000"
140
+ }
141
+ });
142
+ expect(denied).toBe(false);
143
+ });
144
+ it("denies a token with no user and no phone", async () => {
145
+ const allowed = await callerIsAdmin(dbFor({
146
+ phone: "+919800000000",
147
+ access: 100
148
+ }), {
149
+ projectId: project,
150
+ user: {}
151
+ });
152
+ expect(allowed).toBe(false);
153
+ });
154
+ });
91
155
  describe("summarizeVisitors", () => {
92
156
  it("collapses a path log into one person and a page count", () => {
93
157
  const result = summarizeVisitors([{
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.22.2",
3
+ "version": "4.23.0",
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",