powr-sdk-api 4.14.0 → 4.15.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.
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
 
3
3
  const express = require("express");
4
+ const {
5
+ ObjectId
6
+ } = require("mongodb");
4
7
  const router = express.Router();
5
8
  const {
6
9
  getDb
@@ -8,10 +11,42 @@ const {
8
11
  const {
9
12
  PAGEVIEW_TTL_SECONDS,
10
13
  PAGEVIEW_LIST_LIMIT,
11
- PAGEVIEW_LIST_FIELDS,
12
14
  buildPageview,
15
+ isPageviewAdmin,
13
16
  recentPageviewFilter
14
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
+ }
15
50
  let indexesPromise = null;
16
51
  function ensurePageviewIndexes(db) {
17
52
  if (!indexesPromise) {
@@ -35,23 +70,74 @@ function ensurePageviewIndexes(db) {
35
70
  }
36
71
  router.get("/", async (req, res) => {
37
72
  try {
38
- var _req$user;
39
- if (Number((_req$user = req.user) === null || _req$user === void 0 ? void 0 : _req$user.access) !== 100) {
73
+ const db = await getDb();
74
+ if (!(await callerIsAdmin(db, req))) {
40
75
  return res.status(403).json({
41
76
  success: false,
42
77
  message: "Only an admin can view page views."
43
78
  });
44
79
  }
45
- const db = await getDb();
46
80
  await ensurePageviewIndexes(db);
47
- const rows = await db.collection("pageviews").find(recentPageviewFilter(req.projectId), {
48
- projection: PAGEVIEW_LIST_FIELDS
49
- }).sort({
50
- createdAt: -1
51
- }).limit(PAGEVIEW_LIST_LIMIT).toArray();
81
+ const filter = recentPageviewFilter(req.projectId);
82
+ const [pages, grouped] = await Promise.all([db.collection("pageviews").countDocuments(filter), db.collection("pageviews").aggregate([{
83
+ $match: filter
84
+ }, {
85
+ $group: {
86
+ _id: "$userId",
87
+ lastSeen: {
88
+ $max: "$createdAt"
89
+ },
90
+ pages: {
91
+ $sum: 1
92
+ }
93
+ }
94
+ }, {
95
+ $sort: {
96
+ lastSeen: -1
97
+ }
98
+ }, {
99
+ $limit: PAGEVIEW_LIST_LIMIT
100
+ }]).toArray()]);
101
+ const ids = grouped.map(row => String(row._id || "")).filter(id => id.length === 24 && ObjectId.isValid(id)).map(id => new ObjectId(id));
102
+ const [users, profiles] = await Promise.all([ids.length ? db.collection("users").find({
103
+ _id: {
104
+ $in: ids
105
+ }
106
+ }, {
107
+ projection: {
108
+ fullName: 1
109
+ }
110
+ }).toArray() : [], ids.length ? db.collection("profiles").find({
111
+ userId: {
112
+ $in: [...ids, ...ids.map(id => String(id))]
113
+ },
114
+ projectId: String(req.projectId || "")
115
+ }, {
116
+ projection: {
117
+ userId: 1,
118
+ access: 1
119
+ }
120
+ }).toArray() : []]);
121
+ const names = new Map(users.map(user => [String(user._id), user.fullName || ""]));
122
+ const accessByUser = new Map(profiles.map(profile => [String(profile.userId), profile.access]));
123
+ const people = grouped.map(row => {
124
+ const userId = String(row._id || "");
125
+ const name = String(names.get(userId) || "").trim();
126
+ return {
127
+ userId,
128
+ name: name || "Unknown",
129
+ access: accessByUser.has(userId) ? accessByUser.get(userId) : null,
130
+ lastSeen: row.lastSeen,
131
+ pages: row.pages
132
+ };
133
+ });
52
134
  return res.json({
53
135
  success: true,
54
- data: rows
136
+ data: {
137
+ visited: people.length,
138
+ pages,
139
+ people
140
+ }
55
141
  });
56
142
  } catch (error) {
57
143
  console.error("Error listing pageviews:", error);
@@ -114,6 +114,45 @@ function buildPageview({
114
114
  doc
115
115
  };
116
116
  }
117
+ function isPageviewAdmin({
118
+ jwtAccess,
119
+ profileAccess,
120
+ userAccess
121
+ }) {
122
+ const chosen = profileAccess !== undefined && profileAccess !== null && profileAccess !== "" ? profileAccess : userAccess !== undefined && userAccess !== null && userAccess !== "" ? userAccess : jwtAccess;
123
+ return Number(chosen) === 100;
124
+ }
125
+ function summarizeVisitors(rows) {
126
+ const byUser = new Map();
127
+ let pages = 0;
128
+ for (const row of rows || []) {
129
+ pages += 1;
130
+ const userId = String(row && row.userId || "");
131
+ if (!userId) continue;
132
+ const seenAt = row.createdAt ? new Date(row.createdAt) : null;
133
+ const prev = byUser.get(userId);
134
+ if (!prev) {
135
+ byUser.set(userId, {
136
+ userId,
137
+ lastSeen: seenAt,
138
+ pages: 1
139
+ });
140
+ continue;
141
+ }
142
+ prev.pages += 1;
143
+ if (seenAt && (!prev.lastSeen || seenAt > prev.lastSeen)) prev.lastSeen = seenAt;
144
+ }
145
+ const people = [...byUser.values()].sort((a, b) => {
146
+ const left = a.lastSeen ? a.lastSeen.getTime() : 0;
147
+ const right = b.lastSeen ? b.lastSeen.getTime() : 0;
148
+ return right - left;
149
+ });
150
+ return {
151
+ pages,
152
+ visited: people.length,
153
+ people
154
+ };
155
+ }
117
156
  function recentPageviewFilter(projectId, now = new Date()) {
118
157
  return {
119
158
  projectId: String(projectId || ""),
@@ -127,5 +166,7 @@ module.exports = {
127
166
  PAGEVIEW_LIST_LIMIT,
128
167
  PAGEVIEW_LIST_FIELDS,
129
168
  buildPageview,
169
+ isPageviewAdmin,
170
+ summarizeVisitors,
130
171
  recentPageviewFilter
131
172
  };
@@ -3,6 +3,8 @@
3
3
  const {
4
4
  buildPageview,
5
5
  PAGEVIEW_TTL_SECONDS,
6
+ isPageviewAdmin,
7
+ summarizeVisitors,
6
8
  recentPageviewFilter
7
9
  } = require("./track");
8
10
  const projectId = "507f1f77bcf86cd799439011";
@@ -64,6 +66,52 @@ describe("buildPageview", () => {
64
66
  expect(result.doc.referrer).toBeUndefined();
65
67
  });
66
68
  });
69
+ describe("isPageviewAdmin", () => {
70
+ it("allows the project profile or the user record when the token has no access", () => {
71
+ expect(isPageviewAdmin({
72
+ jwtAccess: undefined,
73
+ profileAccess: 100
74
+ })).toBe(true);
75
+ expect(isPageviewAdmin({
76
+ jwtAccess: undefined,
77
+ userAccess: 100
78
+ })).toBe(true);
79
+ expect(isPageviewAdmin({
80
+ jwtAccess: 100
81
+ })).toBe(true);
82
+ });
83
+ it("lets a project profile of 0 override a user record of 100", () => {
84
+ expect(isPageviewAdmin({
85
+ jwtAccess: undefined,
86
+ profileAccess: 0,
87
+ userAccess: 100
88
+ })).toBe(false);
89
+ });
90
+ });
91
+ describe("summarizeVisitors", () => {
92
+ it("collapses a path log into one person and a page count", () => {
93
+ const result = summarizeVisitors([{
94
+ userId: member,
95
+ page: "/login",
96
+ createdAt: new Date("2026-09-29T02:14:40.000Z")
97
+ }, {
98
+ userId: member,
99
+ page: "/my-invoices",
100
+ createdAt: new Date("2026-09-29T02:15:14.000Z")
101
+ }, {
102
+ userId: admin,
103
+ page: "/",
104
+ createdAt: new Date("2026-09-29T02:15:37.000Z")
105
+ }]);
106
+ expect(result.pages).toBe(3);
107
+ expect(result.visited).toBe(2);
108
+ expect(result.people[0].userId).toBe(admin);
109
+ expect(result.people[1]).toMatchObject({
110
+ userId: member,
111
+ pages: 2
112
+ });
113
+ });
114
+ });
67
115
  describe("recentPageviewFilter", () => {
68
116
  it("keeps the last 7 days for one project", () => {
69
117
  const now = new Date("2026-09-29T00:00:00.000Z");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.14.0",
3
+ "version": "4.15.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",