# JavaScript Libraries Documentation

This document describes the custom JavaScript libraries used in the APEX application.

## Static Application Files

| File Name | Description |
|-----------|-------------|
| ajaxUtils.js | AJAX utilities for dynamic updates and server communication |
| iframeObj.js | Jasper Reports integration wrapper |

---

## ajaxUtils.js

Custom AJAX utility library for managing server-side communication and UI feedback.

### Functions

#### `notifica(pText, pType = null)`

Central dynamic notification function.

**Parameters:**
- `pText` (string): Message text to display
- `pType` (string, optional): Notification type - 'alert', 'success', 'error', 'warning', 'info'

**Behavior:**
- Clears existing errors
- If `pType` is provided, shows error notification at page level
- If `pType` is null, shows success message

**Example:**
```javascript
notifica("Record saved successfully"); // Success message
notifica("Error occurred", "error");   // Error message
```

---

#### `setSessionState(elemList, pCallback = null)`

Sets APEX session state for multiple items.

**Parameters:**
- `elemList` (string): Comma-separated list of item IDs (without P prefix)
- `pCallback` (function, optional): Callback function after session state is set

**How it works:**
1. Splits the element list by comma
2. Gets values for each element using jQuery
3. Creates a dictionary of item-value pairs
4. Calls APEX process `SET_ITEM_SESSION` to update session state
5. Executes callback with data and elements dictionary

**Example:**
```javascript
setSessionState("P22_EVENT_ID,P22_CLIENTE", function(pData, elems) {
    console.log("Session state updated");
});
```

---

#### `ajaxExec(pName, clickObj, pParams, pCallback, pConfirm, pLoading, pAsync, pType)`

Generic AJAX execution wrapper for APEX server processes.

**Parameters:**
- `pName` (string): APEX process name to execute
- `clickObj` (jQuery object): Button/element that triggered the action
- `pParams` (object): Parameters to pass to the process
- `pCallback` (function): Callback function on success/error
- `pConfirm` (string): Confirmation message (uses native confirm dialog)
- `pLoading` (boolean): Show loading popup
- `pAsync` (boolean): Execute asynchronously
- `pType` (string): Response data type (default: 'text')

**Features:**
- Prevents page unload during execution
- Shows loading spinner on clicked element
- Handles confirmation dialogs
- Parses response and removes quotes
- Executes callback with parsed data

**Example:**
```javascript
ajaxExec("SAVE_EVENT", clickBtn, {x01: eventId}, function(data, btn, params) {
    notifica("Event saved");
}, "Are you sure?", true);
```

---

#### `execProcessAsync(pName, pParams, pPreExec, pCallback, pItems = null, clickObj = null, pConfirm = null, pLoading = null)`

Wrapper for async process execution with optional session state update.

**Parameters:**
- `pName` (string): Process name
- `pParams` (object): Process parameters
- `pPreExec` (function): Function to execute before AJAX call
- `pCallback` (function): Callback after process execution
- `pItems` (string): Items to set in session state first
- `clickObj`: Clicked element
- `pConfirm` (string): Confirmation message
- `pLoading` (boolean): Show loading indicator

**Example:**
```javascript
execProcessAsync("UPDATE_QTY", {x01: itemId}, null, function(data) {
    apex.region("LIST_PREL").refresh();
}, "P22_EVENT_ID");
```

---

#### `execQueryAsync(pQuery, pPreExec, pCallback, clickObj = null, pConfirm = null, pItems = null, pLoading = null)`

Executes a SQL query asynchronously.

**Parameters:**
- `pQuery` (string): SQL query to execute
- `pPreExec` (function): Pre-execution function
- `pCallback` (function): Callback with query results
- `clickObj`: Clicked element
- `pConfirm` (string): Confirmation message
- `pItems` (string): Items to set in session state
- `pLoading` (boolean): Show loading indicator

**Note:** Calls the `EXEC_QUERY` APEX process with the query in `x01` parameter.

---

## iframeObj.js

JavaScript wrapper for embedding Jasper Reports in iframes.

### Configuration

```javascript
var j_datasource = "default";      // Jasper datasource name
var j_username = "jasperadmin";    // Jasper server username
var j_password = "jasperadmin";    // Jasper server password
var j_def_outp = "pdf";            // Default output format (HTML, PDF)
```

### Iframe Class

#### Constructor

```javascript
var Iframe = function(parentObj, id, attr) { ... }
```

**Parameters:**
- `parentObj`: Parent DOM element
- `id`: Iframe element ID
- `attr`: Additional attributes

### Methods

#### `setCss(css)`

Sets CSS styles on the iframe.

**Parameters:**
- `css` (object): CSS properties dictionary

**Example:**
```javascript
iframe.setCss({ width: "100%", height: "600px", border: "none" });
```

---

#### `setUrl(Url)`

Sets the iframe source URL.

---

#### `getUrl()`

Returns the current iframe URL.

---

#### `refresh()`

Reloads the iframe content.

---

#### `hide()`

Hides the iframe (display: none).

---

#### `show()`

Shows the iframe (display: block).

---

#### `jasperReport(dir, datasource, params, output, username, password)`

Generates a Jasper Reports URL and loads it in the iframe.

**Parameters:**
- `dir` (string, required): Report path in Jasper server
- `datasource` (string): Data source name (default: "default")
- `params` (object): Report parameters as key-value pairs
- `output` (string): Output format - 'pdf' or 'html' (default: 'pdf')
- `username` (string): Jasper server username
- `password` (string): Jasper server password

**URL Format:**
```
/jri/report?_repName={dir}&_repFormat={output}&_dataSource={datasource}&_repLocale=it_IT&_repTimeZone=Europe/Rome&{params}
```

**Example:**
```javascript
var rptFrame = new Iframe(container, "reportFrame");
rptFrame.jasperReport(
    "apcb/scheda_evento_rpt",
    "default",
    { P_EVENT_ID: eventId, P_TIPO: "PREVENTIVO" },
    "pdf"
);
```

---

## Usage in APEX Pages

### Time Input Masks

The application uses inputmask library for time fields:

```javascript
Inputmask("99:99", {
    placeholder: "HH:MM"
}).mask($("#P22_ORA_INI_EVENTO"));
```

### SweetAlert2 Integration

Used for enhanced confirmation dialogs:

```javascript
Swal.fire({
    title: 'Conferma',
    text: 'Vuoi continuare?',
    icon: 'warning',
    showCancelButton: true
}).then((result) => {
    if (result.isConfirmed) {
        // proceed
    }
});
```

### Interactive Grid Refresh

```javascript
// Refresh a specific interactive grid
apex.region("LISTA_PRELIEVO").refresh();

// Refresh with callback
apex.region("OSPITI").widget().interactiveGrid("getViews", "grid").model.fetchRecords();
```

---

## Migration Notes

When migrating to React TypeScript:

1. **AJAX Utilities** - Replace with:
   - Axios or fetch for HTTP requests
   - React Query or SWR for data fetching
   - Toast library (react-toastify) for notifications

2. **Session State** - Replace with:
   - React Context or Redux for state management
   - URL parameters for shareable state
   - Session storage for persistence

3. **Jasper Reports** - Options:
   - Keep Jasper and embed via iframe
   - Migrate to SSRS, Crystal Reports
   - Use PDF libraries (QuestPDF, iTextSharp)
   - Use React-PDF for client-side PDF generation

4. **Input Masks** - Use:
   - react-input-mask
   - @react-input/mask
   - Material-UI TextField with InputProps

5. **SweetAlert2** - Replace with:
   - MUI Dialog components
   - react-confirm-alert
   - Custom modal component

### Example React Migration

```typescript
// ajaxUtils.js equivalent in React
import { toast } from 'react-toastify';
import axios from 'axios';

export const notifica = (text: string, type?: 'success' | 'error' | 'warning' | 'info') => {
  if (type) {
    toast[type](text);
  } else {
    toast.success(text);
  }
};

export const executeProcess = async <T>(
  processName: string,
  params: Record<string, any>
): Promise<T> => {
  const response = await axios.post(`/api/processes/${processName}`, params);
  return response.data;
};
```
