All files / src/components FlyerCorrectionTool.tsx

95.95% Statements 95/99
89.18% Branches 33/37
94.11% Functions 16/17
100% Lines 92/92

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255                                      1x           44x 44x 44x 44x 44x 44x 44x     44x 13x 12x 12x 10x   10x 10x 10x     1x 1x         44x 21x 21x 21x   20x 20x     20x 20x   20x   20x 7x 7x 7x 7x       44x 20x 20x 20x 20x     44x     14x 14x 14x 14x           44x 7x 7x 7x     44x 7x 7x 7x           7x     44x 7x 7x 7x     44x 5x 5x                 5x 1x               1x 1x     4x       4x 4x   4x 4x 4x   4x           4x   4x 4x 3x 3x 1x 1x     2x 2x 2x 2x 2x   2x 2x 2x   4x 4x       44x   43x 43x               6x                                                                                 4x             1x                          
// src/components/FlyerCorrectionTool.tsx
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { XCircleIcon } from './icons/XCircleIcon';
import { ScissorsIcon } from './icons/ScissorsIcon';
import { RefreshCwIcon } from './icons/RefreshCwIcon';
import * as aiApiClient from '../services/aiApiClient';
import { notifyError, notifySuccess } from '../services/notificationService';
import { logger } from '../services/logger.client';
 
export interface FlyerCorrectionToolProps {
  isOpen: boolean;
  onClose: () => void;
  imageUrl: string;
  onDataExtracted: (type: 'store_name' | 'dates', value: string) => void;
}
 
type Rect = { x: number; y: number; width: number; height: number };
type ExtractionType = 'store_name' | 'dates';
 
export const FlyerCorrectionTool: React.FC<FlyerCorrectionToolProps> = ({
  isOpen,
  onClose,
  imageUrl,
  onDataExtracted,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const imageRef = useRef<HTMLImageElement>(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [selectionRect, setSelectionRect] = useState<Rect | null>(null);
  const [startPoint, setStartPoint] = useState<{ x: number; y: number } | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [imageFile, setImageFile] = useState<File | null>(null);
 
  // Fetch the image and store it as a File object for API submission
  useEffect(() => {
    if (isOpen && imageUrl) {
      logger.debug({ imageUrl }, '[FlyerCorrectionTool] isOpen is true, fetching image URL');
      fetch(imageUrl)
        .then((res) => res.blob())
        .then((blob) => {
          const file = new File([blob], 'flyer-image.jpg', { type: blob.type });
          setImageFile(file);
          logger.debug('[FlyerCorrectionTool] Image fetched and stored as File object');
        })
        .catch((err) => {
          logger.error({ err }, '[FlyerCorrectionTool] Failed to fetch image');
          notifyError('Could not load the image for correction.');
        });
    }
  }, [isOpen, imageUrl]);
 
  const draw = useCallback(() => {
    const canvas = canvasRef.current;
    const image = imageRef.current;
    if (!canvas || !image) return;
 
    const ctx = canvas.getContext('2d');
    Iif (!ctx) return;
 
    // Set canvas size to match image display size
    canvas.width = image.clientWidth;
    canvas.height = image.clientHeight;
 
    ctx.clearRect(0, 0, canvas.width, canvas.height);
 
    if (selectionRect) {
      ctx.strokeStyle = '#f59e0b'; // amber-500
      ctx.lineWidth = 2;
      ctx.setLineDash([6, 3]);
      ctx.strokeRect(selectionRect.x, selectionRect.y, selectionRect.width, selectionRect.height);
    }
  }, [selectionRect]);
 
  useEffect(() => {
    draw();
    const handleResize = () => draw();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [draw]);
 
  const getCanvasCoordinates = (
    e: React.MouseEvent<HTMLCanvasElement>,
  ): { x: number; y: number } => {
    const canvas = canvasRef.current;
    Iif (!canvas) return { x: 0, y: 0 };
    const rect = canvas.getBoundingClientRect();
    return {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    };
  };
 
  const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
    setIsDrawing(true);
    setStartPoint(getCanvasCoordinates(e));
    setSelectionRect(null);
  };
 
  const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
    Iif (!isDrawing || !startPoint) return;
    const currentPoint = getCanvasCoordinates(e);
    const rect = {
      x: Math.min(startPoint.x, currentPoint.x),
      y: Math.min(startPoint.y, currentPoint.y),
      width: Math.abs(startPoint.x - currentPoint.x),
      height: Math.abs(startPoint.y - currentPoint.y),
    };
    setSelectionRect(rect);
  };
 
  const handleMouseUp = () => {
    setIsDrawing(false);
    setStartPoint(null);
    logger.debug({ selectionRect }, '[FlyerCorrectionTool] Mouse Up - selection complete');
  };
 
  const handleRescan = async (type: ExtractionType) => {
    logger.debug({ type }, '[FlyerCorrectionTool] handleRescan triggered');
    logger.debug(
      {
        hasSelectionRect: !!selectionRect,
        hasImageRef: !!imageRef.current,
        hasImageFile: !!imageFile,
      },
      '[FlyerCorrectionTool] handleRescan state',
    );
 
    if (!selectionRect || !imageRef.current || !imageFile) {
      logger.warn(
        {
          hasSelectionRect: !!selectionRect,
          hasImageRef: !!imageRef.current,
          hasImageFile: !!imageFile,
        },
        '[FlyerCorrectionTool] handleRescan: Guard failed. Missing prerequisites',
      );
      notifyError('Please select an area on the image first.');
      return;
    }
 
    logger.debug(
      { type },
      '[FlyerCorrectionTool] handleRescan: Prerequisites met. Starting processing',
    );
    setIsProcessing(true);
    try {
      // Scale selection coordinates to the original image dimensions
      const image = imageRef.current;
      const scaleX = image.naturalWidth / image.clientWidth;
      const scaleY = image.naturalHeight / image.clientHeight;
 
      const cropArea = {
        x: selectionRect.x * scaleX,
        y: selectionRect.y * scaleY,
        width: selectionRect.width * scaleX,
        height: selectionRect.height * scaleY,
      };
      logger.debug({ cropArea }, '[FlyerCorrectionTool] handleRescan: Calculated scaled cropArea');
 
      logger.debug('[FlyerCorrectionTool] handleRescan: Awaiting aiApiClient.rescanImageArea');
      const response = await aiApiClient.rescanImageArea(imageFile, cropArea, type);
      logger.debug({ ok: response.ok }, '[FlyerCorrectionTool] handleRescan: API call returned');
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to rescan area.');
      }
 
      const { text } = await response.json();
      logger.debug({ text }, '[FlyerCorrectionTool] handleRescan: Successfully extracted text');
      notifySuccess(`Extracted: ${text}`);
      onDataExtracted(type, text);
      onClose(); // Close modal on success
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'An unknown error occurred.';
      logger.error({ err }, '[FlyerCorrectionTool] handleRescan: Caught an error');
      notifyError(msg);
    } finally {
      logger.debug('[FlyerCorrectionTool] handleRescan: Finished. Setting isProcessing=false');
      setIsProcessing(false);
    }
  };
 
  if (!isOpen) return null;
 
  logger.debug({ isProcessing, hasSelection: !!selectionRect }, '[FlyerCorrectionTool] Rendering');
  return (
    <div
      className="fixed inset-0 bg-black bg-opacity-75 z-50 flex justify-center items-center p-4"
      onClick={onClose}
    >
      <div
        role="dialog"
        className="relative bg-gray-800 rounded-lg shadow-xl w-full max-w-6xl h-[90vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex justify-between items-center p-4 border-b border-gray-700">
          <h2 className="text-lg font-semibold text-white flex items-center">
            <ScissorsIcon className="w-6 h-6 mr-2" /> Flyer Correction Tool
          </h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-white"
            aria-label="Close correction tool"
          >
            <XCircleIcon className="w-7 h-7" />
          </button>
        </div>
        <div className="grow p-4 overflow-auto relative flex justify-center items-center">
          <img
            ref={imageRef}
            src={imageUrl}
            alt="Flyer for correction"
            className="max-w-full max-h-full object-contain"
            onLoad={draw}
          />
          <canvas
            ref={canvasRef}
            className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 cursor-crosshair"
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
            onMouseLeave={handleMouseUp}
          />
        </div>
 
        <div className="p-4 border-t border-gray-700 flex items-center justify-center space-x-4">
          {isProcessing ? (
            <div className="flex items-center text-white">
              <RefreshCwIcon className="w-5 h-5 mr-2 animate-spin" />
              <span>Processing...</span>
            </div>
          ) : (
            <>
              <button
                onClick={() => handleRescan('store_name')}
                disabled={!selectionRect || isProcessing}
                className="px-4 py-2 bg-blue-600 text-white rounded-md disabled:bg-gray-500 disabled:cursor-not-allowed hover:bg-blue-700 transition-colors"
              >
                Extract Store Name
              </button>
              <button
                onClick={() => handleRescan('dates')}
                disabled={!selectionRect || isProcessing}
                className="px-4 py-2 bg-green-600 text-white rounded-md disabled:bg-gray-500 disabled:cursor-not-allowed hover:bg-green-700 transition-colors"
              >
                Extract Sale Dates
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
};