All files / src/pages/admin/components CorrectionRow.tsx

97.5% Statements 78/80
95.45% Branches 42/44
94.44% Functions 17/18
98.7% Lines 76/77

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 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                                            1x           70x 70x 70x 70x 70x 70x 70x     70x 42x 42x 28x 28x 27x     15x 5x 6x 5x   10x 5x 6x 5x       5x     70x 4x   4x 4x 4x 4x 4x 3x 1x 1x 1x 1x   2x         2x     2x       2x 2x   4x     70x 7x 7x 7x 7x       5x 4x 4x   3x 3x       3x   7x       70x 28x   16x       4x           4x     1x       7x             4x     1x       7x             4x       1x             70x                                                                                                                             1x 1x 1x                       11x 11x 11x                 4x 4x                 1x 1x                              
// src/pages/admin/components/CorrectionRow.tsx
import React, { useState } from 'react';
import type { SuggestedCorrection, MasterGroceryItem, Category } from '../../../types';
import {
  approveCorrection,
  rejectCorrection,
  updateSuggestedCorrection,
} from '../../../services/apiClient'; // Ensure we are using apiClient
import { logger } from '../../../services/logger.client';
import { CheckIcon } from '../../../components/icons/CheckIcon';
import { XMarkIcon } from '../../../components/icons/XMarkIcon';
import { LoadingSpinner } from '../../../components/LoadingSpinner';
import { ConfirmationModal } from '../../../components/ConfirmationModal';
import { PencilIcon } from '../../../components/icons/PencilIcon';
 
interface CorrectionRowProps {
  correction: SuggestedCorrection;
  masterItems: MasterGroceryItem[];
  categories: Category[];
  onProcessed: (correctionId: number) => void;
}
 
export const CorrectionRow: React.FC<CorrectionRowProps> = ({
  correction: initialCorrection,
  masterItems,
  categories,
  onProcessed,
}) => {
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editableValue, setEditableValue] = useState(initialCorrection.suggested_value);
  const [currentCorrection, setCurrentCorrection] = useState(initialCorrection);
  const [actionToConfirm, setActionToConfirm] = useState<'approve' | 'reject' | null>(null);
 
  // Helper to make the suggested value more readable for the admin.
  const formatSuggestedValue = () => {
    const { correction_type, suggested_value } = currentCorrection;
    if (correction_type === 'WRONG_PRICE') {
      const priceInCents = parseInt(suggested_value, 10);
      if (!isNaN(priceInCents)) {
        return `$${(priceInCents / 100).toFixed(2)}`;
      }
    }
    if (correction_type === 'INCORRECT_ITEM_LINK') {
      const masterItemId = parseInt(suggested_value, 10);
      const item = masterItems.find((mi) => mi.master_grocery_item_id === masterItemId);
      return item ? `${item.name} (ID: ${masterItemId})` : `Unknown Item (ID: ${masterItemId})`;
    }
    if (correction_type === 'ITEM_IS_MISCATEGORIZED') {
      const categoryId = parseInt(suggested_value, 10);
      const category = categories.find((c) => c.category_id === categoryId);
      return category
        ? `${category.name} (ID: ${categoryId})`
        : `Unknown Category (ID: ${categoryId})`;
    }
    return suggested_value;
  };
 
  const handleConfirm = async () => {
    Iif (!actionToConfirm) return;
 
    setIsProcessing(true);
    setIsModalOpen(false);
    setError(null);
    try {
      if (actionToConfirm === 'approve') {
        await approveCorrection(currentCorrection.suggested_correction_id);
        logger.info(`Correction ${currentCorrection.suggested_correction_id} approved.`);
      E} else if (actionToConfirm === 'reject') {
        await rejectCorrection(currentCorrection.suggested_correction_id);
        logger.info(`Correction ${currentCorrection.suggested_correction_id} rejected.`);
      }
      onProcessed(initialCorrection.suggested_correction_id);
    } catch (err) {
      // This is a type-safe way to handle errors. We check if the caught
      // object is an instance of Error before accessing its message property.
      const errorMessage =
        err instanceof Error
          ? err.message
          : `An unknown error occurred while trying to ${actionToConfirm} the correction.`;
      logger.error(
        { err },
        `Failed to ${actionToConfirm} correction ${currentCorrection.suggested_correction_id}`,
      );
      setError(errorMessage); // Show error on the row
      setIsProcessing(false);
    }
    setActionToConfirm(null);
  };
 
  const handleSaveEdit = async () => {
    setIsProcessing(true);
    setError(null);
    try {
      const response = await updateSuggestedCorrection(
        currentCorrection.suggested_correction_id,
        editableValue,
      );
      const updatedCorrection = await response.json();
      setCurrentCorrection(updatedCorrection); // Update local state with the saved version
      setIsEditing(false);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to save changes.';
      logger.error(
        { err },
        `Failed to update correction ${currentCorrection.suggested_correction_id}`,
      );
      setError(errorMessage);
    } finally {
      setIsProcessing(false);
    }
  };
 
  const renderEditableField = () => {
    switch (currentCorrection.correction_type) {
      case 'WRONG_PRICE':
        return (
          <input
            type="number"
            value={editableValue}
            onChange={(e) => setEditableValue(e.target.value)}
            className="form-input w-full text-sm dark:bg-gray-700 dark:border-gray-600"
            placeholder="Price in cents"
          />
        );
      case 'INCORRECT_ITEM_LINK':
        return (
          <select
            value={editableValue}
            onChange={(e) => setEditableValue(e.target.value)}
            className="form-select w-full text-sm dark:bg-gray-700 dark:border-gray-600"
          >
            {masterItems.map((item) => (
              <option key={item.master_grocery_item_id} value={item.master_grocery_item_id}>
                {item.name}
              </option>
            ))}
          </select>
        );
      case 'ITEM_IS_MISCATEGORIZED':
        return (
          <select
            value={editableValue}
            onChange={(e) => setEditableValue(e.target.value)}
            className="form-select w-full text-sm dark:bg-gray-700 dark:border-gray-600"
          >
            {categories.map((cat) => (
              <option key={cat.category_id} value={cat.category_id}>
                {cat.name}
              </option>
            ))}
          </select>
        );
      default:
        return (
          <input
            type="text"
            value={editableValue}
            onChange={(e) => setEditableValue(e.target.value)}
            className="form-input w-full text-sm dark:bg-gray-700 dark:border-gray-600"
          />
        );
    }
  };
 
  return (
    <>
      <ConfirmationModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onConfirm={handleConfirm}
        title={actionToConfirm === 'approve' ? 'Approve Correction' : 'Reject Correction'}
        message={
          actionToConfirm === 'approve' ? (
            <>
              Are you sure you want to approve this correction?
              <strong className="block mt-2">
                This will permanently modify the original flyer item.
              </strong>
            </>
          ) : (
            'Are you sure you want to reject this correction?'
          )
        }
        confirmButtonText={actionToConfirm === 'approve' ? 'Approve' : 'Reject'}
        confirmButtonClass={
          actionToConfirm === 'approve'
            ? 'bg-green-600 hover:bg-green-700 focus:ring-green-500'
            : 'bg-red-600 hover:bg-red-700 focus:ring-red-500'
        }
      />
      <tr>
        <td className="px-6 py-4 align-top">
          <div className="text-sm font-medium text-gray-900 dark:text-white">
            {currentCorrection.flyer_item_name}
          </div>
          <div className="text-sm text-gray-500 dark:text-gray-400">
            Original Price: {currentCorrection.flyer_item_price_display}
          </div>
        </td>
        <td className="px-6 py-4 align-top text-sm text-gray-500 dark:text-gray-400">
          {currentCorrection.correction_type}
        </td>
        <td className="px-6 py-4 align-top text-sm font-semibold text-blue-600 dark:text-blue-400">
          {isEditing ? renderEditableField() : formatSuggestedValue()}
        </td>
        <td className="px-6 py-4 align-top text-sm text-gray-500 dark:text-gray-400">
          {currentCorrection.user_email || 'Unknown'}
        </td>
        <td className="px-6 py-4 align-top text-sm text-gray-500 dark:text-gray-400">
          {new Date(currentCorrection.created_at).toLocaleDateString()}
        </td>
        <td className="px-6 py-4 align-top text-right text-sm font-medium">
          {isProcessing ? (
            <div className="flex justify-end items-center">
              <LoadingSpinner />
            </div>
          ) : isEditing ? (
            <div className="flex items-center justify-end space-x-2">
              <button
                onClick={handleSaveEdit}
                className="p-1.5 text-green-600 hover:bg-green-100 dark:hover:bg-green-800/50 rounded-md"
                title="Save"
              >
                <CheckIcon className="w-5 h-5" />
              </button>
              <button
                onClick={() => {
                  setIsEditing(false);
                  setError(null);
                  setEditableValue(currentCorrection.suggested_value);
                }}
                className="p-1.5 text-red-600 hover:bg-red-100 dark:hover:bg-red-800/50 rounded-md"
                title="Cancel"
              >
                <XMarkIcon className="w-5 h-5" />
              </button>
            </div>
          ) : (
            <div className="flex items-center justify-end space-x-2">
              <button
                onClick={() => {
                  setIsEditing(true);
                  setError(null);
                  setEditableValue(currentCorrection.suggested_value);
                }}
                className="p-1.5 text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md"
                title="Edit"
              >
                <PencilIcon className="w-5 h-5" />
              </button>
              <button
                onClick={() => {
                  setActionToConfirm('approve');
                  setIsModalOpen(true);
                }}
                className="p-1.5 text-green-600 hover:bg-green-100 dark:hover:bg-green-800/50 rounded-md"
                title="Approve"
              >
                <CheckIcon className="w-5 h-5" />
              </button>
              <button
                onClick={() => {
                  setActionToConfirm('reject');
                  setIsModalOpen(true);
                }}
                className="p-1.5 text-red-600 hover:bg-red-100 dark:hover:bg-red-800/50 rounded-md"
                title="Reject"
              >
                <XMarkIcon className="w-5 h-5" />
              </button>
            </div>
          )}
          {error && <p className="text-xs text-red-500 mt-1 text-right">{error}</p>}
        </td>
      </tr>
    </>
  );
};