Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62e2255b5e | ||
|
|
d7d270510f | ||
|
|
a5c297b911 | ||
|
|
0011c9d4e5 | ||
|
|
db0d2cf215 |
No files matched your search
Binary file not shown.
@@ -13,21 +13,8 @@ export async function POST(req: Request) {
|
||||
// Ensure user exists in DB (sync from Clerk if needed)
|
||||
await ensureUserSynced(userId, db)
|
||||
|
||||
let client = await db.getClientByUserId(userId)
|
||||
|
||||
if (!client) {
|
||||
// Auto-create client profile if it doesn't exist
|
||||
console.log('Client profile not found, creating new one for user:', userId)
|
||||
client = await db.createClient({
|
||||
userId,
|
||||
membershipType: 'basic',
|
||||
membershipStatus: 'active',
|
||||
joinDate: new Date()
|
||||
})
|
||||
}
|
||||
|
||||
// Check if already checked in
|
||||
const activeCheckIn = await db.getActiveCheckIn(client.id)
|
||||
const activeCheckIn = await db.getActiveCheckIn(userId)
|
||||
if (activeCheckIn) {
|
||||
return new NextResponse('Already checked in', { status: 400 })
|
||||
}
|
||||
@@ -35,7 +22,7 @@ export async function POST(req: Request) {
|
||||
const body = await req.json()
|
||||
const { type = 'gym', notes } = body
|
||||
|
||||
const attendance = await db.checkIn(client.id, type, notes)
|
||||
const attendance = await db.checkIn(userId, type, notes)
|
||||
return NextResponse.json(attendance)
|
||||
} catch (error) {
|
||||
console.error('Check-in error:', error)
|
||||
|
||||
@@ -8,13 +8,8 @@ export async function POST(req: Request) {
|
||||
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
|
||||
|
||||
const db = await getDatabase()
|
||||
const client = await db.getClientByUserId(userId)
|
||||
|
||||
if (!client) {
|
||||
return new NextResponse('Client profile not found', { status: 404 })
|
||||
}
|
||||
|
||||
const activeCheckIn = await db.getActiveCheckIn(client.id)
|
||||
const activeCheckIn = await db.getActiveCheckIn(userId)
|
||||
if (!activeCheckIn) {
|
||||
return new NextResponse('No active check-in found', { status: 404 })
|
||||
}
|
||||
|
||||
@@ -22,20 +22,7 @@ export async function GET(req: Request) {
|
||||
// Ensure user exists in DB (sync from Clerk if needed)
|
||||
await ensureUserSynced(userId, db)
|
||||
|
||||
let client = await db.getClientByUserId(userId)
|
||||
|
||||
if (!client) {
|
||||
// Auto-create client profile if it doesn't exist
|
||||
console.log('Client profile not found, creating new one for user:', userId)
|
||||
client = await db.createClient({
|
||||
userId,
|
||||
membershipType: 'basic',
|
||||
membershipStatus: 'active',
|
||||
joinDate: new Date()
|
||||
})
|
||||
}
|
||||
|
||||
const history = await db.getAttendanceHistory(client.id)
|
||||
const history = await db.getAttendanceHistory(userId)
|
||||
return NextResponse.json(history)
|
||||
} catch (error) {
|
||||
console.error('History error:', error)
|
||||
|
||||
@@ -19,7 +19,52 @@ export async function GET(request: NextRequest) {
|
||||
users.map(async (user) => {
|
||||
const { password: _, ...userWithoutPassword } = user;
|
||||
const client = await db.getClientByUserId(user.id);
|
||||
return { ...userWithoutPassword, client };
|
||||
|
||||
// Get active check-in status and statistics for ALL users
|
||||
let isCheckedIn = false;
|
||||
let checkInTime = null;
|
||||
let lastCheckInTime = null;
|
||||
let checkInsThisWeek = 0;
|
||||
let checkInsThisMonth = 0;
|
||||
|
||||
// Query attendance by userId (works for all user types now)
|
||||
const activeCheckIn = await db.getActiveCheckIn(user.id);
|
||||
if (activeCheckIn) {
|
||||
isCheckedIn = true;
|
||||
checkInTime = activeCheckIn.checkInTime;
|
||||
}
|
||||
|
||||
// Get attendance history for statistics
|
||||
const attendanceHistory = await db.getAttendanceHistory(user.id);
|
||||
|
||||
if (attendanceHistory.length > 0) {
|
||||
// Last check-in is the most recent attendance record
|
||||
lastCheckInTime = attendanceHistory[0].checkInTime;
|
||||
|
||||
// Calculate check-ins in last 7 days
|
||||
const weekAgo = new Date();
|
||||
weekAgo.setDate(weekAgo.getDate() - 7);
|
||||
checkInsThisWeek = attendanceHistory.filter(
|
||||
a => new Date(a.checkInTime) >= weekAgo
|
||||
).length;
|
||||
|
||||
// Calculate check-ins in last 30 days
|
||||
const monthAgo = new Date();
|
||||
monthAgo.setDate(monthAgo.getDate() - 30);
|
||||
checkInsThisMonth = attendanceHistory.filter(
|
||||
a => new Date(a.checkInTime) >= monthAgo
|
||||
).length;
|
||||
}
|
||||
|
||||
return {
|
||||
...userWithoutPassword,
|
||||
client,
|
||||
isCheckedIn,
|
||||
checkInTime,
|
||||
lastCheckInTime,
|
||||
checkInsThisWeek,
|
||||
checkInsThisMonth
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -9,6 +9,20 @@ import { formatDate } from "@/lib/utils";
|
||||
|
||||
ModuleRegistry.registerModules([AllCommunityModule]);
|
||||
|
||||
function getTimeAgo(date: Date): string {
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
const diffHours = Math.floor(diffMins / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
|
||||
if (diffMins < 1) return 'just now';
|
||||
if (diffMins < 60) return `${diffMins}m ago`;
|
||||
if (diffHours < 24) return `${diffHours}h ago`;
|
||||
return `${diffDays}d ago`;
|
||||
}
|
||||
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
@@ -17,6 +31,8 @@ interface User {
|
||||
role: string;
|
||||
phone?: string;
|
||||
createdAt: Date;
|
||||
isCheckedIn?: boolean;
|
||||
checkInTime?: Date;
|
||||
client?: {
|
||||
id: string;
|
||||
membershipType: string;
|
||||
@@ -152,6 +168,27 @@ export function UserGrid({
|
||||
},
|
||||
minWidth: 120,
|
||||
},
|
||||
{
|
||||
headerName: "Currently Checked In",
|
||||
valueGetter: (params) => params.data?.isCheckedIn,
|
||||
filter: "agTextColumnFilter",
|
||||
sortable: true,
|
||||
cellRenderer: (params: any) => {
|
||||
if (!params.data?.isCheckedIn) {
|
||||
return <span className="text-gray-400">—</span>;
|
||||
}
|
||||
|
||||
const checkInTime = params.data.checkInTime ? new Date(params.data.checkInTime) : null;
|
||||
const timeAgo = checkInTime ? getTimeAgo(checkInTime) : '';
|
||||
|
||||
return (
|
||||
<span className="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
|
||||
✓ Checked In {timeAgo && `(${timeAgo})`}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
minWidth: 180,
|
||||
},
|
||||
{
|
||||
headerName: "Join Date",
|
||||
valueGetter: (params) =>
|
||||
|
||||
@@ -13,6 +13,11 @@ interface User {
|
||||
role: string;
|
||||
phone?: string;
|
||||
createdAt: Date;
|
||||
isCheckedIn?: boolean;
|
||||
checkInTime?: Date;
|
||||
lastCheckInTime?: Date;
|
||||
checkInsThisWeek?: number;
|
||||
checkInsThisMonth?: number;
|
||||
client?: {
|
||||
id: string;
|
||||
membershipType: string;
|
||||
@@ -444,7 +449,7 @@ export function UserManagement() {
|
||||
</a>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<h4 className="font-medium mb-2">Basic Information</h4>
|
||||
<div className="space-y-1 text-sm">
|
||||
@@ -500,6 +505,28 @@ export function UserManagement() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h4 className="font-medium mb-2">Check-In Statistics</h4>
|
||||
<div className="space-y-1 text-sm">
|
||||
<p>
|
||||
<span className="font-medium">Last Check-In:</span>{" "}
|
||||
{selectedUser.lastCheckInTime
|
||||
? new Date(
|
||||
selectedUser.lastCheckInTime,
|
||||
).toLocaleString()
|
||||
: "Never"}
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-medium">This Week:</span>{" "}
|
||||
{selectedUser.checkInsThisWeek || 0} check-ins
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-medium">This Month:</span>{" "}
|
||||
{selectedUser.checkInsThisMonth || 0} check-ins
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -106,19 +106,61 @@ export class SQLiteDatabase implements IDatabase {
|
||||
CREATE INDEX IF NOT EXISTS idx_fitness_profiles_userId ON fitness_profiles(userId);
|
||||
`)
|
||||
|
||||
// Attendance table
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS attendance (
|
||||
id TEXT PRIMARY KEY,
|
||||
clientId TEXT NOT NULL,
|
||||
checkInTime DATETIME NOT NULL,
|
||||
checkOutTime DATETIME,
|
||||
type TEXT NOT NULL CHECK (type IN ('gym', 'class', 'personal_training')),
|
||||
notes TEXT,
|
||||
createdAt DATETIME NOT NULL,
|
||||
FOREIGN KEY (clientId) REFERENCES clients (id) ON DELETE CASCADE
|
||||
)
|
||||
`)
|
||||
// Attendance table migration: change from clientId to userId
|
||||
// Check if old table exists and migrate
|
||||
const tableInfo = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='attendance'").get() as any;
|
||||
|
||||
if (tableInfo) {
|
||||
// Check if table has clientId column (old schema)
|
||||
const columns = this.db.prepare("PRAGMA table_info(attendance)").all() as any[];
|
||||
const hasClientId = columns.some((col: any) => col.name === 'clientId');
|
||||
|
||||
if (hasClientId) {
|
||||
console.log('Migrating attendance table from clientId to userId...');
|
||||
|
||||
// Create new table with userId
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS attendance_new (
|
||||
id TEXT PRIMARY KEY,
|
||||
userId TEXT NOT NULL,
|
||||
checkInTime DATETIME NOT NULL,
|
||||
checkOutTime DATETIME,
|
||||
type TEXT NOT NULL CHECK (type IN ('gym', 'class', 'personal_training')),
|
||||
notes TEXT,
|
||||
createdAt DATETIME NOT NULL,
|
||||
FOREIGN KEY (userId) REFERENCES users (id) ON DELETE CASCADE
|
||||
)
|
||||
`);
|
||||
|
||||
// Migrate data: map clientId to userId via clients table
|
||||
this.db.exec(`
|
||||
INSERT INTO attendance_new (id, userId, checkInTime, checkOutTime, type, notes, createdAt)
|
||||
SELECT a.id, c.userId, a.checkInTime, a.checkOutTime, a.type, a.notes, a.createdAt
|
||||
FROM attendance a
|
||||
JOIN clients c ON a.clientId = c.id
|
||||
`);
|
||||
|
||||
// Drop old table and rename new one
|
||||
this.db.exec(`DROP TABLE attendance`);
|
||||
this.db.exec(`ALTER TABLE attendance_new RENAME TO attendance`);
|
||||
|
||||
console.log('Attendance table migration completed');
|
||||
}
|
||||
} else {
|
||||
// Create new attendance table with userId
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS attendance (
|
||||
id TEXT PRIMARY KEY,
|
||||
userId TEXT NOT NULL,
|
||||
checkInTime DATETIME NOT NULL,
|
||||
checkOutTime DATETIME,
|
||||
type TEXT NOT NULL CHECK (type IN ('gym', 'class', 'personal_training')),
|
||||
notes TEXT,
|
||||
createdAt DATETIME NOT NULL,
|
||||
FOREIGN KEY (userId) REFERENCES users (id) ON DELETE CASCADE
|
||||
)
|
||||
`);
|
||||
}
|
||||
|
||||
// Recommendations table
|
||||
// Removed DROP TABLE to persist data. Schema is now stable.
|
||||
@@ -140,16 +182,16 @@ export class SQLiteDatabase implements IDatabase {
|
||||
FOREIGN KEY (userId) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (fitnessProfileId) REFERENCES fitness_profiles (userId)
|
||||
)
|
||||
`)
|
||||
`);
|
||||
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_recommendations_userId ON recommendations(userId);
|
||||
`)
|
||||
`);
|
||||
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_attendance_clientId ON attendance(clientId);
|
||||
CREATE INDEX IF NOT EXISTS idx_attendance_userId ON attendance(userId);
|
||||
CREATE INDEX IF NOT EXISTS idx_attendance_checkInTime ON attendance(checkInTime);
|
||||
`)
|
||||
`);
|
||||
}
|
||||
|
||||
// User operations
|
||||
@@ -389,7 +431,7 @@ export class SQLiteDatabase implements IDatabase {
|
||||
}
|
||||
|
||||
// Attendance operations
|
||||
async checkIn(clientId: string, type: 'gym' | 'class' | 'personal_training', notes?: string): Promise<Attendance> {
|
||||
async checkIn(userId: string, type: 'gym' | 'class' | 'personal_training', notes?: string): Promise<Attendance> {
|
||||
if (!this.db) throw new Error('Database not connected')
|
||||
|
||||
const id = Math.random().toString(36).substr(2, 9)
|
||||
@@ -397,7 +439,7 @@ export class SQLiteDatabase implements IDatabase {
|
||||
|
||||
const attendance: Attendance = {
|
||||
id,
|
||||
clientId,
|
||||
userId,
|
||||
checkInTime: now,
|
||||
type,
|
||||
notes,
|
||||
@@ -405,20 +447,23 @@ export class SQLiteDatabase implements IDatabase {
|
||||
}
|
||||
|
||||
const stmt = this.db.prepare(
|
||||
`INSERT INTO attendance(id, clientId, checkInTime, type, notes, createdAt)
|
||||
`INSERT INTO attendance(id, userId, checkInTime, type, notes, createdAt)
|
||||
VALUES(?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
|
||||
stmt.run(
|
||||
attendance.id, attendance.clientId, attendance.checkInTime.toISOString(),
|
||||
attendance.id, attendance.userId, attendance.checkInTime.toISOString(),
|
||||
attendance.type, attendance.notes, attendance.createdAt.toISOString()
|
||||
)
|
||||
|
||||
// Update client last visit
|
||||
this.db.prepare('UPDATE clients SET lastVisit = ? WHERE id = ?').run(
|
||||
now.toISOString(),
|
||||
clientId
|
||||
)
|
||||
// Update client last visit if user is a client
|
||||
const client = await this.getClientByUserId(userId);
|
||||
if (client) {
|
||||
this.db.prepare('UPDATE clients SET lastVisit = ? WHERE id = ?').run(
|
||||
now.toISOString(),
|
||||
client.id
|
||||
);
|
||||
}
|
||||
|
||||
return attendance
|
||||
}
|
||||
@@ -440,10 +485,10 @@ export class SQLiteDatabase implements IDatabase {
|
||||
return row ? this.mapRowToAttendance(row) : null
|
||||
}
|
||||
|
||||
async getAttendanceHistory(clientId: string): Promise<Attendance[]> {
|
||||
async getAttendanceHistory(userId: string): Promise<Attendance[]> {
|
||||
if (!this.db) throw new Error('Database not connected')
|
||||
const stmt = this.db.prepare('SELECT * FROM attendance WHERE clientId = ? ORDER BY checkInTime DESC')
|
||||
const rows = stmt.all(clientId)
|
||||
const stmt = this.db.prepare('SELECT * FROM attendance WHERE userId = ? ORDER BY checkInTime DESC')
|
||||
const rows = stmt.all(userId)
|
||||
return rows.map(row => this.mapRowToAttendance(row))
|
||||
}
|
||||
|
||||
@@ -454,10 +499,10 @@ export class SQLiteDatabase implements IDatabase {
|
||||
return rows.map(row => this.mapRowToAttendance(row))
|
||||
}
|
||||
|
||||
async getActiveCheckIn(clientId: string): Promise<Attendance | null> {
|
||||
async getActiveCheckIn(userId: string): Promise<Attendance | null> {
|
||||
if (!this.db) throw new Error('Database not connected')
|
||||
const stmt = this.db.prepare('SELECT * FROM attendance WHERE clientId = ? AND checkOutTime IS NULL ORDER BY checkInTime DESC LIMIT 1')
|
||||
const row = stmt.get(clientId)
|
||||
const stmt = this.db.prepare('SELECT * FROM attendance WHERE userId = ? AND checkOutTime IS NULL ORDER BY checkInTime DESC LIMIT 1')
|
||||
const row = stmt.get(userId)
|
||||
return row ? this.mapRowToAttendance(row) : null
|
||||
}
|
||||
|
||||
@@ -509,7 +554,7 @@ export class SQLiteDatabase implements IDatabase {
|
||||
private mapRowToAttendance(row: any): Attendance {
|
||||
return {
|
||||
id: row.id,
|
||||
clientId: row.clientId,
|
||||
userId: row.userId,
|
||||
checkInTime: new Date(row.checkInTime),
|
||||
checkOutTime: row.checkOutTime ? new Date(row.checkOutTime) : undefined,
|
||||
type: row.type,
|
||||
|
||||
@@ -39,7 +39,7 @@ export interface FitnessProfile {
|
||||
|
||||
export interface Attendance {
|
||||
id: string;
|
||||
clientId: string;
|
||||
userId: string;
|
||||
checkInTime: Date;
|
||||
checkOutTime?: Date;
|
||||
type: "gym" | "class" | "personal_training";
|
||||
@@ -121,14 +121,14 @@ export interface IDatabase {
|
||||
|
||||
// Attendance operations
|
||||
checkIn(
|
||||
clientId: string,
|
||||
userId: string,
|
||||
type: "gym" | "class" | "personal_training",
|
||||
notes?: string,
|
||||
): Promise<Attendance>;
|
||||
checkOut(attendanceId: string): Promise<Attendance | null>;
|
||||
getAttendanceHistory(clientId: string): Promise<Attendance[]>;
|
||||
getAttendanceHistory(userId: string): Promise<Attendance[]>;
|
||||
getAllAttendance(): Promise<Attendance[]>;
|
||||
getActiveCheckIn(clientId: string): Promise<Attendance | null>;
|
||||
getActiveCheckIn(userId: string): Promise<Attendance | null>;
|
||||
|
||||
// Recommendation operations
|
||||
createRecommendation(
|
||||
|
||||
+11
-4
@@ -15,21 +15,28 @@
|
||||
"**/*"
|
||||
],
|
||||
"ios": {
|
||||
"supportsTablet": true
|
||||
"supportsTablet": true,
|
||||
"infoPlist": {
|
||||
"NSCameraUsageDescription": "This app uses the camera to scan food barcodes and identify nutritional information."
|
||||
}
|
||||
},
|
||||
"android": {
|
||||
"adaptiveIcon": {
|
||||
"foregroundImage": "./assets/adaptive-icon.png",
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
},
|
||||
"permissions": [
|
||||
"CAMERA"
|
||||
]
|
||||
},
|
||||
"web": {
|
||||
"favicon": "./assets/favicon.png"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
"expo-font"
|
||||
"expo-font",
|
||||
"expo-barcode-scanner"
|
||||
],
|
||||
"scheme": "fitai"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+23
-1
@@ -20,7 +20,8 @@
|
||||
"axios": "^1.6.0",
|
||||
"expo": "~54.0.23",
|
||||
"expo-auth-session": "^7.0.8",
|
||||
"expo-camera": "~17.0.0",
|
||||
"expo-barcode-scanner": "^13.0.1",
|
||||
"expo-camera": "~17.0.9",
|
||||
"expo-constants": "^18.0.10",
|
||||
"expo-crypto": "^15.0.7",
|
||||
"expo-font": "~14.0.9",
|
||||
@@ -7203,6 +7204,18 @@
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-barcode-scanner": {
|
||||
"version": "13.0.1",
|
||||
"resolved": "https://registry.npmjs.org/expo-barcode-scanner/-/expo-barcode-scanner-13.0.1.tgz",
|
||||
"integrity": "sha512-xBGLT1An2gpAMIQRTLU3oHydKohX8r8F9/ait1Fk9Vgd0GraFZbP4IiT7nHMlaw4H6E7Muucf7vXpGV6u7d4HQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"expo-image-loader": "~4.7.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-camera": {
|
||||
"version": "17.0.9",
|
||||
"resolved": "https://registry.npmjs.org/expo-camera/-/expo-camera-17.0.9.tgz",
|
||||
@@ -7282,6 +7295,15 @@
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-image-loader": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/expo-image-loader/-/expo-image-loader-4.7.0.tgz",
|
||||
"integrity": "sha512-cx+MxxsAMGl9AiWnQUzrkJMJH4eNOGlu7XkLGnAXSJrRoIiciGaKqzeaD326IyCTV+Z1fXvIliSgNW+DscvD8g==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-linear-gradient": {
|
||||
"version": "15.0.7",
|
||||
"resolved": "https://registry.npmjs.org/expo-linear-gradient/-/expo-linear-gradient-15.0.7.tgz",
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
"axios": "^1.6.0",
|
||||
"expo": "~54.0.23",
|
||||
"expo-auth-session": "^7.0.8",
|
||||
"expo-camera": "~17.0.0",
|
||||
"expo-barcode-scanner": "^13.0.1",
|
||||
"expo-camera": "~17.0.9",
|
||||
"expo-constants": "^18.0.10",
|
||||
"expo-crypto": "^15.0.7",
|
||||
"expo-font": "~14.0.9",
|
||||
|
||||
@@ -9,6 +9,7 @@ import { QuickActionGrid } from "../../components/QuickActionGrid";
|
||||
import { TrackMealModal } from "../../components/TrackMealModal";
|
||||
import { AddWaterModal } from "../../components/AddWaterModal";
|
||||
import { HydrationWidget } from "../../components/HydrationWidget";
|
||||
import { ScanFoodModal } from "../../components/ScanFoodModal";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
|
||||
export default function HomeScreen() {
|
||||
@@ -16,6 +17,7 @@ export default function HomeScreen() {
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [trackMealModalVisible, setTrackMealModalVisible] = useState(false);
|
||||
const [addWaterModalVisible, setAddWaterModalVisible] = useState(false);
|
||||
const [scanFoodModalVisible, setScanFoodModalVisible] = useState(false);
|
||||
const [calories, setCalories] = useState(0);
|
||||
const [waterIntake, setWaterIntake] = useState(0);
|
||||
|
||||
@@ -51,6 +53,11 @@ export default function HomeScreen() {
|
||||
setWaterIntake(0);
|
||||
};
|
||||
|
||||
const handleAddScannedFood = (scannedCalories: number) => {
|
||||
setCalories(prev => prev + scannedCalories);
|
||||
setScanFoodModalVisible(false);
|
||||
};
|
||||
|
||||
const resetAllCounters = async () => {
|
||||
setCalories(0);
|
||||
setWaterIntake(0);
|
||||
@@ -134,6 +141,7 @@ export default function HomeScreen() {
|
||||
<QuickActionGrid
|
||||
onTrackMealPress={() => setTrackMealModalVisible(true)}
|
||||
onAddWaterPress={() => setAddWaterModalVisible(true)}
|
||||
onScanFoodPress={() => setScanFoodModalVisible(true)}
|
||||
/>
|
||||
|
||||
<TrackMealModal
|
||||
@@ -150,6 +158,12 @@ export default function HomeScreen() {
|
||||
onResetData={handleResetWater}
|
||||
/>
|
||||
|
||||
<ScanFoodModal
|
||||
visible={scanFoodModalVisible}
|
||||
onClose={() => setScanFoodModalVisible(false)}
|
||||
onAddFood={handleAddScannedFood}
|
||||
/>
|
||||
|
||||
{/* Recent Activity Section */}
|
||||
<View style={styles.section}>
|
||||
<View style={styles.sectionHeader}>
|
||||
|
||||
@@ -39,9 +39,10 @@ function QuickActionItem({ icon, label, gradient, onPress }: QuickActionProps) {
|
||||
interface QuickActionGridProps {
|
||||
onTrackMealPress?: () => void;
|
||||
onAddWaterPress?: () => void;
|
||||
onScanFoodPress?: () => void;
|
||||
}
|
||||
|
||||
export function QuickActionGrid({ onTrackMealPress, onAddWaterPress }: QuickActionGridProps) {
|
||||
export function QuickActionGrid({ onTrackMealPress, onAddWaterPress, onScanFoodPress }: QuickActionGridProps) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.sectionTitle}>Quick Actions</Text>
|
||||
@@ -67,6 +68,7 @@ export function QuickActionGrid({ onTrackMealPress, onAddWaterPress }: QuickActi
|
||||
icon="scan"
|
||||
label="Scan Food"
|
||||
gradient={theme.gradients.purple}
|
||||
onPress={onScanFoodPress}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { View, Text, StyleSheet, Modal, TouchableOpacity, TextInput, Alert } from 'react-native';
|
||||
import { CameraView, useCameraPermissions } from 'expo-camera';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { LinearGradient } from 'expo-linear-gradient';
|
||||
import { theme } from '../styles/theme';
|
||||
|
||||
interface ScanFoodModalProps {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
onAddFood: (calories: number) => void;
|
||||
}
|
||||
|
||||
// Mock food database
|
||||
const FOOD_DATABASE: { [key: string]: { name: string; calories: number; servingSize: string } } = {
|
||||
'0123456789': { name: 'Apple', calories: 95, servingSize: '1 medium' },
|
||||
'9876543210': { name: 'Banana', calories: 105, servingSize: '1 medium' },
|
||||
'5555555555': { name: 'Protein Bar', calories: 200, servingSize: '1 bar' },
|
||||
'1111111111': { name: 'Greek Yogurt', calories: 150, servingSize: '1 cup' },
|
||||
};
|
||||
|
||||
export function ScanFoodModal({ visible, onClose, onAddFood }: ScanFoodModalProps) {
|
||||
const [permission, requestPermission] = useCameraPermissions();
|
||||
const [scanned, setScanned] = useState(false);
|
||||
const [foodData, setFoodData] = useState<{ name: string; calories: number; servingSize: string } | null>(null);
|
||||
const [servings, setServings] = useState('1');
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
setScanned(false);
|
||||
setFoodData(null);
|
||||
setServings('1');
|
||||
}
|
||||
}, [visible]);
|
||||
|
||||
const handleBarCodeScanned = ({ data }: { data: string }) => {
|
||||
if (scanned) return;
|
||||
|
||||
setScanned(true);
|
||||
|
||||
// Look up food in database
|
||||
const food = FOOD_DATABASE[data];
|
||||
|
||||
if (food) {
|
||||
setFoodData(food);
|
||||
} else {
|
||||
// Mock data for unknown barcodes
|
||||
setFoodData({
|
||||
name: 'Unknown Food',
|
||||
calories: 150,
|
||||
servingSize: '1 serving'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (foodData) {
|
||||
const totalCalories = foodData.calories * parseFloat(servings || '1');
|
||||
onAddFood(totalCalories);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
const handleRescan = () => {
|
||||
setScanned(false);
|
||||
setFoodData(null);
|
||||
setServings('1');
|
||||
};
|
||||
|
||||
if (!permission) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!permission.granted) {
|
||||
return (
|
||||
<Modal visible={visible} transparent animationType="slide">
|
||||
<View style={styles.permissionContainer}>
|
||||
<View style={styles.permissionContent}>
|
||||
<Ionicons name="camera-outline" size={64} color={theme.colors.primary} />
|
||||
<Text style={styles.permissionTitle}>Camera Permission Required</Text>
|
||||
<Text style={styles.permissionText}>
|
||||
We need access to your camera to scan food barcodes.
|
||||
</Text>
|
||||
<TouchableOpacity onPress={requestPermission} style={styles.permissionButtonContainer}>
|
||||
<LinearGradient
|
||||
colors={theme.gradients.primary}
|
||||
style={styles.permissionButton}
|
||||
>
|
||||
<Text style={styles.permissionButtonText}>Grant Permission</Text>
|
||||
</LinearGradient>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity onPress={onClose} style={styles.cancelButton}>
|
||||
<Text style={styles.cancelButtonText}>Cancel</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal visible={visible} animationType="slide">
|
||||
<View style={styles.container}>
|
||||
{!foodData ? (
|
||||
<>
|
||||
<View style={styles.header}>
|
||||
<TouchableOpacity onPress={onClose} style={styles.closeButton}>
|
||||
<Ionicons name="close" size={28} color="#fff" />
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.title}>Scan Food Barcode</Text>
|
||||
<View style={{ width: 28 }} />
|
||||
</View>
|
||||
|
||||
<CameraView
|
||||
style={styles.camera}
|
||||
facing="back"
|
||||
onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
|
||||
barcodeScannerSettings={{
|
||||
barcodeTypes: ['ean13', 'ean8', 'upc_a', 'upc_e', 'code128', 'code39'],
|
||||
}}
|
||||
>
|
||||
<View style={styles.scanOverlay}>
|
||||
<View style={styles.scanFrame} />
|
||||
<Text style={styles.scanText}>Position barcode within frame</Text>
|
||||
</View>
|
||||
</CameraView>
|
||||
</>
|
||||
) : (
|
||||
<View style={styles.resultContainer}>
|
||||
<View style={styles.resultHeader}>
|
||||
<TouchableOpacity onPress={onClose} style={styles.closeButton}>
|
||||
<Ionicons name="close" size={28} color={theme.colors.gray900} />
|
||||
</TouchableOpacity>
|
||||
<Text style={styles.resultTitle}>Food Details</Text>
|
||||
<View style={{ width: 28 }} />
|
||||
</View>
|
||||
|
||||
<View style={styles.foodCard}>
|
||||
<View style={styles.foodIconContainer}>
|
||||
<LinearGradient
|
||||
colors={theme.gradients.success}
|
||||
style={styles.foodIcon}
|
||||
>
|
||||
<Ionicons name="restaurant" size={32} color="#fff" />
|
||||
</LinearGradient>
|
||||
</View>
|
||||
|
||||
<Text style={styles.foodName}>{foodData.name}</Text>
|
||||
<Text style={styles.servingSize}>{foodData.servingSize}</Text>
|
||||
|
||||
<View style={styles.caloriesBadge}>
|
||||
<Text style={styles.caloriesValue}>{foodData.calories}</Text>
|
||||
<Text style={styles.caloriesLabel}>kcal per serving</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.servingsContainer}>
|
||||
<Text style={styles.label}>Number of Servings</Text>
|
||||
<View style={styles.servingsInput}>
|
||||
<TouchableOpacity
|
||||
onPress={() => setServings(String(Math.max(0.5, parseFloat(servings || '1') - 0.5)))}
|
||||
style={styles.servingsButton}
|
||||
>
|
||||
<Ionicons name="remove" size={20} color={theme.colors.primary} />
|
||||
</TouchableOpacity>
|
||||
<TextInput
|
||||
style={styles.servingsValue}
|
||||
value={servings}
|
||||
onChangeText={setServings}
|
||||
keyboardType="decimal-pad"
|
||||
/>
|
||||
<TouchableOpacity
|
||||
onPress={() => setServings(String(parseFloat(servings || '1') + 0.5))}
|
||||
style={styles.servingsButton}
|
||||
>
|
||||
<Ionicons name="add" size={20} color={theme.colors.primary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.totalCalories}>
|
||||
<Text style={styles.totalLabel}>Total Calories</Text>
|
||||
<Text style={styles.totalValue}>
|
||||
{Math.round(foodData.calories * parseFloat(servings || '1'))} kcal
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.buttonRow}>
|
||||
<TouchableOpacity onPress={handleRescan} style={styles.rescanButton}>
|
||||
<Text style={styles.rescanButtonText}>Scan Again</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity onPress={handleConfirm} style={styles.confirmButtonContainer}>
|
||||
<LinearGradient
|
||||
colors={theme.gradients.success}
|
||||
style={styles.confirmButton}
|
||||
>
|
||||
<Text style={styles.confirmButtonText}>Add to Diary</Text>
|
||||
</LinearGradient>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#000',
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: 20,
|
||||
paddingTop: 60,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.8)',
|
||||
},
|
||||
closeButton: {
|
||||
padding: 4,
|
||||
},
|
||||
title: {
|
||||
fontSize: 18,
|
||||
fontWeight: '700',
|
||||
color: '#fff',
|
||||
},
|
||||
camera: {
|
||||
flex: 1,
|
||||
},
|
||||
scanOverlay: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.3)',
|
||||
},
|
||||
scanFrame: {
|
||||
width: 250,
|
||||
height: 250,
|
||||
borderWidth: 2,
|
||||
borderColor: '#fff',
|
||||
borderRadius: 20,
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
scanText: {
|
||||
color: '#fff',
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
marginTop: 24,
|
||||
textAlign: 'center',
|
||||
},
|
||||
resultContainer: {
|
||||
flex: 1,
|
||||
backgroundColor: theme.colors.background,
|
||||
},
|
||||
resultHeader: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: 20,
|
||||
paddingTop: 60,
|
||||
backgroundColor: '#fff',
|
||||
},
|
||||
resultTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: '700',
|
||||
color: theme.colors.gray900,
|
||||
},
|
||||
foodCard: {
|
||||
margin: 20,
|
||||
padding: 24,
|
||||
backgroundColor: '#fff',
|
||||
borderRadius: 24,
|
||||
alignItems: 'center',
|
||||
...theme.shadows.medium,
|
||||
},
|
||||
foodIconContainer: {
|
||||
marginBottom: 16,
|
||||
},
|
||||
foodIcon: {
|
||||
width: 80,
|
||||
height: 80,
|
||||
borderRadius: 40,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
foodName: {
|
||||
fontSize: 24,
|
||||
fontWeight: '700',
|
||||
color: theme.colors.gray900,
|
||||
marginBottom: 8,
|
||||
textAlign: 'center',
|
||||
},
|
||||
servingSize: {
|
||||
fontSize: 16,
|
||||
color: theme.colors.gray600,
|
||||
marginBottom: 24,
|
||||
},
|
||||
caloriesBadge: {
|
||||
backgroundColor: theme.colors.gray50,
|
||||
paddingHorizontal: 24,
|
||||
paddingVertical: 16,
|
||||
borderRadius: 16,
|
||||
alignItems: 'center',
|
||||
marginBottom: 32,
|
||||
},
|
||||
caloriesValue: {
|
||||
fontSize: 32,
|
||||
fontWeight: '700',
|
||||
color: theme.colors.primary,
|
||||
},
|
||||
caloriesLabel: {
|
||||
fontSize: 14,
|
||||
color: theme.colors.gray600,
|
||||
marginTop: 4,
|
||||
},
|
||||
servingsContainer: {
|
||||
width: '100%',
|
||||
marginBottom: 24,
|
||||
},
|
||||
label: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: theme.colors.gray700,
|
||||
marginBottom: 12,
|
||||
},
|
||||
servingsInput: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 16,
|
||||
},
|
||||
servingsButton: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 20,
|
||||
backgroundColor: theme.colors.gray100,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
servingsValue: {
|
||||
fontSize: 24,
|
||||
fontWeight: '700',
|
||||
color: theme.colors.gray900,
|
||||
textAlign: 'center',
|
||||
minWidth: 60,
|
||||
},
|
||||
totalCalories: {
|
||||
width: '100%',
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
paddingTop: 24,
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: theme.colors.gray200,
|
||||
},
|
||||
totalLabel: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: theme.colors.gray700,
|
||||
},
|
||||
totalValue: {
|
||||
fontSize: 20,
|
||||
fontWeight: '700',
|
||||
color: theme.colors.gray900,
|
||||
},
|
||||
buttonRow: {
|
||||
flexDirection: 'row',
|
||||
padding: 20,
|
||||
gap: 12,
|
||||
},
|
||||
rescanButton: {
|
||||
flex: 1,
|
||||
paddingVertical: 16,
|
||||
borderRadius: 20,
|
||||
backgroundColor: theme.colors.gray100,
|
||||
alignItems: 'center',
|
||||
},
|
||||
rescanButtonText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '700',
|
||||
color: theme.colors.gray700,
|
||||
},
|
||||
confirmButtonContainer: {
|
||||
flex: 1,
|
||||
},
|
||||
confirmButton: {
|
||||
paddingVertical: 16,
|
||||
borderRadius: 20,
|
||||
alignItems: 'center',
|
||||
},
|
||||
confirmButtonText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '700',
|
||||
color: '#fff',
|
||||
},
|
||||
permissionContainer: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.5)',
|
||||
},
|
||||
permissionContent: {
|
||||
backgroundColor: '#fff',
|
||||
borderRadius: 24,
|
||||
padding: 32,
|
||||
margin: 20,
|
||||
alignItems: 'center',
|
||||
...theme.shadows.strong,
|
||||
},
|
||||
permissionTitle: {
|
||||
fontSize: 20,
|
||||
fontWeight: '700',
|
||||
color: theme.colors.gray900,
|
||||
marginTop: 16,
|
||||
marginBottom: 8,
|
||||
},
|
||||
permissionText: {
|
||||
fontSize: 16,
|
||||
color: theme.colors.gray600,
|
||||
textAlign: 'center',
|
||||
marginBottom: 24,
|
||||
},
|
||||
permissionButtonContainer: {
|
||||
width: '100%',
|
||||
marginBottom: 12,
|
||||
},
|
||||
permissionButton: {
|
||||
paddingVertical: 16,
|
||||
borderRadius: 20,
|
||||
alignItems: 'center',
|
||||
},
|
||||
permissionButtonText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '700',
|
||||
color: '#fff',
|
||||
},
|
||||
cancelButton: {
|
||||
paddingVertical: 12,
|
||||
},
|
||||
cancelButtonText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: theme.colors.gray600,
|
||||
},
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
export const API_BASE_URL = __DEV__
|
||||
? 'https://694d46f62d87.ngrok-free.app'
|
||||
? 'https://8679109544e4.ngrok-free.app'
|
||||
: 'https://your-production-url.com'
|
||||
|
||||
export const API_ENDPOINTS = {
|
||||
|
||||
Reference in new issue
Block a user