feat(feedback): a third identity mode with one shared colour tag per photo (#1197) (#1208)

* feat(feedback): a third identity mode with one shared colour tag per photo (#1197)

Split out of #1178, where @boergu asked for a colour tag with no identity
dimension at all: not everyone sharing a device's state, but everyone — on any
device — sharing the PHOTO's state. Guest A marks it green, guest B later marks
it orange, and the tag simply becomes orange. One collaboratively-agreed verdict
per photo instead of per-person tallies.

identity_mode gains 'shared'. The mode is scoped to the colour tag: likes,
ratings, comments, favourites and reactions stay per-visitor exactly as in
'simple', because that is what was asked for and widening it would change what
every other control means.

Stored as an ordinary photo_feedback row under a reserved identifier rather
than as a column on photos. That is what keeps the rest of the system working
untouched — the per-colour tally simply has exactly one entry, so
dominant_color_label, color_label_count, the admin colour filter and the
XMP/CSV export that #745 reads all keep their existing shapes, and no consumer
has to learn a second one. The identifier cannot be claimed: real ones are
sha256 hashes or server-minted UUIDs, and the per-guest write path rejects it
outright.

Last write wins, inside a transaction that locks the photo row. Without the
lock two guests tapping different colours in the same instant both read 'no
tag', both insert, and the photo ends up carrying two shared tags — the
per-guest tally this mode exists to remove. Re-sending the colour already on a
photo clears it, from any guest: the same toggle every other colour path uses,
and the only way to remove a tag without inventing a second control.

Switching modes is non-destructive. Existing per-guest labels are left alone
and simply not read while shared is on; the shared tag starts empty rather than
collapsing marks nobody agreed on, and switching back restores every original
exactly. An event can hold both sets, only one of which is live.

The tag stays visible with show_feedback_to_guests off — it arrives through the
per-viewer channel, being the photo's own state rather than someone else's
opinion — while the per-colour tallies stay hidden. The colour filters answer
from it for the same reason, so a gallery with sharing off cannot show colours
on tiles that no filter can find.

Attribution is gone by design, and the settings panel says so before an
operator picks the mode.

Decisions (1), (4) and (5) from the issue were settled up front, as it asked.
Decision (3) turned out not to need anything: guest colour filters already read
my_color_label, and the admin's my_color_labels filters photo_admin_marks
(#1183), not guest identity — so nothing collapses on either side.

* fix(feedback): shared mode saves on Postgres, and dormant labels stay dormant (#1197)

Three findings from external review, all confirmed against source before fixing.

**The mode could not be saved on Postgres at all.** Migration 078 created
identity_mode with a CHECK constraint pinned to ('simple','guest'), guarded on
`client === 'pg'` — so SQLite never has it and no SQLite test can see it, while
the database every default production install runs rejects the new value
outright. Migration 192 drops and re-adds the constraint with 'shared' included;
its down() resets any event using the mode to 'simple' first, or the narrower
constraint could not be restored. Verified against a real Postgres on a scratch
database: the insert fails before, succeeds after, up() is re-runnable, and
down() puts the old constraint back.

**Dormant labels were still being read.** Switching modes is deliberately
non-destructive, which leaves both sets of colour labels in the table with only
one live — and every read that did not say which set it meant kept counting the
other. The per-colour tallies, color_label_count, the admin grid badge, the
XMP/CSV export, both admin colour filters and the guest colour filter all saw
labels the mode does not show; switching back exposed the shared row as an
anonymous other guest's dot. The settings panel promises these are 'kept but not
shown', and that has to mean every surface, not just the badge. Scoped at the
source — the two count helpers resolve the mode themselves — so the admin grid
and the export are fixed without touching either.

**The create form's identity mode was dropped.** CreateEventPage has always
rendered the chooser and the create route never read it, so a gallery created as
'guest' came out 'simple' and had to be set again on the event afterwards. A
pre-existing bug that adding a third option made worse; threaded through now,
which fixes it for all three modes.

Six regression tests, each verified to fail against the un-fixed code.

* fix(feedback): keep every colour surface consistent across a mode change (#1197)

Second review round, four findings, all confirmed in source first.

**Stored counters went stale on a mode switch.** photos.color_label_count is
denormalized and recomputed on feedback writes, so changing identity_mode —
which changes nothing about the rows, only which of them are live — left the
old mode's totals on the tiles, the admin grid and the filter summary until
each photo happened to be touched again. On a finished gallery that is never.
Recounted for the event when the mode actually changes, as two statements
rather than a per-photo recompute: four of the five counters cannot have moved.

**Duplicating an event dropped the mode**, the same shape as the create-form
bug from the last round — a gallery cloned to reuse its proofing setup came
back in 'simple'.

**The event feedback summary counted dormant labels**, inflating total_feedback
in the admin analytics and the guest /feedback-summary while every other
surface hid them.

**The swatch trusted its optimistic guess over the server.** In shared mode the
tag belongs to the photo, so another guest can move it between this viewer's
last read and their click: a viewer still showing green clicks green, the
server sets green because the tag had become red meanwhile, and the optimistic
'same colour, so clear' blanked the swatch against a server that holds one. The
response already says which happened, so it is used. The per-guest modes are
unaffected — only the guest can move their own label, so guess and answer
always agreed there.

Three regression tests, each verified to fail against the un-fixed code.

* fix(feedback): shared tag is not a participant, and the keyboard path reconciles too (#1197)

Third review round, two findings.

**feedback_count counted the shared tag as a guest.** It is COUNT(DISTINCT
guest identity) across all feedback types, and the reserved identifier looked
like a person: a photo with one rating and a shared tag reported two. The
column is exported as rating_count (photoExportService), so merely tagging a
photo inflated its rating count in the CSV and JSON exports.

**The lightbox keyboard path still trusted its own guess.** The reconciliation
from the last round covered clicks through PhotoColorLabels, but the proofing
shortcuts call PhotoLightbox.submitColorLabel directly and set local state from
a locally computed toggle. That is the path a proofing client actually uses, so
it had the divergence the previous fix was for: another guest moves the tag,
this viewer presses the key, the server sets a colour and the swatch blanks.
Both branches now read the outcome off the response.

One regression test, verified to fail against the un-fixed code.

* fix(feedback): identity-mode lookup must survive a migration-time caller (#1197)

updatePhotoFeedbackStats is called from migrations as well as from the request
path — migration 186's duplicate-photo dedupe (#1162) recomputes the survivor's
totals — and a migration runs against a half-built schema where
event_feedback_settings need not exist yet. The new inner join threw there,
which took the whole stats update down with it, so the reparented rows were
never counted and eight assertions in the 186 suite failed.

Falls back to 'simple', which is the right answer rather than merely a safe
one: an install with no feedback settings table has no event in shared mode, so
the non-shared scope is exactly correct.

Caught by CI, not by me — I had been running affected suites rather than the
full one after each review round.

* fix(feedback): atomic shared-tag write, scoped feedback list, safe PG fallback (#1197)

Round 4 of external review, and one of the three is about the fix I made for
the CI failure two rounds ago.

**The identity-mode fallback could poison a Postgres transaction.** The join
was wrapped in try/catch so a migration-time caller with a half-built schema
would fall back to 'simple'. On Postgres a failed statement aborts the entire
transaction, so catching it and carrying on left the caller's trx poisoned and
the aggregate that follows failed with 'current transaction is aborted' —
defeating the very compatibility the fallback was added for. It now asks
whether the table exists before issuing the join, which is safe to ask and
aborts nothing. Memoised once true, since a table does not un-create itself and
this sits on the feedback write path.

**The shared-tag stats were recomputed after the commit.** A failure there
returned 500 for a tag that had already been written, so the client reverted
its swatch and the next tap on the same colour toggled the committed tag off
instead of setting it. Two concurrent writers could also race their aggregate
updates. Recomputed inside the transaction now, while the photo row is still
locked.

**The raw feedback list still carried both label sets.** Only the tallies and
my_feedback had been scoped, so a dormant per-guest label was still visible to
anyone reading the list — and with sharing off it came back flagged is_mine.
getPhotoFeedback now filters colour labels to the active set.

One test for the list; the migration suite that caught the original CI
regression still passes.

---------

Co-authored-by: Paul Nothaft <[email protected]>
This commit is contained in:
Paul Nothaft
2026-08-28 08:19:41 +02:00
committed by GitHub
co-authored by Paul Nothaft
parent 71eaf25d94
commit 22e00f80b6
26 changed files with 1309 additions and 53 deletions
+338 -12
View File
@@ -2,7 +2,7 @@ const { db, logActivity } = require('../database/db');
const logger = require('../utils/logger');
const { formatBoolean } = require('../utils/dbCompat');
const { REACTION_EMOJIS } = require('../constants/reactions');
const { isValidColorLabel } = require('../constants/colorLabels');
const { isValidColorLabel, SHARED_COLOR_LABEL_IDENTITY } = require('../constants/colorLabels');
const { resolveEventFeedbackDefaults, DEFAULT_KEYBIND_MODE, KEYBIND_MODES } = require('./feedbackDefaults');
// Every writable column on event_feedback_settings (#1030). The admin form
@@ -40,6 +40,46 @@ const SINGLE_VALUE_COLUMNS = {
color_label: 'color_label',
};
/**
* Is this write the identity-less shared colour tag (#1197)?
*
* Narrow on purpose. 'shared' is a mode for the colour tag, not for the event:
* a like or a rating in a shared-mode gallery is still that guest's own, so
* only feedback_type='color_label' takes the reserved slot. Everything else
* falls through to the per-guest path unchanged.
*/
// Set once the settings table has been seen. Module scope on purpose: the
// answer is a property of the schema, not of a request.
let settingsTableKnownToExist = false;
function isSharedColorLabel(identityMode, feedbackType) {
return identityMode === 'shared' && feedbackType === 'color_label';
}
/**
* Narrow a colour-label query to the rows the event's current mode actually
* uses (#1197).
*
* Switching modes is deliberately non-destructive: per-guest labels are kept
* when an event moves to shared, and the shared row is kept when it moves
* back. That leaves both sets in the table at once with only one of them live,
* so every read has to say which it means. Without this the dormant set is
* still counted, still tallied in the lightbox, still matches the admin colour
* filter and can still decide the exported dominant colour — the labels would
* be "hidden" only on the badge, which is not what the settings panel promises.
*
* The NULL arm matters: rows written before migration 078 carry no identifier
* at all, and they are per-guest rows, so they belong to the non-shared set.
*/
function scopeColorLabelsToMode(query, identityMode, column = 'guest_identifier') {
if (identityMode === 'shared') {
return query.where(column, SHARED_COLOR_LABEL_IDENTITY);
}
return query.where(function () {
this.whereNot(column, SHARED_COLOR_LABEL_IDENTITY).orWhereNull(column);
});
}
function pickSettingsColumns(settings) {
const picked = {};
for (const column of FEEDBACK_SETTINGS_COLUMNS) {
@@ -111,6 +151,16 @@ class FeedbackService {
const writable = pickSettingsColumns(settings);
// Changing identity_mode changes which colour labels are live, and
// photos.color_label_count is denormalized — recomputed on a feedback
// write, not on a settings write (#1197). Without this the tiles, the
// admin grid and PhotoFilterBuilder.getSummary keep reporting the
// previous mode's totals until each photo happens to receive another
// mutation, which on a finished gallery is never.
const modeChanged = Object.prototype.hasOwnProperty.call(writable, 'identity_mode')
&& existing
&& (existing.identity_mode || 'simple') !== (writable.identity_mode || 'simple');
if (existing) {
await db('event_feedback_settings')
.where('event_id', eventId)
@@ -127,6 +177,10 @@ class FeedbackService {
});
}
if (modeChanged) {
await this.recountEventColorLabels(eventId, writable.identity_mode || 'simple');
}
await logActivity('feedback_settings_updated', writable, eventId);
return this.getEventFeedbackSettings(eventId);
@@ -162,6 +216,195 @@ class FeedbackService {
return parseInt(result?.count, 10) || 0;
}
/**
* Write the photo's one shared colour tag (#1197).
*
* Last write wins, and re-sending the colour that is already there clears it
* — the same toggle every other colour path uses, and the only way to remove
* a tag without inventing a second control for it. Any guest can do either:
* that is the mode, not a hole in it.
*
* The transaction plus the lock on the photo row is what makes "last write
* wins" mean one value rather than two. Without it, two guests tapping
* different colours in the same instant both read "no tag", both insert, and
* the photo ends up carrying two shared tags at once — which is exactly the
* per-guest tally this mode exists to get rid of. SQLite ignores forUpdate
* but serialises writers anyway; on Postgres it is doing real work.
*
* No guest_name, guest_email or guest_id is stored. Attribution is gone by
* design here — the tag is the photo's state, not a person's opinion — so
* the admin feedback list shows a shared tag with no name against it.
*/
async submitSharedColorLabel(photoId, eventId, colorLabel, { ip_address, user_agent } = {}) {
const nowIso = () => new Date().toISOString();
let outcome;
await db.transaction(async (trx) => {
await trx('photos').where({ id: photoId }).forUpdate().first();
// Visible rows only, like every other single-value path (#1150): a
// hidden tag is the admin's moderation record, and a guest writing over
// it must create a fresh visible row rather than quietly unhide it. The
// unhide path in moderateFeedback collapses the pair back to one.
const sharedScope = () => trx('photo_feedback').where({
photo_id: photoId,
event_id: eventId,
feedback_type: 'color_label',
guest_identifier: SHARED_COLOR_LABEL_IDENTITY,
is_hidden: false,
});
const existing = await sharedScope().first();
if (existing && existing.color_label === colorLabel) {
await sharedScope().delete();
outcome = { removed: true, shared: true };
return;
}
if (existing) {
// Converge on one row, the same defence the per-guest path uses: if a
// race ever did leave duplicates behind, the next tap collapses them.
await sharedScope().whereNot('id', existing.id).delete();
await trx('photo_feedback')
.where('id', existing.id)
.update({ color_label: colorLabel, updated_at: nowIso() });
outcome = { id: existing.id, updated: true, shared: true };
return;
}
const inserted = await trx('photo_feedback').insert({
photo_id: photoId,
event_id: eventId,
feedback_type: 'color_label',
color_label: colorLabel,
guest_identifier: SHARED_COLOR_LABEL_IDENTITY,
guest_id: null,
guest_name: null,
guest_email: null,
ip_address,
user_agent,
is_approved: true,
created_at: nowIso(),
updated_at: nowIso(),
}).returning('id');
outcome = { id: inserted[0]?.id || inserted[0], created: true, shared: true };
// Inside the transaction, while the photo row is still locked (#1197
// review). Recomputing after the commit meant a failure there returned
// 500 for a tag that HAD been written — so the client reverted its
// swatch, the next tap on the same colour toggled the committed tag off
// instead of setting it, and the counters stayed stale meanwhile. It
// also let two concurrent writers race their aggregate updates.
await this.updatePhotoFeedbackStats(photoId, trx);
});
return outcome;
}
/**
* Rebuild photos.color_label_count for a whole event against the set the
* given mode makes live (#1197).
*
* Two statements rather than updatePhotoFeedbackStats per photo: a mode
* switch on a 5,000-photo gallery would otherwise be 5,000 aggregate queries
* and 5,000 updates, for a counter that four of its five components cannot
* have changed. Zero everything first, then write the photos that actually
* carry a live label — usually a small fraction of the event.
*/
async recountEventColorLabels(eventId, identityMode) {
await db.transaction(async (trx) => {
await trx('photos').where({ event_id: eventId }).update({ color_label_count: 0 });
const rows = await scopeColorLabelsToMode(
trx('photo_feedback')
.where({ event_id: eventId, feedback_type: 'color_label', is_hidden: false }),
identityMode,
)
.groupBy('photo_id')
.select('photo_id')
.count('id as count');
for (const row of rows) {
await trx('photos')
.where({ id: row.photo_id })
.update({ color_label_count: Number(row.count) || 0 });
}
});
}
/**
* The identity mode of the event a photo belongs to (#1197).
*
* One small join rather than threading the mode through every caller of
* updatePhotoFeedbackStats — including the duplicate-photo dedupe (#1162),
* which recomputes totals from a background service with no request settings
* in hand. Falls back to 'simple' for a photo whose event has no feedback
* settings row, which is the same default getEventFeedbackSettings applies.
*/
async getIdentityModeForPhoto(photoId, trx = db) {
try {
// Asked BEFORE the join, not recovered from afterwards (#1197 review).
// On Postgres a failed statement aborts the whole transaction, so
// catching the error and carrying on left the caller's trx poisoned:
// the aggregate and update that follow would fail with "current
// transaction is aborted", which is exactly the migration-time path the
// fallback exists to support. A metadata check is safe to ask and does
// not abort anything.
//
// Memoised once true because a table does not un-create itself, and this
// sits on the feedback write path; a false answer is not cached, so a
// migration that creates the table later is picked up.
if (!settingsTableKnownToExist) {
settingsTableKnownToExist = await trx.schema.hasTable('event_feedback_settings');
if (!settingsTableKnownToExist) return 'simple';
}
const row = await trx('photos')
.join('event_feedback_settings', 'photos.event_id', 'event_feedback_settings.event_id')
.where('photos.id', photoId)
.select('event_feedback_settings.identity_mode')
.first();
return row?.identity_mode || 'simple';
} catch (error) {
// updatePhotoFeedbackStats is called from MIGRATIONS as well as from the
// request path — migration 186's duplicate-photo dedupe (#1162)
// recomputes the survivor's totals — and a migration runs against a
// half-built schema where event_feedback_settings need not exist yet.
// Letting that throw took the whole stats update down with it, so the
// reparented rows were never counted.
//
// 'simple' is the right answer in that situation rather than merely a
// safe one: an install with no feedback settings table has no event in
// shared mode, so the non-shared scope is exactly correct.
logger.debug(`Identity mode lookup for photo ${photoId} fell back to 'simple': ${error.message}`);
return 'simple';
}
}
/**
* The shared tag for a set of photos (#1197), as { [photoId]: colour }.
*
* One query for the whole page — the gallery list renders hundreds of tiles
* and a per-photo lookup would be a query each.
*/
async getSharedColorLabels(eventId, photoIds) {
if (!photoIds || photoIds.length === 0) return {};
const rows = await db('photo_feedback')
.where({
event_id: eventId,
feedback_type: 'color_label',
guest_identifier: SHARED_COLOR_LABEL_IDENTITY,
is_hidden: false,
})
.whereIn('photo_id', photoIds)
.whereNotNull('color_label')
.select('photo_id', 'color_label');
const byPhoto = {};
rows.forEach((row) => { byPhoto[row.photo_id] = row.color_label; });
return byPhoto;
}
async submitFeedback(photoId, eventId, feedbackData, guestIdentifier) {
try {
const { feedback_type, rating, comment_text, reaction, color_label, guest_name, guest_email, ip_address, user_agent, guest_id } = feedbackData;
@@ -182,6 +425,24 @@ class FeedbackService {
throw new Error('Invalid color label');
}
// The shared tag (#1197) leaves before any of the per-guest machinery
// below runs: none of it applies to a row that belongs to the photo
// rather than to a person.
if (isSharedColorLabel(feedbackData.identity_mode, feedback_type)) {
return await this.submitSharedColorLabel(photoId, eventId, color_label, {
ip_address,
user_agent,
});
}
// Belt and braces: nothing but the branch above may write the reserved
// slot. If some future caller ever passed it as a guest identifier, a
// per-guest write would land on the photo's shared tag and every guest
// in the gallery would see it as their own.
if (guestIdentifier === SHARED_COLOR_LABEL_IDENTITY) {
throw new Error('Reserved guest identifier');
}
// Rating 0 clears the guest's rating (#884). Only the explicit zero
// sentinel (0, or "0" from callers that skip the route validator's
// toInt) triggers the destructive path — malformed input (undefined,
@@ -395,6 +656,22 @@ class FeedbackService {
if (options.approved_only) {
query.where('is_approved', true);
}
// Colour labels belong to one of two sets, and only one is live (#1197
// review). Without this the raw feedback list handed back both — dormant
// per-guest rows while the event is in shared mode, and the reserved
// shared row after switching away — even though the settings panel
// promises the other set is not shown. With sharing off it was worse:
// the caller's own dormant row came back flagged is_mine.
if (options.identity_mode) {
query.where(function () {
this.whereNot('feedback_type', 'color_label');
this.orWhere(function () {
this.where('feedback_type', 'color_label');
scopeColorLabelsToMode(this, options.identity_mode);
});
});
}
if (!options.include_hidden) {
query.where('is_hidden', false);
@@ -426,6 +703,7 @@ class FeedbackService {
.orderBy('average_rating', 'desc')
.orderBy('like_count', 'desc');
const sharedColors = (await this.getEventFeedbackSettings(eventId)).identity_mode === 'shared';
const totalStats = await db('photo_feedback')
.where('event_id', eventId)
// Hidden rows do not count, the same rule the photo counters above
@@ -440,7 +718,19 @@ class FeedbackService {
db.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as total_comments', ['comment']),
db.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as total_favorites', ['favorite']),
db.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as total_reactions', ['reaction']),
db.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as total_color_labels', ['color_label'])
// Scoped to the live colour-label set (#1197), like every other
// colour read. Unscoped, a dormant set left behind by a mode switch
// inflated total_feedback in the admin analytics and the guest
// /feedback-summary while every other surface hid it.
sharedColors
? db.raw(
'COUNT(CASE WHEN feedback_type = ? AND guest_identifier = ? THEN 1 END) as total_color_labels',
['color_label', SHARED_COLOR_LABEL_IDENTITY],
)
: db.raw(
'COUNT(CASE WHEN feedback_type = ? AND (guest_identifier IS NULL OR guest_identifier <> ?) THEN 1 END) as total_color_labels',
['color_label', SHARED_COLOR_LABEL_IDENTITY],
)
)
.first();
@@ -483,11 +773,19 @@ class FeedbackService {
* Per-colour tallies for one photo (#1044) — the colour-label sibling of
* getPhotoReactionCounts.
*/
async getPhotoColorLabelCounts(photoId) {
async getPhotoColorLabelCounts(photoId, identityMode = undefined) {
try {
const rows = await db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'color_label' })
.where('is_hidden', false)
// Resolved here rather than pushed onto every caller (#1197): the admin
// grid, the XMP export and the lightbox all reach colour labels through
// this helper and its event-wide sibling, so scoping them at the source
// is what keeps a dormant label out of all three at once.
const mode = identityMode ?? await this.getIdentityModeForPhoto(photoId);
const rows = await scopeColorLabelsToMode(
db('photo_feedback')
.where({ photo_id: photoId, feedback_type: 'color_label' })
.where('is_hidden', false),
mode,
)
.groupBy('color_label')
.select('color_label')
.count('id as count');
@@ -512,11 +810,15 @@ class FeedbackService {
* @param {number[]} [photoIds] - optional narrowing to the visible page
* @returns {Promise<Object>} { [photoId]: { green: 2, red: 1 } }
*/
async getEventColorLabelCounts(eventId, photoIds = null) {
async getEventColorLabelCounts(eventId, photoIds = null, identityMode = undefined) {
try {
const query = db('photo_feedback')
.where({ event_id: eventId, feedback_type: 'color_label' })
.where('is_hidden', false)
const mode = identityMode ?? (await this.getEventFeedbackSettings(eventId)).identity_mode;
const query = scopeColorLabelsToMode(
db('photo_feedback')
.where({ event_id: eventId, feedback_type: 'color_label' })
.where('is_hidden', false),
mode,
)
.groupBy('photo_id', 'color_label')
.select('photo_id', 'color_label')
.count('id as count');
@@ -550,6 +852,20 @@ class FeedbackService {
*/
async updatePhotoFeedbackStats(photoId, trx = db) {
try {
// Which colour labels are live for this photo's event (#1197). The other
// four counters are identity-agnostic; only the colour tag has two
// possible sets sitting in the table at once.
const sharedColors = (await this.getIdentityModeForPhoto(photoId, trx)) === 'shared';
const colorLabelCount = sharedColors
? trx.raw(
'COUNT(CASE WHEN feedback_type = ? AND guest_identifier = ? THEN 1 END) as color_label_count',
['color_label', SHARED_COLOR_LABEL_IDENTITY],
)
: trx.raw(
'COUNT(CASE WHEN feedback_type = ? AND (guest_identifier IS NULL OR guest_identifier <> ?) THEN 1 END) as color_label_count',
['color_label', SHARED_COLOR_LABEL_IDENTITY],
);
// Get aggregated stats
const stats = await trx('photo_feedback')
.where('photo_id', photoId)
@@ -559,9 +875,19 @@ class FeedbackService {
trx.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as like_count', ['like']),
trx.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as favorite_count', ['favorite']),
trx.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as reaction_count', ['reaction']),
trx.raw('COUNT(CASE WHEN feedback_type = ? THEN 1 END) as color_label_count', ['color_label']),
colorLabelCount,
trx.raw('AVG(CASE WHEN feedback_type = ? THEN rating END) as average_rating', ['rating']),
trx.raw('COUNT(DISTINCT COALESCE(CAST(guest_id AS VARCHAR), guest_identifier)) as feedback_count')
// The shared tag is not a participant (#1197). It carries the
// reserved identifier rather than a person's, so counting it here
// added a phantom guest: a photo with one rating and a shared tag
// reported two, and this column is exported as `rating_count` in the
// CSV/JSON export (photoExportService.js) — so merely tagging a
// photo inflated its rating count.
trx.raw(
'COUNT(DISTINCT CASE WHEN guest_identifier IS NULL OR guest_identifier <> ? '
+ 'THEN COALESCE(CAST(guest_id AS VARCHAR), guest_identifier) END) as feedback_count',
[SHARED_COLOR_LABEL_IDENTITY],
)
)
.first();