מדריך פתרון בעיות - מערכת סריקת מסמכים

פתרונות לבעיות נפוצות ודרכי פתרון תקלות

שגיאות JavaScript

TypeError: this.documents.map is not a function HIGH
Error loading documents: TypeError: this.documents.map is not a function
    at EmailScanningManager.renderDocuments (email-scanning-manager.js:145)

סיבה: הAPI מחזיר נתונים עטופים ב-success_response אבל הקוד מצפה לנתונים ישירים.

✅ פתרון:

שנה את הטיפול בתשובות API לחילוץ הנתונים מ-result.data:

// ❌ שגוי
async loadDocuments() {
    const response = await fetch('/api/email-scanning/documents');
    const data = await response.json();
    this.documents = data.documents;  // ← זה יכשל!
}

// ✅ נכון
async loadDocuments() {
    const response = await fetch('/api/email-scanning/documents');
    const result = await response.json();

    // חלץ נתונים מ-success_response wrapper
    const data = result.data || result;

    // וודא שזה מערך
    this.documents = Array.isArray(data)
        ? data
        : (data.documents || []);

    console.log('✅ Loaded', this.documents.length, 'documents');
}
חשוב: החל את התבנית הזאת על כל קריאות ה-API במערכת!
Cannot read property 'length' of undefined MEDIUM

סיבה: ניסיון לגשת לנתונים שעדיין לא נטענו או לא קיימים.

✅ פתרון:

השתמש ב-nullish coalescing והגנה מפני undefined:

// הוסף בדיקות
renderDocuments() {
    if (!this.documents || !Array.isArray(this.documents)) {
        console.warn('No documents to render');
        return;
    }

    this.documents.forEach(doc => {
        // הגנה על שדות שעלולים להיות null
        const supplierName = doc.supplier_name || 'לא זוהה';
        const amount = doc.total_amount?.toFixed(2) || '-';
    });
}
Failed to fetch / Network Error HIGH

סיבות אפשריות:

  • המשתמש לא מחובר (401 Unauthorized)
  • בעיית רשת או שרת לא זמין
  • CORS issues (במפתחים מקומי)
✅ פתרון:
  1. בדוק אם המשתמש מחובר:
async loadDocuments() {
    try {
        const response = await fetch('/api/email-scanning/documents', {
            credentials: 'include'  // ← חשוב! כלול cookies
        });

        if (response.status === 401 || response.status === 302) {
            // הפנה לדף התחברות
            window.location.href = '/auth/login?next=' + window.location.pathname;
            return;
        }

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        // המשך עיבוד...
    } catch (error) {
        console.error('Error loading documents:', error);
        this.showError('שגיאה בטעינת מסמכים. אנא רענן את הדף.');
    }
}
  1. בדוק ב-Developer Console (F12):
  • לשונית Network - בדוק את קוד התשובה (200/401/500)
  • לשונית Console - חפש הודעות שגיאה
  • בדוק שה-URL נכון

בעיות העלאה

"סוג קובץ לא נתמך" LOW

סיבה: ניסיון להעלות קובץ שאינו בפורמט נתמך.

✅ פתרון:

המערכת תומכת רק ב:

  • PDF (.pdf)
  • תמונות: JPG (.jpg, .jpeg), PNG (.png)

המר קבצים:

  • Word/Excel → PDF באמצעות "שמור כ-PDF"
  • תמונות HEIC/WebP → JPG/PNG באמצעות ממיר אונליין
"גודל הקובץ חורג מהמותר" MEDIUM

סיבה: קובץ גדול מ-10MB.

✅ פתרון:

אפשרות 1: דחוס את הקובץ

  • PDF: השתמש ב-Adobe Acrobat או אתרים כמו ilovepdf.com
  • תמונות: הקטן רזולוציה או דחוס ב-tinypng.com

אפשרות 2: פצל לקבצים קטנים

  • פצל PDF רב-עמודים למספר קבצים
  • העלה כל חלק בנפרד

למפתחים - שינוי המגבלה:

# config.py
MAX_CONTENT_LENGTH = 20 * 1024 * 1024  # 20MB

# או במשתנה סביבה:
MAX_FILE_SIZE_MB=20
העלאה תקועה ב-0% או נכשלת באמצע HIGH

סיבות אפשריות:

  • חיבור אינטרנט איטי או לא יציב
  • Timeout של השרת
  • בעיה בחלל דיסק בשרת
✅ פתרון:

צד משתמש:

  • בדוק חיבור אינטרנט
  • נסה להעלות קובץ קטן יותר תחילה
  • רענן דף ונסה שוב
  • נסה דפדפן אחר

צד מפתח:

# בדוק שטח דיסק פנוי
docker exec techlabs-web df -h

# בדוק logs
docker logs techlabs-web --tail 100

# הגדל timeout של Gunicorn
# gunicorn.conf.py
timeout = 300  # 5 minutes

בעיות OCR

סטטוס OCR תקוע ב-"processing" HIGH

סיבה: Celery worker לא רץ או נתקע.

✅ פתרון:

1 בדוק אם Celery worker רץ:

# בדוק container
docker ps | grep celery

# בדוק logs של celery
docker logs techlabs-celery --tail 50

2 אם לא רץ, הפעל מחדש:

docker-compose restart celery

3 בדוק את Redis (message broker):

# התחבר ל-Redis
docker exec -it techlabs-redis redis-cli

# בדוק חיבור
127.0.0.1:6379> PING
PONG

# בדוק תור משימות
127.0.0.1:6379> LLEN celery

# יציאה
127.0.0.1:6379> exit

4 אתחל מסמכים תקועים:

# Python shell
docker exec -it techlabs-web flask shell

>>> from app.models_email_scanning import ScannedDocument
>>> from app import db
>>> stuck_docs = ScannedDocument.query.filter_by(ocr_status='processing').all()
>>> for doc in stuck_docs:
...     doc.ocr_status = 'pending'
...
>>> db.session.commit()
>>> exit()
OCR נכשל: "No text extracted" MEDIUM

סיבות אפשריות:

  • מסמך סרוק באיכות נמוכה
  • תמונה מטושטשת
  • פונט לא נתמך
  • Tesseract לא מותקן או לא מוגדר
✅ פתרון:

שפר את איכות המסמך:

  • סרוק ברזולוציה גבוהה יותר (300 DPI)
  • ודא שהטקסט חד וברור
  • הימנע מרקע מבולגן

בדוק התקנת Tesseract:

# בדוק אם tesseract מותקן
docker exec techlabs-web tesseract --version

# בדוק שפות זמינות
docker exec techlabs-web tesseract --list-langs

# צריך לראות:
# heb (Hebrew)
# eng (English)

אם Tesseract לא מותקן:

# הוסף ל-Dockerfile
RUN apt-get update && apt-get install -y \
    tesseract-ocr \
    tesseract-ocr-heb \
    tesseract-ocr-eng

# Build מחדש
docker-compose build web
docker-compose up -d
דיוק OCR נמוך - זיהוי לא מדויק MEDIUM
✅ פתרון:

1. שדרג ל-Google Cloud Vision:

# הגדר credentials
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"

# הפעל OCR עם Google Vision
curl -X POST http://localhost/api/email-scanning/documents/123/ocr \
  -d '{"provider": "google_vision"}'

2. שפר קדם-עיבוד תמונה:

# עריכה ב-email_scanning_ocr_service.py
from PIL import Image, ImageEnhance, ImageFilter

def preprocess_image(image_path):
    img = Image.open(image_path)

    # המר לגווני אפור
    img = img.convert('L')

    # הגבר ניגודיות
    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(2.0)

    # החד פרטים
    img = img.filter(ImageFilter.SHARPEN)

    # שמור
    processed_path = image_path.replace('.', '_processed.')
    img.save(processed_path)

    return processed_path

אינטגרציית אימייל

Gmail OAuth: "Invalid credentials" או "Access denied" HIGH
✅ פתרון:

1 בדוק הגדרות Google Cloud Console:

  • Gmail API מופעל בפרויקט
  • OAuth 2.0 Client ID נוצר
  • Redirect URI מוגדר נכון: https://labs.levor.io/email-integration/gmail-callback
  • Scopes מוגדרים: gmail.readonly, gmail.modify

2 בדוק משתני סביבה:

# .env או docker-compose.yml
GMAIL_CLIENT_ID=your-client-id.apps.googleusercontent.com
GMAIL_CLIENT_SECRET=your-client-secret
GMAIL_REDIRECT_URI=https://labs.levor.io/email-integration/gmail-callback

3 אתחל אישור גישה:

  • לך ל-Settings → Email Integration
  • לחץ "Connect Gmail Account"
  • עקוב אחר תהליך ההתחברות
  • אשר את ההרשאות
IMAP Connection Failed HIGH
✅ פתרון:

בדוק הגדרות IMAP:

ספק שרת פורט SSL
Gmail imap.gmail.com 993
Outlook outlook.office365.com 993
Yahoo imap.mail.yahoo.com 993

ב-Gmail - הפעל App Password:

  • לך ל-Google Account → Security
  • הפעל 2-Step Verification
  • צור App Password
  • השתמש ב-App Password במקום הסיסמה הרגילה

בדוק חיבור באופן ידני:

# Test IMAP connection
docker exec -it techlabs-web python3 << EOF
import imaplib

try:
    imap = imaplib.IMAP4_SSL('imap.gmail.com', 993)
    imap.login('your-email@gmail.com', 'your-app-password')
    print("✅ Connection successful!")
    imap.logout()
except Exception as e:
    print(f"❌ Connection failed: {e}")
EOF

בעיות ביצועים

דף טעינה איטית MEDIUM
✅ פתרון:

1. בדוק ביצועי API:

# Developer Console → Network
# בדוק זמני תגובה של API calls
# זמן רצוי: < 500ms

2. הוסף אינדקסים למסד נתונים:

# migrations/versions/xxxx_add_indexes.py
def upgrade():
    op.create_index('idx_scanned_documents_user_id',
                    'scanned_documents', ['user_id'])
    op.create_index('idx_scanned_documents_category_id',
                    'scanned_documents', ['category_id'])
    op.create_index('idx_scanned_documents_upload_date',
                    'scanned_documents', ['upload_date'])
    op.create_index('idx_scanned_documents_status',
                    'scanned_documents', ['status'])

3. השתמש ב-caching:

# הפעל Redis caching
from flask_caching import Cache

cache = Cache(app, config={
    'CACHE_TYPE': 'redis',
    'CACHE_REDIS_URL': 'redis://redis:6379/1'
})

@cache.cached(timeout=300)  # 5 minutes
@email_scanning_api.route('/api/email-scanning/statistics')
def get_statistics():
    # ... expensive query
    return success_response(stats)

4. הגבל pagination:

// Frontend - טען רק 20 מסמכים בכל פעם
async loadDocuments(page = 1) {
    const response = await fetch(
        `/api/email-scanning/documents?page=${page}&per_page=20`
    );
}

בעיות מסד נתונים

"Database connection failed" או "Could not connect to server" HIGH
✅ פתרון:

1 בדוק שה-database container רץ:

docker ps | grep postgres

# אם לא רץ:
docker-compose up -d db

2 בדוק connection string:

# .env או docker-compose.yml
DATABASE_URL=postgresql://user:password@db:5432/techlabs

# בדוק שהפרטים נכונים
docker exec techlabs-web env | grep DATABASE_URL

3 נסה להתחבר ידנית:

# מתוך container
docker exec -it techlabs-db psql -U user -d techlabs

# מצב חיצוני (אם פורט חשוף)
psql -h localhost -p 5432 -U user -d techlabs
"Table does not exist" או "relation does not exist" HIGH
✅ פתרון:

הרץ migrations:

# יצירת migration חדש
docker exec techlabs-web flask db migrate -m "create tables"

# הרצת migrations
docker exec techlabs-web flask db upgrade

# בדוק אילו טבלאות קיימות
docker exec -it techlabs-db psql -U user -d techlabs -c "\dt"

בעיות התחברות

"Invalid email or password" MEDIUM
✅ פתרון:

אפס סיסמה:

# Flask shell
docker exec -it techlabs-web flask shell

>>> from app.models import User
>>> from app import db
>>> user = User.query.filter_by(email='admin@techlab.co.il').first()
>>> user.set_password('newpassword123')
>>> db.session.commit()
>>> print("✅ Password updated")
>>> exit()

בעיות Docker

Container לא עולה או נופל מיד HIGH
✅ פתרון:
# בדוק logs
docker logs techlabs-web --tail 100

# בדוק סטטוס
docker ps -a | grep techlabs

# הרץ מחדש
docker-compose down
docker-compose up -d

# Build מחדש
docker-compose build --no-cache
docker-compose up -d

קריאת Logs

לוגים הם המפתח לפתרון רוב הבעיות. הנה איך לקרוא אותם:

צפייה ב-logs בזמן אמת:

# Flask app logs
docker logs -f techlabs-web

# Celery worker logs
docker logs -f techlabs-celery

# Database logs
docker logs -f techlabs-db

# כל ה-containers
docker-compose logs -f

דוגמה ללוגים תקינים:

[2025-11-23 10:30:15] INFO: Starting Flask app...
[2025-11-23 10:30:16] INFO: Database connected successfully
[2025-11-23 10:30:16] INFO: EmailScanning module registered
[2025-11-23 10:30:17] INFO: Gunicorn listening on 0.0.0.0:8000
[2025-11-23 10:30:45] INFO: User login: admin@techlab.co.il
[2025-11-23 10:31:02] INFO: Document uploaded: invoice_001.pdf
[2025-11-23 10:31:03] INFO: OCR task queued: document_id=123

חיפוש שגיאות:

# חפש שגיאות
docker logs techlabs-web 2>&1 | grep -i error

# חפש exceptions
docker logs techlabs-web 2>&1 | grep -i exception

# חפש OCR failures
docker logs techlabs-celery | grep -i "ocr failed"

# שמור logs לקובץ
docker logs techlabs-web > /tmp/app.log 2>&1

כלי Debug

1. Flask Shell (Python REPL)

docker exec -it techlabs-web flask shell

>>> from app.models_email_scanning import *
>>> from app import db
>>>
>>> # ספור מסמכים
>>> ScannedDocument.query.count()
>>>
>>> # מצא מסמך
>>> doc = ScannedDocument.query.get(123)
>>> print(doc.filename, doc.ocr_status)
>>>
>>> # הרץ שאילתות
>>> docs = ScannedDocument.query.filter_by(status='pending').all()
>>> len(docs)

2. PostgreSQL Client

docker exec -it techlabs-db psql -U user -d techlabs

-- צפה בטבלאות
\dt

-- ספור מסמכים
SELECT COUNT(*) FROM scanned_documents;

-- מצא תקועים
SELECT id, filename, ocr_status
FROM scanned_documents
WHERE ocr_status = 'processing'
AND upload_date < NOW() - INTERVAL '1 hour';

-- יציאה
\q

3. Redis Monitoring

docker exec -it techlabs-redis redis-cli

127.0.0.1:6379> MONITOR  # צפה בכל הפעולות בזמן אמת
127.0.0.1:6379> KEYS *   # צפה בכל המפתחות
127.0.0.1:6379> LLEN celery  # אורך תור Celery

4. cURL Testing

# בדוק API endpoint
curl -i https://labs.levor.io/api/email-scanning/health

# עם authentication
curl -b cookies.txt \
  https://labs.levor.io/api/email-scanning/documents | jq

# POST request
curl -X POST \
  -b cookies.txt \
  -F "file=@invoice.pdf" \
  https://labs.levor.io/api/email-scanning/documents/upload
עדיין צריך עזרה?

אם הבעיה לא נפתרה:

  • אסוף logs מלאים: docker logs techlabs-web > /tmp/error.log 2>&1
  • תעד את השלבים שביצעת
  • פנה לצוות התמיכה עם המידע