# APEX Processes Documentation

This document contains all 98 processes defined in the APEX application, organized by page.

## Process Overview

| Process Type | Count |
|--------------|-------|
| NATIVE_FORM_INIT | Multiple |
| NATIVE_FORM_DML | Multiple |
| NATIVE_PLSQL | Multiple |
| NATIVE_IG_DML | Multiple |
| NATIVE_SESSION_STATE | Multiple |

---

## Shared (Application-Level) Processes

### SET_USER_READONLY

**Process Point:** Before Header (runs on every page)
**Type:** NATIVE_PLSQL

Sets the `APP_READ_ONLY` application item based on user permissions.

```plsql
begin
    if F_USER_IN_ROLE(:APP_USER, 'READONLY') then
        :APP_READ_ONLY := 1;
    else
        :APP_READ_ONLY := 0;
    end if;
end;
```

---

## Page 3 - Articoli (Article Form)

### Fetch Row from ARTICOLI
**Process Point:** After Header
**Type:** NATIVE_FORM_INIT

Initializes form with article data.

### Process Row of ARTICOLI
**Process Point:** After Submit
**Type:** NATIVE_FORM_DML

Saves/updates article record.

### Delete Image
**Process Point:** After Submit
**Type:** NATIVE_PLSQL
**Button:** Delete Image

```plsql
begin
    update articoli
    set
        raw_data = null,
        last_update = null,
        charset = null,
        mimetype = null,
        filename = null
    where rowid = :P3_ROWID;
end;
```

---

## Page 22 - Nuovo Evento (Main Event Form)

Page 22 is the most complex page with 32 processes.

### After Header Processes

#### Get Event Details
**Sequence:** 10
**Type:** NATIVE_FORM_INIT

Fetches event record into form items.

#### Set Ospiti on load
**Sequence:** 20
**Type:** NATIVE_PLSQL

```plsql
begin
    EVENTI_AGGIORNA_TOT_OSPITI(:P22_EVENT_ID);
end;
```

#### Default Values
**Sequence:** 40
**Type:** NATIVE_PLSQL

```plsql
begin
    select trim(l.location)
    into :P22_LOCATION_DESCRI
    from eventi e
    join location l on l.id = e.id_location
    where e.id = :P22_EVENT_ID;
exception when no_data_found then
    null;
end;
```

#### Normalizza dati
**Sequence:** 50
**Type:** NATIVE_PLSQL

Formats time values for display:

```plsql
:P22_ORA_INI_CER := to_char(to_date(:P22_ORA_CERIMONIA, 'DD-MM-YYYY HH24:MI'), 'hh24:mi');
:P22_ORA_INI_EVENTO := to_char(to_date(:P22_ORA_EVENTO, 'DD-MM-YYYY HH24:MI'), 'hh24:mi');
:P22_ORA_FI_CER := to_char(to_date(:ORA_FINE_CERIMONIA, 'DD-MM-YYYY HH24:MI'), 'hh24:mi');
:P22_ORA_FI_EVENTO := to_char(to_date(:ORA_FINE_EVENTO, 'DD-MM-YYYY HH24:MI'), 'hh24:mi');
```

#### New Template Default Data
**Sequence:** 60
**Condition:** P22_IS_TEMPLATE is not null

```plsql
:P22_DATA := sysdate;
```

---

### After Submit Processes

#### Set Date Default if Template
**Sequence:** 10
**Condition:** P22_IS_TEMPLATE is not null

```plsql
:P22_DATA := sysdate;
```

#### Delete Template
**Sequence:** 20
**Button:** Delete Template
**Condition:** P22_IS_TEMPLATE is not null

```plsql
delete from eventi where id = :P22_EVENT_ID;
```

#### Genera Evento da Template
**Sequence:** 30
**Button:** Generate from Template
**Condition:** P22_IS_TEMPLATE is not null

```plsql
EVENTI_COPIA
(
    ID_EVENTO_OLD  => :P22_EVENT_ID,
    NUOVA_VERSIONE => 0,
    ID_EVENTO_NEW  => :P22_EVENT_ID
);
```

#### Formatta Ore Inizio
**Sequence:** 40

Combines date and time for storage:

```plsql
:P22_ORA_EVENTO := :P22_DATA || ' ' || :P22_ORA_INI_EVENTO;
:P22_ORA_CERIMONIA := :P22_DATA || ' ' || :P22_ORA_INI_CER;
```

#### Prepara Acconti Automatici
**Sequence:** 50
**Condition:** REQUEST in ('PREPARA_ACCONTI', 'PRINT_PREVENTIVO')

```plsql
EVENTI_RICALCOLA_ACCONTI(p_event_id => :P22_EVENT_ID);
```

**Comment:** Default 3 deposits: 30%, 50%, 20%

#### Go Forward
**Sequence:** 60
**Button:** NEXT

Navigates to next wizard step:

```plsql
declare
    v_step number;
begin
    begin
        select min(cod_step)
        into v_step
        from tb_tipi_mat
        where cod_step > TO_NUMBER(:P22_STEP);
    end;
    
    begin
        select cod_tipo
        into :P22_COD_TIPO_FILTER
        from tb_tipi_mat
        where cod_step = v_step;
        exception when no_data_found
            then raise_application_error(-20001, 'Errore sconosciuto');
    end;
    
    :P22_STEP := v_step;
end;
```

#### Go Backward
**Sequence:** 70
**Button:** PREVIOUS

Navigates to previous wizard step.

#### Tipo Ospiti - Save Interactive Grid Data
**Sequence:** 80
**Region:** Guest Types Grid
**Type:** NATIVE_IG_DML
**Condition:** APP_READ_ONLY = 0

Saves guest type records.

#### Tipo Ospiti - Aggiorna Lista Prelievo
**Sequence:** 90
**Type:** NATIVE_PLSQL
**Condition:** APP_READ_ONLY = 0

Recalculates pick list quantities after guest changes:

```plsql
EVENTI_AGGIORNA_QTA_LISTA(
    P_ID_EVENTO => :P22_EVENT_ID
);
```

#### Degustazioni - Save Interactive Grid Data
**Sequence:** 100
**Region:** Tastings Grid
**Type:** NATIVE_IG_DML

#### Delete Eventi Childs
**Sequence:** 110
**Button:** DELETE
**Condition:** NEVER (disabled)

```plsql
begin
    delete from eventi_det_ospiti
    where id_evento = :P22_EVENT_ID;
    
    delete from eventi_det_prel
    where id_evento = :P22_EVENT_ID;
    
    delete from eventi_det_ris
    where id_evento = :P22_EVENT_ID;
            
    delete from eventi_det_degust
    where id_evento = :P22_EVENT_ID;
end;
```

#### Set Obsoleto
**Sequence:** 120
**Button:** Set Obsolete
**Condition:** APP_READ_ONLY = 0

Marks event as expired/cancelled:

```plsql
begin
    UPDATE EVENTI
    SET FLG_SUPERATO = 1, STATO = 900, MAIL_ENABLED = 0
    WHERE ID = :P22_EVENT_ID;
end;
```

#### Salva Evento
**Sequence:** 130
**Condition:** Complex (handles CREATE, SAVE, DELETE)

Main event save process. Full implementation handles:
- All event fields mapping
- Email validation
- Status-based logic
- Versioning support
- Soft delete

Key excerpts:

```plsql
declare
    r_eventi eventi%rowtype;
begin
    if :REQUEST = 'PREVIOUS' or :REQUEST = 'NEXT'
    then
        return;
    end if;

    if(:P22_DATA is null)
    then
        raise_application_error(-20001, 'Inserire la data evento');
    end if;

    -- Set all row fields
    r_eventi."ID" := :P22_EVENT_ID;
    r_eventi.DESCRIZIONE := :P22_DESCRIZIONE;
    r_eventi.COD_TIPO := :P22_COD_TIPO;
    -- ... (all other fields)
    
    -- Email validation
    IF REGEXP_LIKE(:P22_CLIENTE_EMAIL, '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$') 
       OR :P22_CLIENTE_EMAIL IS NULL THEN
        r_eventi.CLIENTE_EMAIL := :P22_CLIENTE_EMAIL;
    ELSE
        RAISE_APPLICATION_ERROR(-20005, 'Formato email cliente non valido');
    END IF;
    
    -- Versioning
    r_eventi.VERS_NUMBER := nvl(:P22_VERS_NUMBER, 0);
    r_eventi.VERS_TOKEN := :P22_VERS_TOKEN;
    
    case :REQUEST
        when 'SAVE' then
            update eventi set row = r_eventi where id = :P22_EVENT_ID;
        when 'CREATE' then
            insert into eventi values r_eventi returning id into :P22_EVENT_ID;
        when 'DELETE' then
            if r_eventi.ID_EVT_FIGLIO is not null or r_eventi.ID_EVT_PADRE is not null
            then
                raise_application_error(-20001, 'Impossibile eliminare un evento...');
            end if;
            update eventi
               set deleted = 1,
                   deleted_by = :APP_USER,
                   deleted_date = sysdate
            where id = r_eventi."ID";
        else
            null;
    end case;
end;
```

#### Nuova Versione
**Sequence:** 140
**Button:** New Version

Creates a new version of the event:

```plsql
EVENTI_COPIA
(
    ID_EVENTO_OLD  => :P22_EVENT_ID,
    NUOVA_VERSIONE => 1,
    ID_EVENTO_NEW  => :P22_NEW_EVENT_ID
);
```

#### Lista Prelievo - Save Interactive Grid Data
**Sequence:** 150
**Type:** NATIVE_IG_DML
**Table:** EVENTI_DET_PREL

Saves pick list records.

#### Continue Event
**Sequence:** 160
**Button:** Continue

Advances event to "Confermata" status (300):

```plsql
declare
  v_count       number;
  v_count_evt   number;
begin
  -- Check if confirmed event exists for same location/date
  select count(*) into v_count
    from eventi
   where data = (select data from eventi where id = :P22_EVENT_ID)
     and stato = 300
     and id_location = (select id_location from eventi where id = :P22_EVENT_ID);      
    
  if v_count > 0 then   
      raise_application_error(-20001, 'Esiste un evento Confermato per la location - Impossibile proseguire'); 
      return;
  end if;

  -- Update status
  update eventi
  set stato = 300 
  where id = :P22_EVENT_ID;

  -- Check total confirmed events for date
  select count(*) into v_count_evt
    from eventi
   where data = (select data from eventi where id = :P22_EVENT_ID)
     and stato = 300;      
     
  if v_count_evt > 6 then   
      RAISE_APPLICATION_ERROR(-20000, 'Ci sono già 6 eventi Confermati per la data'); 
  end if;    
end;
```

#### Almost Continue Event
**Sequence:** 170
**Button:** Almost Continue

Sets status to "Quasi Confermato" (350):

```plsql
begin
  update eventi
  set stato = 350 
  where id = :P22_EVENT_ID;
end;
```

#### Confirm Event
**Sequence:** 180
**Button:** Confirm
**Condition:** APP_READ_ONLY = 0

Final confirmation (status 400) and cancels competing events:

```plsql
begin
    update eventi
    set stato = 400
    where id = :P22_EVENT_ID;
    
    -- Cancel events with same date and location
    p_cancel_same_location_events(
        p_good_event_id => :P22_EVENT_ID
    );
end;
```

#### Unconfirm Event
**Sequence:** 190
**Button:** Unconfirm

Returns event to initial status (100):

```plsql
begin
    update eventi
    set stato = 100
    where id = :P22_EVENT_ID;
end;
```

#### Reopen Event
**Sequence:** 200
**Button:** Reopen

Clears the expired flag:

```plsql
begin
    update eventi
    set flg_superato = 0
    where id = :P22_EVENT_ID;
end;
```

#### Return to Preparazione
**Sequence:** 210
**Button:** Return to Preparation

Sets status back to preparation (200):

```plsql
begin
    update eventi
    set stato = 200
    where id = :P22_EVENT_ID;
end;
```

#### Risorse - Save Interactive Grid Data
**Sequence:** 220
**Type:** NATIVE_IG_DML

Saves resource assignments.

#### Aggiorna QTA Lista
**Sequence:** 230
**Condition:** APP_READ_ONLY = 0 AND REQUEST = 'AGGIORNA_QTA'

Manual quantity recalculation:

```plsql
EVENTI_AGGIORNA_QTA_LISTA(
    P_ID_EVENTO => :P22_EVENT_ID
);
```

#### Restore Deleted Event
**Sequence:** 240

Restores soft-deleted event.

---

## Event Status Workflow Summary

| Status Code | Status Name | Italian | Next Action |
|-------------|-------------|---------|-------------|
| 100 | Preventivo | Quote | Continue Event → 300 |
| 200 | Scheda | Preparation | - |
| 300 | Confermata | Confirmed (Pending) | Almost Continue → 350 |
| 350 | Quasi | Almost Confirmed | Confirm → 400 |
| 400 | Confermato | Confirmed | - |
| 900 | Superato | Expired/Cancelled | Reopen → clears flag |

---

## Common Process Patterns

### Read-Only Check
All write processes include this condition:
```plsql
:APP_READ_ONLY = 0
```

### Error Handling
Standard error pattern:
```plsql
exception when no_data_found then
    raise_application_error(-20001, 'Error message in Italian');
```

### Interactive Grid Save
Standard IG DML process:
- Type: NATIVE_IG_DML
- Attributes: REGION_SOURCE, Allow Insert (Y), Allow Update (Y), Allow Delete (Y)

---

## Migration Notes

When migrating these processes to .NET:

1. **Form Initialization** - Use API endpoints to fetch entity data
2. **Form DML** - Implement CRUD endpoints with proper validation
3. **Custom PL/SQL** - Convert to C# methods or stored procedures
4. **IG DML** - Implement batch update endpoints for grid data
5. **Session State** - Use application state management (Redux, Context)
6. **Validation** - Implement in both frontend and backend
7. **Workflow** - Consider state machine pattern for event status
