# Error Handling Implementation - importItem Function

## Overview

Fungsi `importItem` di `erp.service.js` telah di-upgrade dengan error handling yang lebih detail dan informatif menggunakan error handling utilities yang baru.

## Perubahan yang Dilakukan

### 1. **Import Error Handling Utilities**

```javascript
const { createValidationError, createBadRequestError } = require("../../../utils/createError");
const ValidationHelper = require("../../../utils/validationHelper");
```

### 2. **Validasi Input yang Comprehensive**

Fungsi sekarang melakukan validasi lengkap untuk:
- ✅ Parameter structure (`params.params` harus ada)
- ✅ Required fields (`item_code` atau `sku_code`, `item_name`)
- ✅ Field format validation (string, number, date)
- ✅ Field length validation (item_code max 30 chars, item_name max 255 chars)
- ✅ Value validation (price tidak boleh negatif, dates harus valid)
- ✅ Type validation (modified_by, owner harus positive integer)

### 3. **Error Handling yang Proper**

**Sebelum:**
```javascript
catch (error) {
  await transaction.rollback();
  return {
    success: false,
    message: error.message,
  };
}
```

**Sesudah:**
```javascript
catch (error) {
  if (transaction && !transaction.finished) {
    await transaction.rollback();
  }
  // Re-throw error to be handled by error handler middleware
  throw error;
}
```

### 4. **Field-Specific Validation Errors**

Sekarang error akan menampilkan field mana yang error dan kenapa:

```json
{
  "success": false,
  "message": "Item import validation failed",
  "error": {
    "type": "VALIDATION_ERROR",
    "details": {
      "fields": {
        "item_name": {
          "message": "Item name is required"
        },
        "item_price": {
          "message": "Item price must be a valid number"
        }
      }
    }
  }
}
```

## Contoh Error Response

### Validation Error

**Request:**
```json
{
  "params": {
    "item_code": "ITEM001",
    "item_price": "invalid"
  }
}
```

**Response (Development):**
```json
{
  "success": false,
  "message": "Item import validation failed: Item price must be a valid number",
  "error": {
    "type": "VALIDATION_ERROR",
    "name": "ValidationError",
    "message": "Item import validation failed",
    "details": {
      "type": "field_validation",
      "fields": {
        "item_name": {
          "message": "Item name is required"
        },
        "item_price": {
          "message": "Item price must be a valid number"
        }
      },
      "summary": "2 validation error(s)"
    },
    "location": {
      "file": "apps/sapps/masters/erps/erp.service.js",
      "line": 2247,
      "column": 15
    },
    "stack": "ValidationError: Item import validation failed\n  → erp.service.js:2247:15"
  },
  "request": {
    "method": "POST",
    "url": "/sapps/erps/import-item",
    "body": {
      "params": {
        "item_code": "ITEM001"
      }
    }
  }
}
```

### Sequelize Validation Error

Jika ada error dari Sequelize (misalnya duplicate `display_name`), error handler akan otomatis format:

```json
{
  "success": false,
  "message": "Validation failed: display_name must be unique",
  "error": {
    "type": "UNIQUE_CONSTRAINT_ERROR",
    "details": {
      "type": "unique_constraint",
      "fields": {
        "display_name": {
          "message": "display_name must be unique",
          "value": "Item Name"
        }
      }
    }
  }
}
```

## Keuntungan

1. **Debugging Lebih Mudah**
   - Langsung tahu field mana yang error
   - Langsung tahu file dan line number yang error
   - Stack trace lengkap di development mode

2. **Error Messages Lebih Jelas**
   - Field-specific error messages
   - Validation rules yang jelas
   - Context yang lengkap

3. **Konsisten dengan Error Handling System**
   - Menggunakan error handler middleware yang sama
   - Format error yang konsisten di seluruh aplikasi
   - Support untuk berbagai jenis error (validation, database, dll)

4. **Production Safe**
   - Data sensitif di-redact
   - Stack trace hanya di development
   - Error messages yang user-friendly

## Testing

### Test Case 1: Missing Required Fields
```javascript
// Request
{
  "params": {}
}

// Expected: Validation error dengan field-specific messages
```

### Test Case 2: Invalid Price
```javascript
// Request
{
  "params": {
    "item_name": "Test Item",
    "item_code": "TEST001",
    "item_price": -100
  }
}

// Expected: "Item price cannot be negative"
```

### Test Case 3: Invalid Date Format
```javascript
// Request
{
  "params": {
    "item_name": "Test Item",
    "item_code": "TEST001",
    "creation": "invalid-date"
  }
}

// Expected: "Invalid creation date format"
```

### Test Case 4: Duplicate Display Name
```javascript
// Request (jika display_name sudah ada)
{
  "params": {
    "item_name": "Existing Item Name",
    "item_code": "TEST001"
  }
}

// Expected: SequelizeUniqueConstraintError dengan detail
```

## Migration Notes

Controller tidak perlu diubah karena sudah menggunakan `.catch(next)` yang akan pass error ke error handler middleware:

```javascript
function importItem(req, res, next) {
  erpService
    .importItem(req.body)
    .then((result) => res.json(result))
    .catch(next); // ✅ Error akan di-handle oleh middleware
}
```

---

**Status:** ✅ Implemented
**Date:** 2024-01-15
