# LHDN e-Invoice Node for n8n

[![npm version](https://badge.fury.io/js/n8n-nodes-lhdn-einvoice.svg)](https://www.npmjs.com/package/n8n-nodes-lhdn-einvoice)
[![npm downloads](https://img.shields.io/npm/dm/n8n-nodes-lhdn-einvoice.svg)](https://www.npmjs.com/package/n8n-nodes-lhdn-einvoice)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://img.shields.io/badge/build-passing-brightgreen.svg)](https://github.com/nmhafiz/n8n-nodes-lhdn-einvoice)
[![Test Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen.svg)](https://github.com/nmhafiz/n8n-nodes-lhdn-einvoice)
[![Version](https://img.shields.io/badge/version-1.2.1-blue.svg)](https://www.npmjs.com/package/n8n-nodes-lhdn-einvoice)

🇲🇾 **Node n8n rasmi untuk integrasi LHDN e-Invoice Malaysia**

Automasi lengkap untuk proses e-invoice perniagaan Malaysia dengan pematuhan penuh kepada spesifikasi LHDN.

## ✨ What's New in v1.2.1

- 🐛 **Bug Fixes**: Fixed all TypeScript errors and test failures
- ✅ **100% Test Coverage**: All 58 tests passing across 9 test suites
- 🔧 **UBL 2.1 Compliance**: Enhanced format compliance for invoice structures
- 🧮 **Tax Calculation**: Fixed zero tax rate handling
- 🛠️ **Credential Tools**: Added interactive setup wizard and helper scripts
- 📚 **Documentation**: Comprehensive setup guides in Bahasa Malaysia

## Ciri-ciri

- ✅ **Easy Form Input Mode** - Mod input mudah dengan form fields (BARU!)
- ✅ **Advanced Raw Mode** - Input dokumen JSON/XML terus untuk pengguna mahir
- ✅ **Authentication** - Dapatkan access token untuk API
- ✅ **Submit Documents** - Hantar dokumen e-invoice (JSON/XML)
- ✅ **Get Documents** - Dapatkan dokumen berdasarkan UUID
- ✅ **Get Recent Documents** - Dapatkan senarai dokumen terkini
- ✅ **Cancel Documents** - Batalkan dokumen yang sah
- ✅ **Reject Documents** - Tolak dokumen
- ✅ **Get Document Status** - Semak status dokumen
- ✅ **Validate TIN** - Sahkan Tax Identification Number
- ✅ **Digital Signature** - Sokongan untuk tandatangan digital
- ✅ **Sandbox & Production** - Sokongan untuk kedua-dua environment

## Pemasangan

### Melalui n8n Community Nodes

1. Buka n8n instance anda
2. Pergi ke **Settings** > **Community Nodes**
3. Klik **Install a community node**
4. Masukkan `n8n-nodes-lhdn-einvoice`
5. Klik **Install**

### Melalui npm

```bash
npm install n8n-nodes-lhdn-einvoice
```

## 🚀 Quick Start

### Using Form Mode (Recommended for Beginners)

1. **Add the LHDN e-Invoice node** to your workflow
2. **Select "Submit Document"** operation
3. **Choose "Form Fields (Easy)"** as Input Mode
4. **Fill in the form fields**:
   - Invoice Number: `INV-2024-001`
   - Supplier TIN: `C12345678`
   - Supplier Name: `Your Company Sdn Bhd`
   - Customer TIN: `D98765432`
   - Add invoice items with description, quantity, and price
5. **Set Code Number**: `INV001`
6. **Execute** - The node will automatically generate UBL 2.1 format!

### Using Raw Mode (Advanced Users)

1. **Choose "Raw Document (Advanced)"** as Input Mode
2. **Prepare your UBL 2.1 JSON/XML document**
3. **Paste the document** in the Document field
4. **Set Document Format** (JSON/XML)
5. **Execute**

### Example Form Input
```json
{
  "invoiceNumber": "INV-2024-001",
  "supplier": {
    "tin": "C12345678",
    "name": "Syarikat ABC Sdn Bhd",
    "address": "No. 123, Jalan Utama",
    "city": "Kuala Lumpur",
    "postalCode": "50000",
    "state": "14"
  },
  "customer": {
    "tin": "D98765432",
    "name": "Syarikat XYZ Sdn Bhd"
  },
  "items": [
    {
      "description": "Perkhidmatan Konsultasi IT",
      "quantity": 10,
      "unitPrice": 500.00,
      "taxRate": 6
    }
  ]
}
```

## ❓ Kenapa Banyak Credential?

LHDN e-Invoice API memerlukan **8 field credential** untuk keselamatan maksimum. Ini adalah **requirement kerajaan Malaysia**, bukan pilihan kita:

- 🛡️ **Digital Signature**: Untuk tandatangan digital dokumen
- 🔐 **Encryption**: Untuk encrypt data sensitive  
- 🆔 **Authentication**: Untuk verify identity syarikat
- 📋 **Compliance**: Untuk comply dengan undang-undang Malaysia

**INI STANDARD KERAJAAN** - semua vendor e-Invoice kena ikut requirement yang sama.

### 🚀 Cara Mudah Setup (3 Langkah Sahaja!)

#### **Option 1: Guna Credential Wizard (RECOMMENDED)**
```bash
# Jalankan wizard interaktif
node credential-wizard.js
```
Wizard akan guide anda step-by-step dan auto-extract semua maklumat!

#### **Option 2: Guna Helper Script**
```bash
# Extract certificate info automatically
./credential-helper.sh /path/to/your/certificate.pem
```

#### **Option 3: Manual Setup** (lihat bahagian Konfigurasi di bawah)

### 💡 Setup Sekali Sahaja
**Good news**: Credential ini setup **SEKALI SAHAJA** per syarikat. Lepas tu boleh guna untuk semua workflow!

📖 **Baca panduan lengkap**: [CREDENTIAL_SETUP_GUIDE.md](./CREDENTIAL_SETUP_GUIDE.md)

## Konfigurasi

### 1. Buat Credentials

Sebelum menggunakan node ini, anda perlu menyediakan credentials untuk API LHDN:

1. Pergi ke **Credentials** dalam n8n
2. Klik **Create New**
3. Pilih **LHDN e-Invoice API**
4. Isi maklumat berikut:

| Field | Keterangan |
|-------|------------|
| Environment | Pilih Sandbox atau Production |
| Client ID | Client ID dari LHDN |
| Client Secret | Client Secret dari LHDN |
| X.509 Certificate | Certificate dalam format PEM |
| Private Key | Private key dalam format PEM |
| X.509 Subject Name | Subject name dari certificate |
| X.509 Issuer Name | Issuer name dari certificate |
| X.509 Serial Number | Serial number dari certificate |

### 2. Dapatkan Credentials dari LHDN

Untuk mendapatkan credentials yang diperlukan:

1. Daftar di [MyInvois Portal](https://myinvois.hasil.gov.my/)
2. Buat aplikasi baru dalam Developer Portal
3. Dapatkan Client ID dan Client Secret
4. Generate atau upload X.509 certificate
5. Catat semua maklumat yang diperlukan

## Penggunaan

### 1. Get Access Token

```json
{
  "resource": "authentication",
  "operation": "getToken"
}
```

### 2. Submit e-Invoice

```json
{
  "resource": "document",
  "operation": "submit",
  "documentFormat": "JSON",
  "document": {
    "Invoice": {
      "InvoiceTypeCode": {
        "@listVersionID": "1.1",
        "#text": "01"
      },
      "ID": "INV12345",
      "IssueDate": "2024-01-15",
      "IssueTime": "15:30:00Z",
      "DocumentCurrencyCode": "MYR",
      "AccountingSupplierParty": {
        // Maklumat pembekal
      },
      "AccountingCustomerParty": {
        // Maklumat pembeli
      },
      "InvoiceLine": [
        // Item-item invoice
      ]
    }
  },
  "codeNumber": "INV001"
}
```

### 3. Get Recent Documents

```json
{
  "resource": "document",
  "operation": "getRecent",
  "pageNo": 1,
  "pageSize": 20,
  "submissionDateFrom": "2024-01-01T00:00:00Z",
  "submissionDateTo": "2024-01-31T23:59:59Z"
}
```

### 4. Validate TIN

```json
{
  "resource": "validation",
  "operation": "validateTin",
  "tin": "C12345678",
  "idType": "BRN",
  "idValue": "123456789"
}
```

## Contoh Workflow

### Workflow 1: Submit e-Invoice

1. **HTTP Request Node** - Terima data invoice dari webhook
2. **Function Node** - Format data mengikut struktur UBL 2.1
3. **LHDN e-Invoice Node** - Submit dokumen
4. **IF Node** - Semak status submission
5. **Email Node** - Hantar notifikasi

### Workflow 2: Monitor Document Status

1. **Cron Node** - Jalankan setiap jam
2. **LHDN e-Invoice Node** - Get recent documents
3. **Function Node** - Filter dokumen yang perlu dikemaskini
4. **LHDN e-Invoice Node** - Get status untuk setiap dokumen
5. **Database Node** - Kemaskini status dalam database

## Format Dokumen

### JSON Format (UBL 2.1)

```json
{
  "Invoice": {
    "InvoiceTypeCode": {
      "@listVersionID": "1.1",
      "#text": "01"
    },
    "ID": "INV12345",
    "IssueDate": "2024-01-15",
    "IssueTime": "15:30:00Z",
    "DocumentCurrencyCode": "MYR",
    "AccountingSupplierParty": {
      "Party": {
        "PartyIdentification": [
          {
            "ID": {
              "@schemeID": "TIN",
              "#text": "C12345678"
            }
          }
        ],
        "PartyName": [
          {
            "Name": "Syarikat ABC Sdn Bhd"
          }
        ],
        "PostalAddress": {
          "CityName": "Kuala Lumpur",
          "PostalZone": "50000",
          "CountrySubentityCode": "14",
          "AddressLine": [
            {
              "Line": "Jalan ABC 123"
            }
          ],
          "Country": {
            "IdentificationCode": "MYS"
          }
        }
      }
    },
    "AccountingCustomerParty": {
      "Party": {
        "PartyIdentification": [
          {
            "ID": {
              "@schemeID": "TIN",
              "#text": "D98765432"
            }
          }
        ],
        "PartyName": [
          {
            "Name": "Syarikat XYZ Sdn Bhd"
          }
        ]
      }
    },
    "InvoiceLine": [
      {
        "ID": "1",
        "InvoicedQuantity": {
          "@unitCode": "C62",
          "#text": "1"
        },
        "LineExtensionAmount": {
          "@currencyID": "MYR",
          "#text": "100.00"
        },
        "Item": {
          "Name": "Perkhidmatan Konsultansi"
        },
        "Price": {
          "PriceAmount": {
            "@currencyID": "MYR",
            "#text": "100.00"
          }
        }
      }
    ],
    "LegalMonetaryTotal": {
      "LineExtensionAmount": {
        "@currencyID": "MYR",
        "#text": "100.00"
      },
      "TaxExclusiveAmount": {
        "@currencyID": "MYR",
        "#text": "100.00"
      },
      "TaxInclusiveAmount": {
        "@currencyID": "MYR",
        "#text": "106.00"
      },
      "PayableAmount": {
        "@currencyID": "MYR",
        "#text": "106.00"
      }
    }
  }
}
```

## Error Handling

Node ini menyediakan error handling yang komprehensif:

- **Authentication Errors** - Token tidak sah atau expired
- **Validation Errors** - Format dokumen tidak betul
- **API Rate Limits** - Automatic retry dengan backoff
- **Network Errors** - Timeout dan connection issues

## Sokongan

- **Dokumentasi Rasmi**: [LHDN e-Invoice SDK](https://sdk.myinvois.hasil.gov.my/)
- **MyInvois Portal**: [https://myinvois.hasil.gov.my/](https://myinvois.hasil.gov.my/)
- **GitHub Issues**: [Laporkan masalah](https://github.com/nmhafiz/n8n-nodes-lhdn-einvoice/issues)

## Lesen

MIT License - lihat [LICENSE](LICENSE) untuk butiran penuh.

## Sumbangan

Sumbangan adalah dialu-alukan! Sila baca [CONTRIBUTING.md](CONTRIBUTING.md) untuk panduan.

## Changelog

### v1.0.0
- ✅ Keluaran awal
- ✅ Sokongan untuk semua operasi asas LHDN e-Invoice API
- ✅ Sokongan untuk format JSON dan XML
- ✅ Digital signature support
- ✅ Comprehensive error handling