Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ DevOrbit was built in six sprints. Sprint 2 was split into pairs (one backend an

| Part | Task | What we built |
|---|---|---|
| M2 | Edit and delete DMs | In a direct conversation, hover your own message (always shown on touch screens) for **Edit** and **Delete**. An edited message shows *edited*; a deleted one stays in place as *Message deleted* for both people (its text is removed from the database), after a confirmation. The other person's messages cannot be changed: the API answers **403**. Changes appear live on both sides (`dm:updated`) and in the inbox line. `PATCH` / `DELETE /api/direct-messages/:conversationId/messages/:messageId` |
| M2 | Sent / Seen | Each of your messages shows **Sent**, then **Seen** once the other person has opened the conversation. Based on the read time already saved per person in the conversation, so it survives reloads; the sender is told live (`dm:seen`). Messages also carry `status`, and conversations `otherReadAt`. Messages from before Sprint 7 work unchanged |
| M7 | Transfer ownership | The Owner makes another member the Owner (crown button in Team & roles, after confirming) and becomes an Admin, in one step, so a project always has exactly one Owner. The former Owner can then leave. Logged in the activity feed; both people's open pages switch role live. `POST /api/projects/:id/transfer-ownership` |
| M7 | Overdue on the dashboard (FR-15) | The project Dashboard tab now also shows **overdue** tasks (open, due day passed), most overdue first with *N days overdue*, using the same rule as project health. Every member sees it |
| M7 | D7 | The Dashboard's progress card shows the real **weekly goal**: *X of Y done* for your tasks due this week (Mon–Sun, UTC), instead of the fixed "4 of 5". `GET /api/tasks/stats` returns `weekGoal` |
73 changes: 70 additions & 3 deletions backend/src/lib/directMessageRules.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,24 @@ export const DM_MESSAGES = {
empty: 'Message cannot be empty.',
tooLong: `Message must be ${DM_BODY_MAX.toLocaleString('en-US')} characters or fewer.`,
tooFast: 'You are sending messages too quickly. Wait a moment and try again.',
// [Sprint 7 · M2] Edit and delete your own direct messages
invalidMessage: 'Invalid message ID.',
messageNotFound: 'Message not found.',
notSender: 'You can only edit or delete your own messages.',
editDeleted: 'This message was deleted, so it can no longer be edited.',
edited: 'Message updated.',
unchanged: 'Nothing changed.',
deleted: 'Message deleted.',
alreadyDeleted: 'This message was already deleted.',
};

// [Sprint 7 · M2] What a deleted message shows instead of its text (in the conversation and the inbox).
export const DM_DELETED_TEXT = 'Message deleted';

// [Sprint 7 · M2] Delivery status of my own messages: 'sent' until the other person has opened the
// conversation after it arrived, then 'seen'.
export const DM_STATUS = Object.freeze({ sent: 'sent', seen: 'seen' });

export const idOf = (value) => String(value?._id || value || '');

// One conversation per pair of users, whoever opens it first: "a:b" with the smaller ID first.
Expand Down Expand Up @@ -98,19 +114,66 @@ export function userView(user) {
return { _id: idOf(user), name: user.name, username: user.username || '', avatarUrl: user.avatarUrl || '' };
}

export function messageView(message) {
/*
* [Sprint 7 · M2] true when the message was sent before (or at) the moment the other person last read the
* conversation, i.e. they have seen it. `readAt` comes from conversation.reads (readAtFor), which only moves
* forward, so once a message is seen it stays seen.
*/
export function isSeenAt(message, readAt) {
if (!message?.createdAt || !readAt) return false;
const sent = new Date(message.createdAt).getTime();
const read = new Date(readAt).getTime();
return Number.isFinite(sent) && Number.isFinite(read) && sent <= read;
}

export function isMessageSender(message, userId) {
const sender = idOf(message?.sender);
return Boolean(sender) && sender === idOf(userId);
}

/*
* One message as the browser sees it:
* { _id, conversation, sender, body, createdAt, edited, editedAt, deleted, deletedAt, status }
* [Sprint 7 · M2]
* - deleted: the text is never sent again (body ''); the browser shows "Message deleted" in its place.
* - edited / editedAt: the sender changed the text; shown as "edited". A deleted message is not "edited".
* - status: only on the viewer's own messages: 'sent' or 'seen' (otherReadAt = when the other person last
* read the conversation). null on the other person's messages, and when no viewer is given.
* Messages saved before Sprint 7 (no editedAt / deletedAt) come out as not edited and not deleted.
*/
export function messageView(message, { viewerId = null, otherReadAt = null } = {}) {
const deleted = Boolean(message.deletedAt);
const mine = Boolean(viewerId) && isMessageSender(message, viewerId);
let status = null;
if (mine) status = isSeenAt(message, otherReadAt) ? DM_STATUS.seen : DM_STATUS.sent;
return {
_id: idOf(message),
conversation: idOf(message.conversation),
sender: userView(message.sender),
body: message.body,
body: deleted ? '' : message.body,
createdAt: message.createdAt,
edited: !deleted && Boolean(message.editedAt),
editedAt: deleted ? null : message.editedAt || null,
deleted,
deletedAt: message.deletedAt || null,
status,
};
}

// [Sprint 7 · M2] The inbox line for a message: its text, or "Message deleted".
export function messagePreview(message) {
return message?.deletedAt ? DM_DELETED_TEXT : previewOf(message?.body);
}

// [Sprint 7 · M2] When the other person (not `meId`) last read the conversation, or null.
export function otherReadAtFor(conversation, meId) {
const other = otherParticipant(conversation, meId);
return other ? readAtFor(conversation, other) : null;
}

/*
* One inbox row / conversation header, as seen by `meId`:
* { _id, otherUser, lastMessage: { preview, at, fromMe } | null, unreadCount, activityAt, createdAt }
* { _id, otherUser, lastMessage: { preview, at, fromMe } | null, unreadCount, otherReadAt, activityAt, createdAt }
* The two participants each get their own view (different otherUser and unreadCount).
*/
export function conversationView(conversation, meId, unreadCount = 0) {
Expand All @@ -126,6 +189,8 @@ export function conversationView(conversation, meId, unreadCount = 0) {
}
: null,
unreadCount: Number.isFinite(count) && count > 0 ? Math.floor(count) : 0,
// [Sprint 7 · M2] When the other person last read it: my messages up to this time show "Seen".
otherReadAt: otherReadAtFor(conversation, meId),
activityAt: conversation.activityAt || conversation.createdAt || null,
createdAt: conversation.createdAt || null,
};
Expand Down Expand Up @@ -167,5 +232,7 @@ export function createSendLimiter({ limit = DM_SEND_LIMIT, windowMs = DM_SEND_WI
* Small pure helpers for direct messages (US-19): one key per pair of users,
* message checks (text, not empty, at most 4,000 characters), inbox previews,
* the safe views sent to the browser and the per-user send limit.
* [Sprint 7 · M2] Also: edited / deleted messages ("edited", "Message deleted")
* and the Sent / Seen status of the viewer's own messages.
* ---------------------------------------------------------------------------
*/
152 changes: 141 additions & 11 deletions backend/src/lib/directMessages.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import {
conversationView,
idOf,
mayHaveUnread,
messagePreview,
messageView,
otherParticipant,
otherReadAtFor,
pairKeyOf,
previewOf,
readAtFor,
Expand Down Expand Up @@ -58,7 +60,8 @@ export async function openConversation(meId, otherId) {
export async function unreadCountFor(conversation, userId) {
if (!mayHaveUnread(conversation, userId)) return 0;
const readAt = readAtFor(conversation, userId);
const filter = { conversation: conversation._id, sender: { $ne: objectId(userId) } };
// [Sprint 7 · M2] A message deleted before it was read no longer counts as unread.
const filter = { conversation: conversation._id, sender: { $ne: objectId(userId) }, deletedAt: null };
if (readAt) filter.createdAt = { $gt: readAt };
return DirectMessage.countDocuments(filter);
}
Expand Down Expand Up @@ -93,9 +96,11 @@ export async function inboxFor(userId) {
/*
* One page of messages, oldest first, like project chat. `before` = the ID of the oldest message the
* browser already has; ties on the same millisecond are broken by ID so no message is skipped or repeated.
* -> { messages, nextBefore } or null when `before` is not a message of this conversation.
* [Sprint 7 · M2] `viewerId` = who is reading: their own messages get status 'sent' / 'seen', and the page
* carries otherReadAt (when the other person last read) so the browser can keep the marks up to date.
* -> { messages, nextBefore, otherReadAt } or null when `before` is not a message of this conversation.
*/
export async function messagePage(conversation, { limit, before } = {}) {
export async function messagePage(conversation, { limit, before, viewerId = null } = {}) {
const filter = { conversation: conversation._id };
if (before) {
const anchor = await DirectMessage.findOne({ _id: before, conversation: conversation._id }).select('_id createdAt').lean();
Expand All @@ -109,23 +114,39 @@ export async function messagePage(conversation, { limit, before } = {}) {
.lean();
const page = rows.slice(0, limit);
const nextBefore = rows.length > limit ? idOf(page[page.length - 1]) : null;
return { messages: page.reverse().map(messageView), nextBefore };
const otherReadAt = viewerId ? otherReadAtFor(conversation, viewerId) : null;
return {
messages: page.reverse().map((message) => messageView(message, { viewerId, otherReadAt })),
nextBefore,
otherReadAt,
};
}

/*
* Marks everything up to the newest message as read for this user. $max: a slow request can never move
* the read time backwards. Tells the user's other tabs, so their badges drop too.
* -> { unreadCount: 0, unreadTotal }
* [Sprint 7 · M2] The read time is saved in the conversation (reads.<userId>), so "Seen" survives reloads.
* The other person gets 'dm:seen' { conversationId, readAt } at once: their messages sent up to readAt
* turn from "Sent" to "Seen".
* -> { unreadCount: 0, unreadTotal } (the same answer as in Sprint 6)
*/
export async function markRead(conversation, userId) {
let readAt = readAtFor(conversation, userId);
if (conversation.lastMessageAt) {
await DirectConversation.updateOne(
const updated = await DirectConversation.findOneAndUpdate(
{ _id: conversation._id },
{ $max: { [`reads.${idOf(userId)}`]: new Date(conversation.lastMessageAt) } }
);
{ $max: { [`reads.${idOf(userId)}`]: new Date(conversation.lastMessageAt) } },
{ new: true }
)
.select('reads')
.lean();
readAt = readAtFor(updated, userId) || readAt;
}
const unreadTotal = await unreadTotalFor(userId);
emitToUser(userId, 'dm:read', { conversationId: idOf(conversation), unreadTotal });
const conversationId = idOf(conversation);
emitToUser(userId, 'dm:read', { conversationId, unreadTotal });
const other = otherParticipant(conversation, userId);
if (other && readAt) emitToUser(idOf(other), 'dm:seen', { conversationId, readAt });
return { unreadCount: 0, unreadTotal };
}

Expand Down Expand Up @@ -155,7 +176,9 @@ export async function sendMessage(conversation, senderId, body) {
DirectConversation.findById(conversation._id).populate('participants', DM_USER_FIELDS).lean(),
DirectMessage.findById(created._id).populate('sender', DM_USER_FIELDS).lean(),
]);
// [Sprint 7 · M2] The recipient sees a plain message; the sender sees it with status 'sent'.
const message = messageView(populated);
const senderMessage = messageView(populated, { viewerId: sender, otherReadAt: otherReadAtFor(updated, sender) });
const conversationId = idOf(conversation);

const [recipientUnread, recipientTotal, senderTotal] = await Promise.all([
Expand All @@ -170,9 +193,114 @@ export async function sendMessage(conversation, senderId, body) {
unreadTotal: recipientTotal,
});
const senderView = conversationView(updated, sender, 0);
emitToUser(sender, 'dm:message', { conversationId, message, conversation: senderView, unreadTotal: senderTotal });
emitToUser(sender, 'dm:message', { conversationId, message: senderMessage, conversation: senderView, unreadTotal: senderTotal });

return { message: senderMessage, conversation: senderView };
}

/*
* [Sprint 7 · M2] Edit and delete your own direct messages.
*
* Both are single atomic updates that only match the sender's own, not-yet-deleted message, so an edit
* racing a delete can never bring the text back. The routes check who may do it first (403 for the other
* person); the filters here are a second guard.
*
* After a change both participants get 'dm:updated' { conversationId, message, conversation, unreadTotal }
* in their own rooms (nobody else), so the message changes live on both sides and in every open tab.
*/

// The message with this ID in this conversation (any sender), or null.
export function findMessageIn(conversation, messageId) {
return DirectMessage.findOne({ _id: messageId, conversation: conversation._id }).lean();
}

/*
* When the changed message is the newest one, the inbox line follows it (new text, or "Message deleted").
* The filter on lastMessageAt makes this a no-op if a newer message arrived in the meantime.
*/
async function refreshInboxPreview(conversation, messageId) {
const newest = await DirectMessage.findOne({ conversation: conversation._id })
.sort({ createdAt: -1, _id: -1 })
.select('_id body deletedAt createdAt')
.lean();
if (!newest || idOf(newest) !== idOf(messageId)) return;
await DirectConversation.updateOne(
{ _id: conversation._id, lastMessageAt: newest.createdAt },
{ $set: { lastMessagePreview: messagePreview(newest) } }
);
}

return { message, conversation: senderView };
// The message and conversation as they are now, as `viewerId` sees them (used when nothing changed).
async function currentView(conversation, messageId, viewerId) {
const [populated, fresh] = await Promise.all([
DirectMessage.findById(messageId).populate('sender', DM_USER_FIELDS).lean(),
DirectConversation.findById(conversation._id).populate('participants', DM_USER_FIELDS).lean(),
]);
const unread = await unreadCountFor(fresh, viewerId);
return {
message: messageView(populated, { viewerId, otherReadAt: otherReadAtFor(fresh, viewerId) }),
conversation: conversationView(fresh, viewerId, unread),
};
}

// Sends the changed message to both participants and returns what the person who changed it sees.
async function announceChange(conversation, messageId, actorId) {
const actor = objectId(actorId);
const other = otherParticipant(conversation, actor);
const [updated, populated] = await Promise.all([
DirectConversation.findById(conversation._id).populate('participants', DM_USER_FIELDS).lean(),
DirectMessage.findById(messageId).populate('sender', DM_USER_FIELDS).lean(),
]);
const conversationId = idOf(conversation);
const people = [actor, ...(other ? [objectId(other)] : [])];
const views = await Promise.all(
people.map(async (person) => {
const [unread, unreadTotal] = await Promise.all([unreadCountFor(updated, person), unreadTotalFor(person)]);
return {
person,
payload: {
conversationId,
message: messageView(populated, { viewerId: person, otherReadAt: otherReadAtFor(updated, person) }),
conversation: conversationView(updated, person, unread),
unreadTotal,
},
};
})
);
for (const { person, payload } of views) emitToUser(person, 'dm:updated', payload);
const mine = views[0].payload;
return { message: mine.message, conversation: mine.conversation };
}

/*
* The sender changes the text. Saving the same text again is not an edit (no "edited" mark, no event).
* -> { changed: true | false, message, conversation } or { changed: false, deleted: true } when the message
* was deleted in the meantime.
*/
export async function editMessage(conversation, message, editorId, body) {
if (message.body === body && !message.deletedAt) return { changed: false, ...(await currentView(conversation, message._id, editorId)) };
const result = await DirectMessage.updateOne(
{ _id: message._id, conversation: conversation._id, sender: objectId(editorId), deletedAt: null },
{ $set: { body, editedAt: new Date() } }
);
if (!result.matchedCount) return { changed: false, deleted: true };
await refreshInboxPreview(conversation, message._id);
return { changed: true, ...(await announceChange(conversation, message._id, editorId)) };
}

/*
* The sender deletes the message. The row stays (so the conversation still reads in order and replies
* keep their context) as "Message deleted"; its text is removed from the database. Deleting it again
* changes nothing. -> { changed, message, conversation }
*/
export async function deleteMessage(conversation, message, senderId) {
const result = await DirectMessage.updateOne(
{ _id: message._id, conversation: conversation._id, sender: objectId(senderId), deletedAt: null },
{ $set: { deletedAt: new Date(), body: '', editedAt: null } }
);
if (!result.matchedCount) return { changed: false, ...(await currentView(conversation, message._id, senderId)) };
await refreshInboxPreview(conversation, message._id);
return { changed: true, ...(await announceChange(conversation, message._id, senderId)) };
}

/*
Expand All @@ -182,5 +310,7 @@ export async function sendMessage(conversation, senderId, body) {
* between two users, list a user's inbox with unread counts, read pages of
* messages, send a message (saved, then pushed live to the two participants
* only) and mark a conversation read.
* [Sprint 7 · M2] Edit and delete your own messages (pushed live as
* 'dm:updated'), and tell the sender when their messages were seen ('dm:seen').
* ---------------------------------------------------------------------------
*/
11 changes: 10 additions & 1 deletion backend/src/models/DirectMessage.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import mongoose from 'mongoose';
import { DM_BODY_MAX } from '../lib/directMessageRules.js';

// [Sprint 7 · M2] A deleted message keeps its row (so the conversation still reads in order) but not its text.
function bodyRequired() {
return !this.deletedAt;
}

/*
* [Sprint 6 · M2] US-19 One message in a direct conversation (models/DirectConversation.js).
* Kept apart from project channel messages (models/Message.js): a different collection with no project
Expand All @@ -10,7 +15,11 @@ const directMessageSchema = new mongoose.Schema(
{
conversation: { type: mongoose.Schema.Types.ObjectId, ref: 'DirectConversation', required: true },
sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
body: { type: String, required: true, trim: true, maxlength: DM_BODY_MAX },
body: { type: String, required: bodyRequired, trim: true, maxlength: DM_BODY_MAX, default: '' },
// [Sprint 7 · M2] Edit and delete your own messages. Messages saved before Sprint 7 have neither field,
// which reads as "not edited, not deleted" (a missing field matches `null` in MongoDB queries).
editedAt: { type: Date, default: null }, // set when the sender changes the text ("edited")
deletedAt: { type: Date, default: null }, // set when the sender deletes it; body is emptied ("Message deleted")
},
{ timestamps: { createdAt: true, updatedAt: false } }
);
Expand Down
Loading
Loading