import PocketBase from 'pocketbase'; import { AppSettings, DEFAULT_SETTINGS, Collection, DriverLocation } from './types'; const POCKETBASE_URL = process.env.NEXT_PUBLIC_POCKETBASE_URL || 'https://pocketbase-gnqc88suy8fqk6wyryjjdpvl.169.239.180.130.sslip.io'; export const pb = new PocketBase(POCKETBASE_URL); // Collection names in PocketBase (matching Django table names) const COLLECTIONS_TABLE = 'driver_list_collection'; const PROBLEMS_TABLE = 'driver_list_collectionproblem'; const LOCATIONS_TABLE = 'driver_locations'; // Auth helpers export const isAuthenticated = () => pb.authStore.isValid; export const getCurrentUser = () => pb.authStore.model; export const logout = () => { pb.authStore.clear(); if (typeof window !== 'undefined') { window.location.href = '/login/'; } }; export const login = async (email: string, password: string) => { // Try 'users' first (PocketBase default), fallback to 'auth_user' try { return await pb.collection('users').authWithPassword(email, password); } catch { return await pb.collection('auth_user').authWithPassword(email, password); } }; // Collection data helpers export const getAssignedCollections = async () => { const user = getCurrentUser(); if (!user) return []; const today = new Date(); today.setHours(0, 0, 0, 0); const tomorrow = new Date(today); tomorrow.setDate(tomorrow.getDate() + 2); const records = await pb.collection(COLLECTIONS_TABLE).getFullList({ filter: `status = "assigned" && auth_user = "${user.id}" && planned_date <= "${tomorrow.toISOString()}"`, expand: 'orders_orderitem,wfdash_suppliers', sort: 'wfdash_suppliers.suppliername', }); return records as unknown as Collection[]; }; export const getPendingCollections = async () => { const records = await pb.collection(COLLECTIONS_TABLE).getFullList({ filter: 'status = "pending" || status = "problem"', expand: 'orders_orderitem,wfdash_suppliers', sort: 'wfdash_suppliers.suppliername', }); return records as unknown as Collection[]; }; export const updateCollectionStatus = async ( id: string, status: string, data: Partial ) => { return await pb.collection(COLLECTIONS_TABLE).update(id, { status, ...data, }); }; export const reportProblem = async ( collectionId: string, problemType: string, description: string ) => { // Update collection status await pb.collection(COLLECTIONS_TABLE).update(collectionId, { status: 'problem', notes: description, }); // Create problem record return await pb.collection(PROBLEMS_TABLE).create({ driver_list_collection: collectionId, problem_type: problemType, description, reported_at: new Date().toISOString(), }); }; // Location tracking export const saveDriverLocation = async (location: Omit) => { try { return await pb.collection(LOCATIONS_TABLE).create(location); } catch (err) { // If driver_locations table doesn't exist yet, silently fail console.warn('Could not save location - table may not exist:', err); } }; // Settings helpers const SETTINGS_KEY = '1driver_settings'; export const getSettings = (): AppSettings => { if (typeof window === 'undefined') return DEFAULT_SETTINGS; const saved = localStorage.getItem(SETTINGS_KEY); if (saved) { try { return { ...DEFAULT_SETTINGS, ...JSON.parse(saved) }; } catch { return DEFAULT_SETTINGS; } } return DEFAULT_SETTINGS; }; export const saveSettings = (settings: Partial) => { if (typeof window === 'undefined') return; const current = getSettings(); const updated = { ...current, ...settings }; localStorage.setItem(SETTINGS_KEY, JSON.stringify(updated)); return updated; }; // Offline queue helpers const QUEUE_KEY = '1driver_offline_queue'; export interface QueueItem { id: string; type: 'status_update' | 'problem_report'; data: Record; timestamp: string; } export const addToQueue = (item: Omit) => { if (typeof window === 'undefined') return; const queue = getQueue(); const newItem: QueueItem = { ...item, id: crypto.randomUUID(), timestamp: new Date().toISOString(), }; queue.push(newItem); localStorage.setItem(QUEUE_KEY, JSON.stringify(queue)); }; export const getQueue = (): QueueItem[] => { if (typeof window === 'undefined') return []; const saved = localStorage.getItem(QUEUE_KEY); return saved ? JSON.parse(saved) : []; }; export const removeFromQueue = (id: string) => { if (typeof window === 'undefined') return; const queue = getQueue().filter((item) => item.id !== id); localStorage.setItem(QUEUE_KEY, JSON.stringify(queue)); }; export const clearQueue = () => { if (typeof window === 'undefined') return; localStorage.removeItem(QUEUE_KEY); };