@davoodmehraban89 / LifeMate / commits / 265097c
Fork 0

LifeMate — Personal, Family & Learning Companion

feat: apply offline mutations with conflict checks

davoodmehraban89 committed Oct 5, 2026 at 15:12 UTC 265097ca65ad8a28c7e75c6d785252513c4af3c5
1 file changed +140 -26
backend/src/phase3.js
+140 -26
@@ -579,35 +579,149 @@ export function createPhase3Router({ pool, auth }) {
579
580 router.post('/sync/mutations', auth, async (req, res) => {
581 const mutations = Array.isArray(req.body.mutations) ? req.body.mutations : [];
582 - if (mutations.length > 100) return res.status(400).json({ error: 'too_many_mutations' });
582 + if (mutations.length > 100) {
583 + return res.status(400).json({ error: 'too_many_mutations' });
584 + }
585 +
586 + const client = await pool.connect();
587 const results = [];
584 - for (const m of mutations) {
585 - const id = String(m.id ?? '');
586 - const operation = String(m.operation ?? '');
587 - if (!id || !['create','update','complete','reschedule'].includes(operation)) {
588 - results.push({ id, status: 'rejected', error: 'invalid_mutation' });
589 - continue;
590 - }
591 - const existing = await pool.query(
592 - 'select accepted_at from sync_mutation where id=$1 and user_id=$2',
593 - [id, req.identity.sub],
594 - );
595 - if (existing.rowCount) {
596 - results.push({ id, status: 'already_applied', acceptedAt: existing.rows[0].accepted_at });
597 - continue;
588 + try {
589 + for (const mutation of mutations) {
590 + const id = String(mutation.id ?? '');
591 + const operation = String(mutation.operation ?? '');
592 + const entityType = String(mutation.entityType ?? 'plan_item');
593 + const entityId = mutation.entityId ? String(mutation.entityId) : null;
594 + const clientUpdatedAt = asDate(mutation.clientUpdatedAt);
595 + const payload = mutation.payload && typeof mutation.payload === 'object'
596 + ? mutation.payload
597 + : {};
598 +
599 + if (
600 + !id ||
601 + entityType !== 'plan_item' ||
602 + !entityId ||
603 + !clientUpdatedAt ||
604 + !['update', 'complete', 'reschedule'].includes(operation)
605 + ) {
606 + results.push({ id, status: 'rejected', error: 'invalid_mutation' });
607 + continue;
608 + }
609 +
610 + await client.query('begin');
611 + try {
612 + const duplicate = await client.query(
613 + 'select accepted_at from sync_mutation where id=$1 and user_id=$2',
614 + [id, req.identity.sub],
615 + );
616 + if (duplicate.rowCount) {
617 + await client.query('rollback');
618 + results.push({
619 + id,
620 + status: 'already_applied',
621 + acceptedAt: duplicate.rows[0].accepted_at,
622 + });
623 + continue;
624 + }
625 +
626 + const current = await client.query(
627 + 'select * from plan_item where id=$1 for update',
628 + [entityId],
629 + );
630 + if (!current.rowCount) {
631 + await client.query('rollback');
632 + results.push({ id, status: 'rejected', error: 'not_found' });
633 + continue;
634 + }
635 + const item = current.rows[0];
636 + if (item.owner_user_id !== req.identity.sub) {
637 + await client.query('rollback');
638 + results.push({ id, status: 'rejected', error: 'forbidden' });
639 + continue;
640 + }
641 +
642 + const serverUpdatedAt = new Date(item.updated_at);
643 + if (serverUpdatedAt.getTime() > clientUpdatedAt.getTime() + 1000) {
644 + await client.query('rollback');
645 + results.push({
646 + id,
647 + status: 'conflict',
648 + serverUpdatedAt: serverUpdatedAt.toISOString(),
649 + });
650 + continue;
651 + }
652 +
653 + if (operation === 'complete') {
654 + await client.query(
655 + `update plan_item
656 + set status='completed',completed_at=now(),updated_at=now()
657 + where id=$1`,
658 + [entityId],
659 + );
660 + await client.query(
661 + `update reminder set status='cancelled'
662 + where plan_item_id=$1 and status in ('scheduled','claimed')`,
663 + [entityId],
664 + );
665 + } else if (operation === 'reschedule') {
666 + const dueAt = asDate(payload.dueAt);
667 + const startsAt = asDate(payload.startsAt);
668 + if (!dueAt && !startsAt) {
669 + await client.query('rollback');
670 + results.push({ id, status: 'rejected', error: 'invalid_reschedule' });
671 + continue;
672 + }
673 + await client.query(
674 + `update plan_item
675 + set due_at=coalesce($2,due_at),
676 + starts_at=coalesce($3,starts_at),
677 + updated_at=now()
678 + where id=$1`,
679 + [entityId, dueAt, startsAt],
680 + );
681 + await client.query('select recompute_reminder_schedule($1)', [entityId]);
682 + } else {
683 + const title = payload.title == null ? null : String(payload.title).trim();
684 + const status = payload.status == null ? null : String(payload.status);
685 + if (status != null && !allowedStatus.has(status)) {
686 + await client.query('rollback');
687 + results.push({ id, status: 'rejected', error: 'invalid_status' });
688 + continue;
689 + }
690 + await client.query(
691 + `update plan_item
692 + set title=coalesce($2,title),
693 + status=coalesce($3::plan_item_status,status),
694 + updated_at=now()
695 + where id=$1`,
696 + [entityId, title || null, status],
697 + );
698 + }
699 +
700 + await client.query(
701 + `insert into sync_mutation(
702 + id,user_id,entity_type,entity_id,operation,client_updated_at,payload
703 + ) values($1,$2,$3,$4,$5,$6,$7::jsonb)`,
704 + [
705 + id,
706 + req.identity.sub,
707 + entityType,
708 + entityId,
709 + operation,
710 + clientUpdatedAt,
711 + JSON.stringify(payload),
712 + ],
713 + );
714 + await client.query('commit');
715 + results.push({ id, status: 'accepted' });
716 + } catch (error) {
717 + await client.query('rollback').catch(() => {});
718 + throw error;
719 + }
720 }
599 - await pool.query(
600 - `insert into sync_mutation(id,user_id,entity_type,entity_id,operation,client_updated_at,payload)
601 - values($1,$2,$3,$4,$5,$6,$7::jsonb)`,
602 - [
603 - id, req.identity.sub, String(m.entityType ?? 'plan_item'),
604 - m.entityId || null, operation, m.clientUpdatedAt || new Date(),
605 - JSON.stringify(m.payload ?? {}),
606 - ],
607 - );
608 - results.push({ id, status: 'accepted' });
721 + res.json({ results });
722 + } finally {
723 + client.release();
724 }
610 - res.json({ results });
725 });
726
727 return router;