muller-reporting-sys/TROUBLESHOOTING.md
2025-11-12 22:21:35 +03:00

424 lines
7.3 KiB
Markdown

# Troubleshooting Guide
## Issue: CredentialsSignin Error
### Problem
Getting `[auth][error] CredentialsSignin` error when trying to login.
### Root Cause
The database had old seed data without passwords. When the schema was updated to add password fields, existing records didn't get the new password values.
### Solution ✅
1. Reset the database:
```bash
npx prisma db push --force-reset
```
2. Re-seed with fresh data:
```bash
npx prisma db seed
```
3. Verify data:
```bash
node check-db.mjs
```
### Prevention
Always reset the database when adding new required/important fields to existing models.
---
## Issue: "Invalid credentials" on Login
### Possible Causes
#### 1. Wrong Email or Password
**Check:**
- Admin: admin@muller.com / admin123
- Managers: *.muller.com / muller123
- Operators: *.muller.com / muller123
#### 2. Wrong User Type Selected
**Check:**
- Make sure you select the correct user type dropdown
- Admin emails only work with "Admin" type
- Manager emails only work with "Shift Manager" type
- Operator emails only work with "Operator" type
#### 3. Database Not Seeded
**Solution:**
```bash
npx prisma db seed
```
#### 4. Prisma Client Not Generated
**Solution:**
```bash
npx prisma generate
```
---
## Issue: User Not Found
### Check Database
Create a file `check-db.mjs`:
```javascript
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function check() {
const admin = await prisma.admin.findUnique({
where: { email: 'admin@muller.com' }
})
console.log('Admin:', admin)
const manager = await prisma.shiftManager.findFirst({
where: { email: 'james.anderson@muller.com' }
})
console.log('Manager:', manager)
await prisma.$disconnect()
}
check()
```
Run: `node check-db.mjs`
---
## Issue: Database Connection Error
### Check .env File
Verify `DATABASE_URL` is correct:
```
DATABASE_URL="postgresql://user:password@localhost:5432/muller_db"
```
### Check PostgreSQL is Running
```bash
# Windows
services.msc
# Look for PostgreSQL service
# Or check connection
psql -U postgres -d muller_db
```
---
## Issue: Shift Not Appearing for Operator
### Checklist
1. ✅ Shift was created for today's date
2. ✅ Operator is assigned to the shift
3. ✅ Shift status is "active"
4. ✅ Operator's email matches the one used to login
5. ✅ Operator's job position is "Blow Moulder Level 1"
### Debug Query
```javascript
const worker = await prisma.worker.findFirst({
where: { email: 'david.wilson.red@muller.com' }
})
const shifts = await prisma.shiftTeamMember.findMany({
where: { workerId: worker.id },
include: { shift: true, machine: true }
})
console.log(shifts)
```
---
## Issue: Data Not Saving
### Check Browser Console
1. Open DevTools (F12)
2. Go to Console tab
3. Look for errors when clicking Save
### Check Network Tab
1. Open DevTools (F12)
2. Go to Network tab
3. Click Save button
4. Look for failed requests (red)
5. Click on the request to see error details
### Common Causes
- API route not found (404)
- Server error (500)
- Invalid data format
- Missing required fields
---
## Issue: Charts Not Displaying
### Check Data Format
Bottle weight tracking data should be:
```javascript
[
{
time: "2024-01-01T08:00:00Z",
bottle1: 33.8,
bottle2: 34.1,
bottle3: 34.0,
bottle4: 33.9,
average: 33.95,
upperLimit: 34.45,
lowerLimit: 33.45
}
]
```
### Check Recharts Installation
```bash
npm list recharts
```
If not installed:
```bash
npm install recharts
```
---
## Issue: Session Expired / Logged Out
### Cause
NextAuth sessions expire after a period of inactivity.
### Solution
Simply login again. To extend session time, update `lib/auth.ts`:
```typescript
export const { handlers, signIn, signOut, auth } = NextAuth({
session: {
maxAge: 30 * 24 * 60 * 60, // 30 days
},
// ... rest of config
})
```
---
## Issue: Cannot Access Admin/Manager/Operator Pages
### Check Middleware
Verify `middleware.ts` exists and is configured:
```typescript
export { auth as middleware } from "./lib/auth"
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|login).*)"],
}
```
### Check Session
Add debug logging in page:
```typescript
import { auth } from "@/lib/auth"
export default async function Page() {
const session = await auth()
console.log('Session:', session)
// ...
}
```
---
## Issue: Build Errors
### TypeScript Errors
```bash
npx tsc --noEmit
```
### Fix Common Issues
1. Missing types: `npm install @types/node @types/react -D`
2. Prisma client: `npx prisma generate`
3. Clear cache: `rm -rf .next`
---
## Issue: Development Server Won't Start
### Check Port
Port 3000 might be in use:
```bash
# Windows
netstat -ano | findstr :3000
taskkill /PID <PID> /F
# Or use different port
npm run dev -- -p 3001
```
### Check Dependencies
```bash
npm install
```
### Clear Cache
```bash
rm -rf .next
rm -rf node_modules
npm install
```
---
## Debug Mode
### Enable NextAuth Debug
Already enabled in development. Check terminal for logs:
```
Attempting login for admin@muller.com as admin
Admin login successful
```
### Enable Prisma Logging
Update `lib/prisma.ts`:
```typescript
export const prisma = new PrismaClient({
log: ['query', 'info', 'warn', 'error'],
})
```
---
## Quick Fixes
### Reset Everything
```bash
# Reset database
npx prisma db push --force-reset
# Seed data
npx prisma db seed
# Clear Next.js cache
rm -rf .next
# Restart dev server
npm run dev
```
### Verify Installation
```bash
# Check Node version (should be 18+)
node --version
# Check npm packages
npm list --depth=0
# Check Prisma
npx prisma --version
```
---
## Getting Help
### Check Logs
1. **Terminal** - Server-side errors
2. **Browser Console** - Client-side errors
3. **Network Tab** - API errors
### Collect Information
When reporting issues, include:
- Error message (full stack trace)
- Steps to reproduce
- Browser and version
- Node version
- Operating system
- Relevant code snippets
---
## Common Error Messages
### "Prisma Client not found"
```bash
npx prisma generate
```
### "Cannot find module '@prisma/client'"
```bash
npm install @prisma/client
```
### "Database connection failed"
Check PostgreSQL is running and DATABASE_URL is correct
### "Invalid `prisma.xxx.findXxx()` invocation"
Schema and database are out of sync:
```bash
npx prisma db push
```
### "Module not found: Can't resolve 'bcryptjs'"
```bash
npm install bcryptjs
```
---
## Performance Issues
### Slow Queries
Add indexes to frequently queried fields in `schema.prisma`:
```prisma
model Worker {
email String? @unique
empNo String @unique
// ...
}
```
### Large Data Sets
Implement pagination:
```typescript
const workers = await prisma.worker.findMany({
take: 50,
skip: page * 50
})
```
---
## Security Checklist
✅ Passwords are hashed with bcrypt
✅ Sessions are secure (httpOnly cookies)
✅ Routes are protected with middleware
✅ Environment variables are not committed
✅ SQL injection prevented (Prisma)
✅ XSS prevented (React escaping)
---
## Maintenance
### Regular Tasks
- [ ] Backup database weekly
- [ ] Update dependencies monthly
- [ ] Review logs for errors
- [ ] Test all user flows
- [ ] Archive old shifts
### Database Backup
```bash
pg_dump -U postgres muller_db > backup.sql
```
### Database Restore
```bash
psql -U postgres muller_db < backup.sql
```