[backend] Reset poll votes when choices change on note edit

This commit is contained in:
Laura Hausmann 2023-11-04 23:16:26 +01:00
parent 8b78709378
commit 35c75bbebf
Signed by: zotan
GPG key ID: D044E84C5BE01605
2 changed files with 73 additions and 50 deletions

View file

@ -25,6 +25,7 @@ import {
Notes,
NoteEdits,
DriveFiles,
PollVotes,
} from "@/models/index.js";
import type { IMentionedRemoteUsers, Note } from "@/models/entities/note.js";
import type { IObject, IPost } from "../type.js";
@ -710,11 +711,14 @@ export async function updateNote(value: string | IObject, resolver?: Resolver) {
userHost: actor.host,
});
updating = true;
} else if (
} else {
const choicesChanged = JSON.stringify(dbPoll.choices) !== JSON.stringify(poll.choices);
if (
dbPoll.multiple !== poll.multiple ||
dbPoll.expiresAt !== poll.expiresAt ||
dbPoll.noteVisibility !== note.visibility ||
JSON.stringify(dbPoll.choices) !== JSON.stringify(poll.choices)
choicesChanged
) {
await Polls.update(
{ noteId: note.id },
@ -727,6 +731,12 @@ export async function updateNote(value: string | IObject, resolver?: Resolver) {
note.visibility === "hidden" ? "home" : note.visibility,
},
);
// Reset votes
if (choicesChanged) {
await PollVotes.delete({ noteId: dbPoll.noteId });
}
updating = true;
} else {
for (let i = 0; i < poll.choices.length; i++) {
@ -738,6 +748,7 @@ export async function updateNote(value: string | IObject, resolver?: Resolver) {
}
}
}
}
// Update Note
if (notEmpty(update)) {

View file

@ -13,7 +13,9 @@ import {
Users,
Notes,
UserProfiles,
Polls, NoteEdits,
Polls,
NoteEdits,
PollVotes,
} from "@/models/index.js";
import type { DriveFile } from "@/models/entities/drive-file.js";
import { In } from "typeorm";
@ -121,23 +123,32 @@ export default async function (
userHost: user.host,
});
publishing = true;
} else if (
} else {
const choicesChanged = JSON.stringify(dbPoll.choices) !== JSON.stringify(data.poll.choices);
if (
dbPoll.multiple !== data.poll.multiple ||
dbPoll.expiresAt !== data.poll.expiresAt ||
dbPoll.noteVisibility !== note.visibility ||
JSON.stringify(dbPoll.choices) !== JSON.stringify(data.poll.choices)
choicesChanged
) {
await Polls.update(
{ noteId: note.id },
{
choices: data.poll?.choices,
multiple: data.poll?.multiple,
votes: data.poll?.votes,
votes: choicesChanged ? new Array(data.poll.choices.length).fill(0) : data.poll?.votes,
expiresAt: data.poll?.expiresAt,
noteVisibility:
note.visibility === "hidden" ? "home" : note.visibility,
},
);
// Reset votes
if (JSON.stringify(dbPoll.choices) !== JSON.stringify(data.poll.choices)) {
await PollVotes.delete({ noteId: dbPoll.noteId });
}
publishing = true;
} else {
for (let i = 0; i < data.poll.choices.length; i++) {
@ -149,6 +160,7 @@ export default async function (
}
}
}
}
if (notEmpty(update)) {
update.updatedAt = new Date();