📦 EqualifyEverything / equalify

📄 getAuditTable.ts · 347 lines
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347import { db, event, graphqlQuery, validateShortId } from "#src/utils";

export const getAuditTable = async () => {
  const auditId = (event.queryStringParameters as any).id;
  const page = parseInt((event.queryStringParameters as any).page || "0", 10);
  const pageSize = parseInt(
    (event.queryStringParameters as any).pageSize || "50",
    10
  );
  const contentType = (event.queryStringParameters as any).contentType || "all";
  const sortBy = (event.queryStringParameters as any).sortBy || "created_at";
  const sortOrder = (event.queryStringParameters as any).sortOrder || "desc";

  // Parse multiple filter parameters (comma-separated)
  const tagsParam = (event.queryStringParameters as any).tags || null;
  const categoriesParam =
    (event.queryStringParameters as any).categories || null;
  const statusParam = (event.queryStringParameters as any).status || null;

  const tagFilters = tagsParam ? tagsParam.split(",").filter(Boolean) : [];
  const typeFilters = categoriesParam
    ? categoriesParam.split(",").filter(Boolean)
    : [];

  const searchString = (event.queryStringParameters as any).searchString || "";

  await db.connect();
  const audit = (
    await db.query({
      text: `SELECT * FROM "audits" WHERE "id" = $1`,
      values: [auditId],
    })
  ).rows?.[0];
  await db.clean();

  // Build the where clause with multiple filters
  const whereConditions: any[] = [];

  // Tag filtering (OR condition - blocker has ANY of the selected tags)
  if (tagFilters.length > 0) {
    whereConditions.push({
      blocker_messages: {
        message: {
          message_tags: {
            tag: {
              id: { _in: tagFilters },
            },
          },
        },
      },
    });
  }

  // Category filtering (OR condition - blocker has ANY of the selected categories)
  if (typeFilters.length > 0) {
    whereConditions.push({
      blocker_messages: {
        message: {
          category: { _in: typeFilters },
        },
      },
    });
  }

  // Status filtering ('ignore' field true/false)
  if (statusParam) {
    if (statusParam === "active") {
      whereConditions.push({
        blocker_messages: {
          blocker: {
            _not: {
              ignored_blocker: {
                blocker_id: {
                  _is_null: false,
                },
              },
            },
          },
        },
      });
    } else if (statusParam === "ignored") {
      whereConditions.push({
        blocker_messages: {
          blocker: {
            ignored_blocker: {
              id: {
                _is_null: false,
              },
            },
          },
        },
      });
    }
  }

  // Add search string to where clause
  if (searchString !== "") {
    if (validateShortId(searchString)) {
      // if valid UUID, use that
      whereConditions.push({
        short_id: { _eq: searchString },
      });
    } else {
      // otherwise search URL
      whereConditions.push({
        url: { url: { _ilike: `%${searchString}%` } },
      });
    }
  }

  // Combine all conditions with AND
  const whereClause =
    whereConditions.length > 0 ? { _and: whereConditions } : {};

  // Build order_by clause based on sortBy parameter
  let orderByClause;
  if (sortBy === "url") {
    // Sort by the related url table's url field
    orderByClause = { url: { url: sortOrder } };
  } else {
    // Default to sorting by created_at or other fields on the blocker table
    orderByClause = { created_at: sortOrder };
  }

  // Build where clauses for status counts (excluding status filter)
  // Get Where conditions without ignore conditions
  const baseWhereConditions = whereConditions.filter(
    (cond) =>
      !(
        cond.blocker_messages?.blocker?.ignored_blocker ||
        cond.blocker_messages?.blocker?._not?.ignored_blocker
      )
  );
  const baseWhereClause =
    baseWhereConditions.length > 0 ? { _and: baseWhereConditions } : {};

  const activeWhereClause = {
    _and: [
      ...baseWhereConditions,
      {
        blocker_messages: {
          blocker: {
            _not: {
              ignored_blocker: {
                blocker_id: {
                  _is_null: false,
                },
              },
            },
          },
        },
      },
    ],
  };

  const ignoredWhereClause = {
    _and: [
      ...baseWhereConditions,
      {
        blocker_messages: {
          blocker: {
            ignored_blocker: {
              id: {
                _is_null: false,
              },
            },
          },
        },
      },
    ],
  };

  // Query to get blockers from the latest scan with pagination
  const query = {
    query: `query ($audit_id: uuid!, $limit: Int!, $offset: Int!, $where: blockers_bool_exp!, $order_by: [blockers_order_by!], $baseWhere: blockers_bool_exp!, $activeWhere: blockers_bool_exp!, $ignoredWhere: blockers_bool_exp!) {
  audits_by_pk(id: $audit_id) {
    scans(order_by: {created_at: desc}, limit: 1) {
      id
      created_at
      blockers(where: $where, limit: $limit, offset: $offset, order_by: $order_by) {
        id
        short_id
        created_at
        content
        url_id
        url {
          url
          type
        }
        blocker_messages {
          id
          message {
            id
            content
            category
            message_tags {
              tag {
                id
                content
              }
            }
          }
        }
      }
      blockers_aggregate(where: $where) {
        aggregate {
          count
        }
      }
      all_blockers_count: blockers_aggregate(where: $baseWhere) {
        aggregate {
          count
        }
      }
      active_blockers_count: blockers_aggregate(where: $activeWhere) {
        aggregate {
          count
        }
      }
      ignored_blockers_count: blockers_aggregate(where: $ignoredWhere) {
        aggregate {
          count
        }
      }
    }
  }
  tags(order_by: {content: asc}) {
    id
    content
  }
  messages(order_by: {category: asc}, distinct_on: category) {
    category
  }
}`,
    variables: {
      audit_id: auditId,
      limit: pageSize,
      offset: page * pageSize,
      where: whereClause,
      order_by: [orderByClause],
      baseWhere: baseWhereClause,
      activeWhere: activeWhereClause,
      ignoredWhere: ignoredWhereClause,
    },
  };

  console.log(JSON.stringify({ query }));
  const response = await graphqlQuery(query);
  console.log(JSON.stringify({ response }));

  const latestScan = response.audits_by_pk?.scans?.[0];
  const blockers = latestScan?.blockers || [];
  const totalCount = latestScan?.blockers_aggregate?.aggregate?.count || 0;
  const allBlockersCount =
    latestScan?.all_blockers_count?.aggregate?.count || 0;
  const activeBlockersCount =
    latestScan?.active_blockers_count?.aggregate?.count || 0;
  const ignoredBlockersCount =
    latestScan?.ignored_blockers_count?.aggregate?.count || 0;
  const availableTags = response.tags || [];
  const availableCategories = response.messages || [];

  // Format the blockers data
  let formattedBlockers = blockers.map((blocker) => {
    // Extract tags from blocker_messages -> message -> message_tags -> tag
    const tags = blocker.blocker_messages.flatMap(
      (bm) => bm.message.message_tags?.map((mt) => mt.tag).filter(Boolean) || []
    );

    const uniqueTags = Array.from(
      new Map(tags.map((tag) => [tag.id, tag])).values()
    );

    // Extract categories from blocker_messages -> message -> category
    const categories = blocker.blocker_messages.map(
      (bm) => bm.message.category
    );
    const uniqueCategories = Array.from(new Set(categories));

    // Extract equalified status from blocker_messages -> blocker -> equalified
    /* const equalified = blocker.blocker_messages.length > 0 
            ? blocker.blocker_messages[0].blocker.equalified 
            : false; */

    // Extract message contents
    const messages = blocker.blocker_messages.map(
      (bm) => `[${bm.message.category}] ${bm.message.content}`
    );

    return {
      id: blocker.id,
      short_id: blocker.short_id,
      created_at: blocker.created_at,
      url: blocker.url?.url || blocker.url_id,
      type: blocker.url?.type || "unknown",
      url_id: blocker.url_id,
      content: blocker.content,
      ignore: blocker.ignore,
      //equalified: equalified,
      messages: messages,
      tags: uniqueTags,
      categories: uniqueCategories,
    };
  });

  // filter for content type. We need to do it last because the type field is set by URL, not blocker
  if (
    contentType.toLowerCase() === "html" ||
    contentType.toLowerCase() === "pdf"
  ) {
    formattedBlockers = formattedBlockers.filter((blocker) => {
      return blocker.type.toLowerCase() === contentType.toLowerCase();
    });
  }

  return {
    statusCode: 200,
    headers: { "content-type": "application/json" },
    body: {
      audit_id: auditId,
      audit_name: audit?.name,
      scan_date: latestScan?.created_at,
      blockers: formattedBlockers,
      pagination: {
        page,
        pageSize,
        totalCount,
        totalPages: Math.ceil(totalCount / pageSize),
      },
      statusCounts: {
        all: allBlockersCount,
        active: activeBlockersCount,
        ignored: ignoredBlockersCount,
      },
      availableTags,
      availableCategories: availableCategories
        .map((m: any) => m.category)
        .filter(Boolean),
      filters: {
        tags: tagFilters,
        types: typeFilters,
        status: statusParam,
      },
    },
  };
};