# KSeF User Guide

## What is KSeF?

KSeF (Krajowy System e-Faktur) is the Polish national e-invoicing system. It enables businesses to send and receive invoices electronically through a government platform.

This integration allows you to:

- Upload invoices to the Polish KSeF system
- Retrieve invoices from KSeF
- Check upload and processing status
- Manage authentication tokens

## Prerequisites

Before using this integration, you need:

1. **Company Registration**
   - Valid Polish NIP (tax identification number)
   - Company registered in Polish tax system

2. **Digital Certificate**
   - XAdES-compatible certificate (podpis kwalifikowany)
   - Certificate issued by trusted certification authority
   - Certificate must match your company NIP

3. **API Access**
   - KSeF platform account
   - API credentials configured

## Configuration

### Connection Settings

The KSeF integration uses these settings:

| Setting | Value |
|---------|-------|
| **System Name** | KSeF Poland |
| **Organization ID** | ksef |
| **Environment** | Test, Demo, or Production |

### KSeF Environments

KSeF provides three environments:

| Environment | Code | URL | Purpose |
|-------------|------|-----|---------|
| **Test** | TEST | `https://api-test.ksef.mf.gov.pl` | Development and testing (Release Candidate) |
| **Demo** | DEMO | `https://api-demo.ksef.mf.gov.pl` | Pre-production validation |
| **Production** | PRD | `https://api.ksef.mf.gov.pl` | Real invoices with legal validity |

### Adding Test and Production Accounts

To configure KSeF accounts, you need to edit the database configuration files.

#### 1. Configure Connection

Edit `preference/database/connection/rest-ksef.json`:

```json
{
  "name": "database/connection/rest-ksef.json",
  "connection": [
    {
      "name": "KSeF Poland",
      "auth_preference": "auth-ksef.json",
      "host": "https://ksef.mf.gov.pl",
      "call_path": "/api/v2/"
    }
  ],
  "connection-test": [
    {
      "name": "KSeF Poland test",
      "auth_preference": "auth-ksef-test.json",
      "host": "https://ksef-test.mf.gov.pl",
      "call_path": "/api/v2/"
    }
  ]
}
```

#### 2. Configure Organization

Edit `preference/database/organization/ksef.json`:

```json
{
  "name": "database/organization/ksef.json",
  "organization": "ksef",
  "database": [
    {
      "show": "KSeF Test",
      "alias_id": "ksef-test",
      "connection": "database/connection/rest-ksef.json",
      "connection_name": "KSeF Poland test",
      "status": "active"
    },
    {
      "show": "KSeF Production",
      "alias_id": "ksef-production",
      "connection": "database/connection/rest-ksef.json",
      "connection_name": "KSeF Poland production",
      "status": "inactive"
    }
  ]
}
```

#### 3. Create Authentication Files

Create auth preference files (location varies by system configuration):

**Test environment** - `auth-ksef-test.json`:

```json
{
  "name": "auth-ksef-test.json",
  "certificate_path": "/path/to/test-certificate.pfx",
  "certificate_password": "test-password",
  "nip": "0000000000"
}
```

**Production environment** - `auth-ksef.json`:

```json
{
  "name": "auth-ksef.json",
  "certificate_path": "/path/to/certificate.pfx",
  "certificate_password": "your-password",
  "nip": "1234567890"
}
```

### Required Credentials

For each KSeF environment, you need:

| Field | Description | Example |
|-------|-------------|---------|
| **nip** | Tax identification number (10 digits) | `1234567890` |
| **certificate_path** | Path to XAdES certificate file | `/path/to/cert.pfx` |
| **certificate_password** | Certificate password | `your-password` |
| **token_ksef** | KSeF token (optional alternative) | `generated-token` |

### Certificate Requirements

**For Test Environment**:

- Self-signed certificates are allowed
- Use test NIP values (random 10-digit numbers)
- No validation with certification authority

**For Production Environment**:

- Qualified electronic certificate (podpis kwalifikowany)
- Certificate must contain your company NIP
- Issued by trusted certification authority
- Certificate must be valid (not expired)

### Authentication Methods

KSeF supports two authentication methods:

1. **XAdES Digital Signature** (recommended for production)
   - Uses qualified certificate
   - Certificate must match company NIP
   - Certificate is verified against OCSP/CRL services

2. **KSeF Token** (alternative)
   - Generated after initial XAdES authentication
   - Encrypted token stored securely
   - Can be used for subsequent logins

### Test Data Setup

For testing, you can use the official KSeF test endpoints to create test scenarios:

- Create test persons/companies via `/v2/testdata/person`
- Set up VAT groups via `/v2/testdata/subject`
- Configure permissions via `/v2/testdata/permissions`

Example test NIP values (from official documentation):

- `7980332920` - Test person (JDG)
- `3755747347` - Test VAT group

### Switching Between Environments

1. **To enable production**:
   - Set `status: "active"` in `ksef.json` for production entry
   - Set `status: "inactive"` for test entry

2. **To switch back to test**:
   - Reverse the status settings

3. **Restart** the application after changes

**Important**: Never use test credentials in production. Always keep test and production certificates separate.

## Using the Integration

### Tabs Overview

The integration has 5 main tabs:

| Tab | Icon | Purpose |
|-----|------|---------|
| **Invoice** | arrow-alt-circle-down | Retrieve invoices from KSeF |
| **Upload invoice** | cloud-upload | Send invoices to KSeF |
| **Invoice metadata** | arrow-alt-circle-down | View invoice processing status |
| **Token** | key | View authentication tokens |
| **Session status** | clock | Check upload session status |

### Tab: Invoice

**Purpose**: Retrieve invoices stored in KSeF

**Key Fields**:

- `ksef_number` - KSeF invoice number (primary identifier)
- `invoice_number` - Your own invoice number
- `nip` - Seller's tax identification number
- `issue_date` - Invoice issue date
- `total_gross_amount` - Total amount including VAT
- `currency` - Invoice currency (PLN default)

**Actions**:

- Import invoices from KSeF by KSeF number
- Compare local invoices with KSeF data

### Tab: Upload Invoice

**Purpose**: Send new invoices to KSeF

**Key Fields**:

- `invoice_id` - Local invoice identifier
- `invoice_data` - Invoice data in required XML format

**Process**:

1. Select local invoice to upload
2. System converts to KSeF XML format
3. Uploads to KSeF platform
4. Receives KSeF invoice number
5. Updates local record with KSeF number

**Important**: After upload, verify status in Session Status tab.

### Tab: Invoice Metadata

**Purpose**: View processing status and timestamps

**Key Fields**:

- `ksef_number` - KSeF invoice number
- `processing_status` - Current processing state
- `timestamp` - Last update timestamp
- `modification_date` - Last modification date

**Status Values**:

- `NEW` - New upload, not yet processed
- `PROCESSING` - Being processed by KSeF
- `COMPLETED` - Successfully processed
- `ERROR` - Processing failed

### Tab: Token

**Purpose**: View authentication tokens

**Key Fields**:

- `token_id` - Token identifier
- `token_name` - Token name/description
- `issuer_nip` - NIP of token issuer
- `active` - Whether token is active

**Note**: Tokens are managed automatically by the system.

### Tab: Session Status

**Purpose**: Check upload session status

**Key Fields**:

- `session_id` - Session identifier
- `reference_number` - KSeF reference number
- `status` - Session status
- `processing_status` - Upload processing status

**Status Values**:

- `OPEN` - Session ready for upload
- `CLOSED` - Session completed
- `ERROR` - Session failed

## Workflow Examples

### Uploading an Invoice to KSeF

1. **Navigate to Upload Invoice tab**
2. **Select local invoice** to upload
3. **Click Export**
4. **System will:**
   - Authenticate with KSeF
   - Open upload session
   - Upload invoice data
   - Receive KSeF number
   - Close session
5. **Verify status** in Session Status tab
6. **Check metadata** to confirm processing

### Retrieving an Invoice from KSeF

1. **Navigate to Invoice tab**
2. **Enter KSeF number** (or your invoice number)
3. **Click Import**
4. **System retrieves** invoice data from KSeF
5. **Compare** with local data if needed

### Checking Upload Status

1. **After upload**, go to Session Status tab
2. **Find your session** by reference number
3. **Check status**:
   - `PROCESSING` - Still being processed
   - `COMPLETED` - Successfully uploaded
   - `ERROR` - Upload failed

## Common Issues

### Upload Fails

**Symptom**: Export returns error

**Possible causes**:

- Invalid certificate
- Certificate expired
- Wrong environment (test vs production)
- NIP mismatch

**Solution**:

1. Verify certificate is valid
2. Check NIP matches certificate
3. Confirm correct environment

### Cannot Retrieve Invoice

**Symptom**: Import returns no data

**Possible causes**:

- Wrong KSeF number
- Invoice not yet uploaded
- Invoice belongs to different NIP

**Solution**:

1. Verify KSeF number is correct
2. Check invoice was uploaded successfully
3. Ensure you have access rights

### Session Timeout

**Symptom**: Session closes before upload completes

**Possible causes**:

- Upload took too long
- Network issues

**Solution**:

1. Retry the upload
2. Check network connection
3. Reduce invoice batch size

## Security Notes

- Certificates are stored securely
- Tokens are managed automatically
- Never share certificate private keys
- Use test environment for development
- Monitor for unauthorized access

## Support

For issues with:

- **Integration**: Contact your system administrator
- **KSeF Platform**: Visit <https://www.podatki.gov.pl/ksef/>
- **Certificates**: Contact your certification authority

## Data Retention

- Uploaded invoices remain in KSeF system
- Local records are kept according to your retention policy
- Tokens expire and are renewed automatically

## Best Practices

1. **Always start in test environment** before using production
2. **Verify uploads** by checking session status
3. **Keep certificates valid** - renew before expiry
4. **Monitor processing status** after uploads
5. **Backup local data** regularly
6. **Use unique invoice numbers** to avoid conflicts

## Glossary

| Term | Meaning |
|------|---------|
| **KSeF** | Krajowy System e-Faktur (Polish e-invoicing system) |
| **NIP** | Numer Identyfikacji Podatkowej (Tax ID) |
| **XAdES** | XML Advanced Electronic Signature |
| **KSeF Number** | System-assigned invoice identifier |
| **Session** | Temporary connection for uploading invoices |
