summaryrefslogtreecommitdiffstats
path: root/src/features/reservations/services/reservationsService.ts
blob: e56a302b0ea0972f10c5990813fba6179583fa4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import {
  addDoc,
  collection,
  getDocs,
  orderBy,
  query,
  serverTimestamp,
  where,
} from 'firebase/firestore';
import { db } from '@/shared/lib/firebase/config';
import {
  CreateReservationInput,
  Reservation,
} from '@/features/reservations/types';

function mapReservation(id: string, data: any): Reservation {
  return {
    id,
    officeId: data.officeId ?? '',
    officeName: data.officeName ?? '',
    userId: data.userId ?? '',
    userEmail: data.userEmail ?? '',
    date: data.date ?? '',
    startTime: data.startTime ?? '',
    endTime: data.endTime ?? '',
    createdAt: data.createdAt,
  };
}

export const reservationsService = {
  async create(input: CreateReservationInput): Promise<void> {
    await addDoc(collection(db, 'reservations'), {
      ...input,
      createdAt: serverTimestamp(),
    });
  },

  async getByUserId(userId: string): Promise<Reservation[]> {
    const q = query(
      collection(db, 'reservations'),
      where('userId', '==', userId),
      orderBy('date', 'asc'),
      orderBy('startTime', 'asc')
    );

    const snapshot = await getDocs(q);

    return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data()));
  },

  async getByOfficeAndDate(officeId: string, date: string): Promise<Reservation[]> {
    const q = query(
      collection(db, 'reservations'),
      where('officeId', '==', officeId),
      where('date', '==', date),
      orderBy('startTime', 'asc')
    );

    const snapshot = await getDocs(q);

    return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data()));
  },
};