Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

7.2 KB
Raw Blame
import { packingRepo } from '../../repo/packingRepo'
import { packingApi } from '../../api/client'
import type { StoreApi } from 'zustand'
import type { TripStoreState } from '../tripStore'
import type { PackingItem } from '../../types'
import { getApiErrorMessage } from '../../types'
import { notify } from '../notify'
import { resolvePackedState } from '@trek/shared'

type SetState = StoreApi<TripStoreState>['setState']
type GetState = StoreApi<TripStoreState>['getState']

export interface PackingSlice {
  addPackingItem: (tripId: number | string, data: Partial<PackingItem> & { name: string }) => Promise<PackingItem>
  updatePackingItem: (tripId: number | string, id: number, data: Partial<PackingItem>) => Promise<PackingItem>
  deletePackingItem: (tripId: number | string, id: number) => Promise<void>
  togglePackingItem: (tripId: number | string, id: number, checked: boolean) => Promise<void>
  /** Count how many pieces of a multi-piece item are packed (#2296). */
  setPackedCount: (tripId: number | string, id: number, count: number) => Promise<void>
  reorderPackingItems: (tripId: number | string, orderedIds: number[]) => Promise<void>
  // Three-tier sharing (#858)
  setPackingItemSharing: (tripId: number | string, id: number, visibility: 'common' | 'personal' | 'shared', recipientIds: number[]) => Promise<void>
  clonePackingItem: (tripId: number | string, id: number) => Promise<void>
  /** Without a userId the caller pledges themselves; with one, that member is put down as a bringer (#3098). */
  addPackingContributor: (tripId: number | string, id: number, userId?: number) => Promise<void>
  removePackingContributor: (tripId: number | string, id: number, userId: number) => Promise<void>
}

export const createPackingSlice = (set: SetState, get: GetState): PackingSlice => ({
  addPackingItem: async (tripId, data) => {
    try {
      const result = await packingRepo.create(tripId, data as Record<string, unknown> & { name: string })
      set(state => ({ packingItems: [...state.packingItems, result.item] }))
      return result.item
    } catch (err: unknown) {
      throw new Error(getApiErrorMessage(err, 'Error adding item'))
    }
  },

  updatePackingItem: async (tripId, id, data) => {
    try {
      const result = await packingRepo.update(tripId, id, data as Record<string, unknown>)
      set(state => ({
        packingItems: state.packingItems.map(item => item.id === id ? result.item : item)
      }))
      return result.item
    } catch (err: unknown) {
      throw new Error(getApiErrorMessage(err, 'Error updating item'))
    }
  },

  deletePackingItem: async (tripId, id) => {
    const prev = get().packingItems
    set(state => ({ packingItems: state.packingItems.filter(item => item.id !== id) }))
    try {
      await packingRepo.delete(tripId, id)
    } catch (err: unknown) {
      set({ packingItems: prev })
      throw new Error(getApiErrorMessage(err, 'Error deleting item'))
    }
  },

  togglePackingItem: async (tripId, id, checked) => {
    const prev = get().packingItems.find(item => item.id === id)
    // Ticking decides for the whole item, so a partial count goes with it (#2296).
    set(state => ({
      packingItems: state.packingItems.map(item =>
        item.id === id ? { ...item, checked: checked ? 1 : 0, packed_quantity: null } : item
      )
    }))
    try {
      await packingRepo.update(tripId, id, { checked })
    } catch (err: unknown) {
      // The caller fires this optimistically and doesn't await, so rolling back
      // silently would just flip the checkbox with no explanation. Surface it.
      set(state => ({
        packingItems: state.packingItems.map(item =>
          item.id === id ? { ...item, checked: checked ? 0 : 1, packed_quantity: prev?.packed_quantity ?? null } : item
        )
      }))
      notify(getApiErrorMessage(err, 'Error updating item'), 'error')
    }
  },

  setPackedCount: async (tripId, id, count) => {
    const prev = get().packingItems.find(item => item.id === id)
    if (!prev) return
    // The server's own rule, run ahead of it so the counter answers at once.
    const next = resolvePackedState(
      { checked: prev.checked ? 1 : 0, packed_quantity: prev.packed_quantity ?? null },
      { bodyKeys: ['packed_quantity'], packed_quantity: count, quantity: prev.quantity || 1 },
    )
    set(state => ({ packingItems: state.packingItems.map(item => item.id === id ? { ...item, ...next } : item) }))
    try {
      await packingRepo.update(tripId, id, { packed_quantity: count })
    } catch (err: unknown) {
      set(state => ({ packingItems: state.packingItems.map(item => item.id === id ? prev : item) }))
      notify(getApiErrorMessage(err, 'Error updating item'), 'error')
    }
  },

  reorderPackingItems: async (tripId, orderedIds) => {
    const prev = get().packingItems
    // Optimistic reorder: rebuild the array in the requested order, reindexing
    // sort_order; any items not in orderedIds keep their place at the end.
    // Unknown ids are dropped first so a stale id can't leave a gap in the
    // local sort_order sequence.
    set(state => {
      const byId = new Map(state.packingItems.map(i => [i.id, i]))
      const reordered = orderedIds
        .map(id => byId.get(id))
        .filter((i): i is PackingItem => i !== undefined)
        .map((item, idx): PackingItem => ({ ...item, sort_order: idx }))
      const remaining = state.packingItems.filter(i => !orderedIds.includes(i.id))
      return { packingItems: [...reordered, ...remaining] }
    })
    try {
      await packingApi.reorder(tripId, orderedIds)
    } catch (err: unknown) {
      set({ packingItems: prev })
      notify(getApiErrorMessage(err, 'Error reordering items'), 'error')
    }
  },

  // ── Three-tier sharing (#858) ──────────────────────────────────────────────
  setPackingItemSharing: async (tripId, id, visibility, recipientIds) => {
    try {
      const result = await packingApi.setSharing(tripId, id, { visibility, recipient_ids: recipientIds })
      set(state => ({ packingItems: state.packingItems.map(i => i.id === id ? result.item : i) }))
    } catch (err: unknown) {
      notify(getApiErrorMessage(err, 'Error updating sharing'), 'error')
      throw err
    }
  },

  clonePackingItem: async (tripId, id) => {
    try {
      const result = await packingApi.clone(tripId, id)
      set(state => (state.packingItems.some(i => i.id === result.item.id) ? {} : { packingItems: [...state.packingItems, result.item] }))
    } catch (err: unknown) {
      notify(getApiErrorMessage(err, 'Error copying item'), 'error')
    }
  },

  addPackingContributor: async (tripId, id, userId) => {
    try {
      const result = await packingApi.addContributor(tripId, id, userId)
      set(state => ({ packingItems: state.packingItems.map(i => i.id === id ? result.item : i) }))
    } catch (err: unknown) {
      notify(getApiErrorMessage(err, 'Error joining item'), 'error')
    }
  },

  removePackingContributor: async (tripId, id, userId) => {
    try {
      const result = await packingApi.removeContributor(tripId, id, userId)
      set(state => ({ packingItems: state.packingItems.map(i => i.id === id ? result.item : i) }))
    } catch (err: unknown) {
      notify(getApiErrorMessage(err, 'Error leaving item'), 'error')
    }
  },
})