diff --git a/CHANGELOG.md b/CHANGELOG.md index 298aab6e6..4f3ba3024 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,10 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - API: recurring invoices can be changed, paused or resumed, and deleted, and their lines read, added, changed and taken off - a line can count its quantity from the client's users or devices, as in the line window. - API: expenses can be recorded, refunded, changed and deleted, with the same checks as the expense window. Services can be made, changed, archived and deleted, licenses made, changed and deleted, certificates changed, archived and deleted, and products made, archived and deleted. - API: tickets can be reopened and deleted, and replies edited and archived. Assets can be archived and unarchived, and documents, domains, networks and vendors deleted. Documents, domains, networks and vendors are archived before the API deletes them, as clients and contacts are, and a closed ticket is kept, not deleted. Deleting needs Full access. An admin's key can delete tags. A client's waiting portal invites can be listed and cancelled. +- API: payments can be read, recorded on an invoice that is sent and still owed on - no more than is owed, into one of your accounts, with the client's receipt emailed - changed, deleted, and their receipt sent again, with the same checks as the payment window. A payment cleared on a reconciled statement keeps its date, amount and account. Payments need Financial, with Read on Sales. Card payments are still charged and refunded in ITFlow. +- API: projects can be read - one with its tickets and its progress and time - started for a client or as internal work, with a project template's tickets, changed, completed once none of its tickets is open, reopened, archived, unarchived and deleted once archived. A template's tickets can be added to an open project. A ticket goes on or off a project with tickets/create and tickets/update. +- API: a ticket's tasks can be read, added, changed, marked done or not done, and deleted, and an approval can be asked of the client or your team, given by the key's agent, and taken off. A task waiting on an approval, or whose approval was declined, can't be marked done. +- API: recurring tickets can be read, made - from a ticket template, with its fill-ins answered and its tasks for those answers - changed, paused and resumed, raised now and deleted. ### Bug Fixes @@ -58,6 +62,9 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - The line endpoints of all three document types are one body, `api/v1/billing_lines.php`, included by files that set `$billing_type` (`invoice`, `quote`, `recurring`) and `$billing_op`. `billingLineFromApi()` (`functions/billing.php`) checks a line an API call sends - a product's name, description and price for those not sent, qty 1, `tax_id` `default` - and is shared by `recurring_invoices/create` (its messages are unchanged), `invoices/create`, `quotes/create` and the line creates. `billing_lines.php` and `quotes/quote_answer.php` refuse a request that doesn't come through an endpoint. - `enforce_api_rbac.php` maps `quote_items` and `recurring_invoice_items` to `module_sales`, and lists the state changes - `archive`, `unarchive`, `close`, `resolve`, `reopen`, `send`, `mark_sent`, `cancel`, `accept`, `decline`, `invoice`, `status` - at level 2 rather than leaving them to the default. `delete.php` stays at 3, a line's included. - The new updates answer success when the record is saved unchanged; the older ones still answer failure when no row changed. +- API endpoints: `payments/` `read`, `create`, `update`, `delete`, `send` (the receipt); `projects/` `read`, `create`, `update`, `complete`, `reopen`, `archive`, `unarchive`, `delete`, `apply_template`; `tasks/` `read`, `create`, `update`, `complete`, `delete`; `task_approvals/` `create`, `approve`, `delete`; `recurring_tickets/` `read`, `create`, `update`, `status`, `raise`, `delete`. They call `billingMoneyCan()`, `invoiceCanPay()`, `updateInvoiceStatusFromPayments()`, `reconcileCheckChange()`, `reconcileCheckDelete()`, `transferDepositRelease()`, `billingPaymentSend()`, `projectNextNumber()`, `projectApplyTemplate()`, `projectComplete()`, `projectReopen()`, `projectArchive()`, `projectRestore()`, `projectDelete()`, `projectNotifyManager()`, `projectStats()`, `ticketMailTaskApproval()`, `recurringTicketRunNow()`, `recurringTicketNextRun()`, `ticketFillInAnswers()`, `ticketTemplateTaskApplies()` and `recurringTicketMailAssigned()`; the task and recurring ticket handlers work inline, and their endpoints do the same steps. Payment and recurring ticket fields go through `payments/payment_model.php` and `recurring_tickets/recurring_ticket_model.php`, project fields through `projects/project_model.php`. +- `enforce_api_rbac.php` maps `payments` to `module_financial` (the endpoints also check Sales at Read through `billingMoneyCan()`), and `projects`, `tasks`, `task_approvals` and `recurring_tickets` to `module_support`, with `complete`, `approve`, `raise` and `apply_template` at level 2. +- `tickets/ticket_model.php` takes `ticket_project_id` - the client's project or an internal one (`ticketClientOwnedId()`), 0 to take it off - and turns down any other id rather than dropping it; `tickets/create` and `tickets/update` write it and the ticket's history. - `php_flag engine off` in `uploads/.htaccess`, its `backups`, `expenses`, `tmp` and `canned_responses` folders and `scripts/.htaccess` is wrapped in ``. Apache only knows `php_flag` under mod_php - with PHP-FPM through `mod_proxy_fcgi` it stops on the line and answers every request in the folder with a 500. Under FPM, PHP still can't run there: `uploads/.htaccess` denies `.php`, `.phtml`, `.phar` and the rest by name, and the other five deny everything. ## [26.11.8] diff --git a/api/v1/enforce_api_rbac.php b/api/v1/enforce_api_rbac.php index 88812bbe2..68a610865 100644 --- a/api/v1/enforce_api_rbac.php +++ b/api/v1/enforce_api_rbac.php @@ -150,6 +150,10 @@ $resource_module = [ 'tickets' => 'module_support', 'ticket_replies' => 'module_support', 'technicians' => 'module_support', + 'projects' => 'module_support', + 'tasks' => 'module_support', + 'task_approvals' => 'module_support', + 'recurring_tickets' => 'module_support', 'clients' => 'module_client', 'contacts' => 'module_client', 'locations' => 'module_client', @@ -164,6 +168,8 @@ $resource_module = [ 'products' => 'module_sales', 'taxes' => 'module_sales', 'expenses' => 'module_financial', + // Payments are accounting work - Financial, and api/v1/payments/ also needs Sales at Read to see the invoices (billingMoneyCan()) + 'payments' => 'module_financial', 'credentials' => 'module_credential', // Each kind of tag is its record's module - api/v1/tags/ checks the kind // asked about (tagApiKind()), so there is no one module to check here @@ -195,6 +201,10 @@ $operation_level = [ 'decline.php' => 2, 'invoice.php' => 2, 'status.php' => 2, + 'complete.php' => 2, + 'approve.php' => 2, + 'raise.php' => 2, + 'apply_template.php' => 2, ]; if (!isset($resource_module[$resource])) { diff --git a/api/v1/payments/create.php b/api/v1/payments/create.php new file mode 100644 index 000000000..87540bd64 --- /dev/null +++ b/api/v1/payments/create.php @@ -0,0 +1,126 @@ + (int) round($state['balance'] * 100)) { + $refuse = 'amount is more than is owed on ' . $reference_text . ' - ' . billingMoney($state['balance'], $currency) . '.'; + } elseif (!isset(paymentAccounts()[$account_id])) { + $refuse = 'account_id is needed - the account it went into. There is no default payment account (Admin > Settings > Invoices and billing).'; + } elseif ($payment_method === '' || !in_array($payment_method, paymentMethods('in'), true)) { + $refuse = 'payment_method is needed - how it was paid, one of: ' . implode(', ', paymentMethods('in')) . '.'; + } + if ($refuse !== '') { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $refuse; + echo json_encode($return_arr); + exit(); + } + + $date_sql = escapeSql($date); + $currency_sql = escapeSql($currency); + $method_sql = escapeSql($payment_method); + $reference_sql = escapeSql($reference); + + mysqli_query($mysqli, "INSERT INTO payments SET payment_date = '$date_sql', payment_amount = $amount, payment_currency_code = '$currency_sql', payment_account_id = $account_id, + payment_method = '$method_sql', payment_reference = '$reference_sql', payment_invoice_id = $invoice_id"); + $payment_id = intval(mysqli_insert_id($mysqli)); + + if ($payment_id) { + $insert_id = $payment_id; + + $status = updateInvoiceStatusFromPayments($invoice_id); + $money = billingMoney($amount, $currency); + billingLog('invoice', $invoice_id, $status, "Payment of $money added via the API (" . html_entity_decode($api_key_name, ENT_QUOTES, 'UTF-8') . ")"); + + logAudit("Invoice", "Payment", "Payment amount of " . escapeSql($money) . " added to invoice " . escapeSql($reference_text) . " via API ($api_key_name)", $client_id, $invoice_id); + logAudit("API", "Success", "Added a payment of " . escapeSql($money) . " to invoice " . escapeSql($reference_text) . " via API ($api_key_name)", $client_id); + + // The client's receipt (functions/billing_email.php) + $receipt_to = []; + // Left out, it goes when ITFlow sends mail - as the switch on Add Payment shows then + if (array_key_exists('email_receipt', $_POST) ? !empty($_POST['email_receipt']) : !empty($config_smtp_provider)) { + $receipt_to = billingPaymentSend($invoice_id, $amount, ['date' => $date, 'method' => $payment_method, 'reference' => $reference]); + if ($receipt_to) { + logAudit("Invoice", "Payment", "Payment receipt for invoice " . escapeSql($reference_text) . " queued to " . escapeSql(implode(', ', $receipt_to)), $client_id, $invoice_id); + } + } + + triggerCustomAction('invoice_pay', $invoice_id); + + $return_arr['invoice_status'] = (string) getFieldById('invoices', $invoice_id, 'invoice_status'); + $return_arr['balance'] = round(floatval($invoice['invoice_amount']) - invoicePaid($invoice_id), 2); + $return_arr['receipt_to'] = array_values($receipt_to); + } +} + +// Output +require_once '../create_output.php'; diff --git a/api/v1/payments/delete.php b/api/v1/payments/delete.php new file mode 100644 index 000000000..36f892ad0 --- /dev/null +++ b/api/v1/payments/delete.php @@ -0,0 +1,59 @@ + 0) { + // From what is left + $status = updateInvoiceStatusFromPayments($invoice_id); + $money = billingMoney($row['payment_amount'], $row['payment_currency_code']); + billingLog('invoice', $invoice_id, $status, "Payment of $money deleted via the API (" . html_entity_decode($api_key_name, ENT_QUOTES, 'UTF-8') . ")"); + + logAudit("Invoice", "Edit", "Deleted a payment of " . escapeSql($money) . " on invoice " . escapeSql($reference_text) . " via API ($api_key_name)", $client_id, $invoice_id); + logAudit("API", "Success", "Deleted a payment on invoice " . escapeSql($reference_text) . " via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/payments/payment_model.php b/api/v1/payments/payment_model.php new file mode 100644 index 000000000..5c7183c7f --- /dev/null +++ b/api/v1/payments/payment_model.php @@ -0,0 +1,78 @@ +format('Y-m-d') !== $value || $value > '2999-12-31') { + $payment_model_error = 'date is a date - 2026-11-05.'; + } else { + $payment_set['date'] = $value; + } +} + +if (array_key_exists('amount', $_POST)) { + $amount = billingNumberInput(is_scalar($_POST['amount']) ? $_POST['amount'] : ''); + if ($amount === null || $amount <= 0) { + $payment_model_error = 'amount is what was paid - more than 0, such as 150.00.'; + } else { + $payment_set['amount'] = $amount; + } +} + +if (array_key_exists('account_id', $_POST)) { + $accounts = paymentAccounts(intval($payment_row['payment_account_id'] ?? 0)); + $account_id = intval($_POST['account_id']); + if (!isset($accounts[$account_id])) { + $payment_model_error = 'account_id is the account it went into, one of: ' . implode(', ', array_map(function ($account) { + return $account['account_id'] . ' (' . $account['account_name'] . ')'; + }, $accounts)) . '.'; + } else { + $payment_set['account_id'] = $account_id; + } +} + +if (array_key_exists('payment_method', $_POST)) { + $methods = paymentMethods('in'); + $current = (string) ($payment_row['payment_method'] ?? ''); + if ($current !== '' && !in_array($current, $methods, true)) { + $methods[] = $current; + } + $posted = trim((string) (is_scalar($_POST['payment_method']) ? $_POST['payment_method'] : '')); + $match = null; + foreach ($methods as $method) { + if (strcasecmp($method, $posted) === 0) { + $match = $method; + } + } + if ($match === null) { + $payment_model_error = 'payment_method is how it was paid, one of: ' . implode(', ', $methods) . '.'; + } else { + $payment_set['payment_method'] = $match; + } +} + +if (array_key_exists('reference', $_POST)) { + $payment_set['reference'] = mb_substr(trim((string) (is_scalar($_POST['reference']) ? $_POST['reference'] : '')), 0, 200); +} + +if ($payment_model_error !== '') { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $payment_model_error; + echo json_encode($return_arr); + exit(); +} diff --git a/api/v1/payments/read.php b/api/v1/payments/read.php new file mode 100644 index 000000000..c4201f69a --- /dev/null +++ b/api/v1/payments/read.php @@ -0,0 +1,38 @@ + $row['payment_date'], + 'method' => (string) $row['payment_method'], + 'reference' => (string) $row['payment_reference'], + ]); + if (!$receipt_to) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $row['client_name'] . ' has no primary or billing contact with an email address to send the receipt to.'; + echo json_encode($return_arr); + exit(); + } + + $update_count = 1; + $return_arr['receipt_to'] = array_values($receipt_to); + + logAudit("Invoice", "Payment", "Payment receipt for invoice " . escapeSql($reference_text) . " queued to " . escapeSql(implode(', ', $receipt_to)) . " via API ($api_key_name)", $client_id, intval($row['invoice_id'])); + logAudit("API", "Success", "Sent a payment receipt for invoice " . escapeSql($reference_text) . " via API ($api_key_name)", $client_id); +} + +// Output +require_once '../update_output.php'; diff --git a/api/v1/payments/update.php b/api/v1/payments/update.php new file mode 100644 index 000000000..af1143e0e --- /dev/null +++ b/api/v1/payments/update.php @@ -0,0 +1,98 @@ + (int) round($room * 100)) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = "amount is more than $reference_text has left to pay with its other payments - " . billingMoney(max(0, $room), $payment_row['invoice_currency_code']) . '.'; + echo json_encode($return_arr); + exit(); + } + + // Cleared on a reconciled statement - its date, amount and account stay + $error = ''; + if (!reconcileCheckChange('payment', $payment_id, $date, $amount, $account_id, $error)) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $error . '.'; + echo json_encode($return_arr); + exit(); + } + // Moved to another account - out of the deposit it was in + transferDepositRelease('payment', $payment_id, $account_id); + + $date_sql = escapeSql($date); + $method_sql = escapeSql($payment_method); + $reference_sql = escapeSql($reference); + + $update_sql = mysqli_query($mysqli, "UPDATE payments SET payment_date = '$date_sql', payment_amount = $amount, payment_account_id = $account_id, + payment_method = '$method_sql', payment_reference = '$reference_sql' WHERE payment_id = $payment_id"); + + if ($update_sql) { + $update_count = 1; + + // A changed amount can leave the invoice paid, part paid or owing again + updateInvoiceStatusFromPayments($invoice_id); + + $money = escapeSql(billingMoney($amount, $payment_row['invoice_currency_code'])); + logAudit("Payment", "Edit", "Payment on invoice " . escapeSql($reference_text) . " edited to $money via API ($api_key_name)", intval($payment_row['invoice_client_id']), $invoice_id); + logAudit("API", "Success", "Edited a payment on invoice " . escapeSql($reference_text) . " via API ($api_key_name)", intval($payment_row['invoice_client_id'])); + } +} + +// Output +require_once '../update_output.php'; diff --git a/api/v1/projects/apply_template.php b/api/v1/projects/apply_template.php new file mode 100644 index 000000000..cb7eb186b --- /dev/null +++ b/api/v1/projects/apply_template.php @@ -0,0 +1,65 @@ + Project Templates) + * assign_to_manager optional - 1: the tickets go to the project's manager + * + * Answer: tickets_raised. + */ + +require_once '../validate_api_key.php'; +require_once '../require_post_method.php'; +require_once "../../../includes/load_global_settings.php"; + +$project_id = intval($_POST['project_id'] ?? 0); + +$row = $project_id ? projectRow($project_id) : null; +if ($row && (!apiUserCanAccessClient($row['project_client_id']) || ($client_id && intval($row['project_client_id']) !== $client_id))) { + $row = null; +} + +$update_count = false; + +if ($row) { + + $client_id = intval($row['project_client_id']); + $reference = projectReference($row); + + $refuse = ''; + $project_template_id = intval($_POST['project_template_id'] ?? 0); + if (!projectIsOpen($row)) { + $refuse = "Project $reference isn't open - " . (!empty($row['project_archived_at']) ? 'it is archived.' : 'it is completed, reopen it first.'); + } elseif (!$project_template_id || !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM project_templates WHERE project_template_id = $project_template_id AND project_template_archived_at IS NULL"))) { + $refuse = 'project_template_id is one of your project templates - see Admin > Project Templates.'; + } + if ($refuse !== '') { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $refuse; + echo json_encode($return_arr); + exit(); + } + + $raised = projectApplyTemplate($row, $project_template_id, intval($_POST['assign_to_manager'] ?? 0) ? $row['project_manager'] : 0); + + $update_count = 1; + $return_arr['tickets_raised'] = $raised; + + $label = escapeSql($reference . ' - ' . $row['project_name']); + logAudit("Project", "Edit", "Added $raised ticket" . ($raised === 1 ? '' : 's') . " from a template to project $label via API ($api_key_name)", $client_id, intval($row['project_id'])); + logAudit("API", "Success", "Applied a template to project $label via API ($api_key_name)", $client_id); +} + +// Output +require_once '../update_output.php'; diff --git a/api/v1/projects/archive.php b/api/v1/projects/archive.php new file mode 100644 index 000000000..92faaf105 --- /dev/null +++ b/api/v1/projects/archive.php @@ -0,0 +1,35 @@ + Project Templates) to raise tickets from + * assign_to_manager optional - 1: the template's tickets go to the manager + * + * Answer: insert_id, and project_reference and tickets_raised. + */ + +require_once '../validate_api_key.php'; +require_once '../require_post_method.php'; +require_once "../../../includes/load_global_settings.php"; + +$insert_id = false; + +$client_ok = !$client_id || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id AND client_archived_at IS NULL")); + +if (!$client_ok) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = "There is no client $client_id - it may be archived. Leave client_id out for internal work."; + echo json_encode($return_arr); + exit(); +} + +if ($client_ok) { + + require_once 'project_model.php'; + + $refuse = ''; + if (!isset($project_set['project_name'])) { + $refuse = 'A project needs a name - project_name.'; + } + $project_template_id = intval($_POST['project_template_id'] ?? 0); + if ($project_template_id && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM project_templates WHERE project_template_id = $project_template_id AND project_template_archived_at IS NULL"))) { + $refuse = "There is no project template $project_template_id - it may be archived. See Admin > Project Templates."; + } + if ($refuse !== '') { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $refuse; + echo json_encode($return_arr); + exit(); + } + + $project_number = projectNextNumber(); + $project_prefix = escapeSql($config_project_prefix); + $manager = intval($project_set['project_manager'] ?? 0); + + mysqli_query($mysqli, "INSERT INTO projects SET project_prefix = '$project_prefix', project_number = $project_number, project_name = {$project_set['project_name']}, + project_description = " . ($project_set['project_description'] ?? "''") . ", project_start = " . ($project_set['project_start'] ?? 'NULL') . ", + project_due = " . ($project_set['project_due'] ?? 'NULL') . ", project_budget_hours = " . ($project_set['project_budget_hours'] ?? 'NULL') . ", + project_manager = $manager, project_contact_id = " . intval($project_set['project_contact_id'] ?? 0) . ", project_client_id = $client_id"); + + $project_id = intval(mysqli_insert_id($mysqli)); + + if ($project_id) { + $insert_id = $project_id; + $row = projectRow($project_id); + + // A template's tickets - to the manager when asked + $raised = $project_template_id ? projectApplyTemplate($row, $project_template_id, intval($_POST['assign_to_manager'] ?? 0) ? $manager : 0) : 0; + + projectNotifyManager($row, $manager); + + $reference = projectReference($row); + $return_arr['project_reference'] = $reference; + $return_arr['tickets_raised'] = $raised; + + $label = escapeSql($reference . ' - ' . $row['project_name']); + logAudit("Project", "Create", "Created project $label via API ($api_key_name)", $client_id, $project_id); + logAudit("API", "Success", "Created project $label via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../create_output.php'; diff --git a/api/v1/projects/delete.php b/api/v1/projects/delete.php new file mode 100644 index 000000000..ff2906d6e --- /dev/null +++ b/api/v1/projects/delete.php @@ -0,0 +1,38 @@ + 'project_start', 'project_due' => 'project_due'] as $field => $column) { + if (array_key_exists($field, $_POST)) { + $value = trim((string) (is_scalar($_POST[$field]) ? $_POST[$field] : '')); + $sql_value = projectDateSql($value); + if ($value !== '' && $sql_value === 'NULL') { + $project_model_error = "$field is a date - 2026-11-05 - or empty for none."; + } + $project_set[$column] = $sql_value; + } +} +$start = $project_set['project_start'] ?? (!empty($project_row['project_start']) ? "'" . $project_row['project_start'] . "'" : 'NULL'); +$due = $project_set['project_due'] ?? (!empty($project_row['project_due']) ? "'" . $project_row['project_due'] . "'" : 'NULL'); +if ($start !== 'NULL' && $due !== 'NULL' && $due < $start) { + $project_model_error = 'The due date is before the start date.'; +} + +if (array_key_exists('project_budget_hours', $_POST)) { + $value = trim((string) (is_scalar($_POST['project_budget_hours']) ? $_POST['project_budget_hours'] : '')); + $budget = projectBudgetHours($value); + if ($value !== '' && $value !== '0' && $budget === null) { + $project_model_error = 'project_budget_hours is the hours sold for it, such as 40 - or empty for no budget.'; + } + $project_set['project_budget_hours'] = $budget === null ? 'NULL' : number_format($budget, 2, '.', ''); +} + +if (array_key_exists('project_manager', $_POST)) { + $manager = ticketAgentId($_POST['project_manager']); + if (intval($_POST['project_manager']) && !$manager) { + $project_model_error = 'project_manager is an active agent - see technicians/read.php - or 0 for none.'; + } + $project_set['project_manager'] = $manager; +} + +if (array_key_exists('project_contact_id', $_POST)) { + $contact = projectContactId($_POST['project_contact_id'], $client_id); + if (intval($_POST['project_contact_id']) && !$contact) { + $project_model_error = $client_id ? "project_contact_id isn't one of the client's contacts." : 'An internal project has no client contact.'; + } + $project_set['project_contact_id'] = $contact; +} + +if ($project_model_error !== '') { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $project_model_error; + echo json_encode($return_arr); + exit(); +} diff --git a/api/v1/projects/read.php b/api/v1/projects/read.php new file mode 100644 index 000000000..834de5a5e --- /dev/null +++ b/api/v1/projects/read.php @@ -0,0 +1,44 @@ + 'True', 'count' => 1, 'data' => [$row]]); + exit(); + } +} else { + $sql = mysqli_query($mysqli, "SELECT $columns FROM projects WHERE 1=1 " . apiClientScopeSql('project_client_id') . " ORDER BY project_id LIMIT $limit OFFSET $offset"); +} + +// Output +require_once "../read_output.php"; diff --git a/api/v1/projects/reopen.php b/api/v1/projects/reopen.php new file mode 100644 index 000000000..203cfdd13 --- /dev/null +++ b/api/v1/projects/reopen.php @@ -0,0 +1,45 @@ + Ticket Templates) + * fill_ins optional - The template's fill-ins answered: {"Name": "answer"} + * tasks optional - Its tasks: names, or {"name": "...", "estimate": minutes} + * + * Answer: insert_id, and next_date. + */ + +require_once '../validate_api_key.php'; +require_once '../require_post_method.php'; +require_once "../../../includes/load_global_settings.php"; + +$insert_id = false; + +if (!$client_id || !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id AND client_archived_at IS NULL"))) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = 'client_id is required - the client it is for.'; + echo json_encode($return_arr); + exit(); +} + +require_once 'recurring_ticket_model.php'; + +// From a template - what it sets, for whatever the request leaves out +if ($rt_template) { + if (!isset($rt_set['recurring_ticket_subject'])) { + $subject = trim((string) $rt_template['ticket_template_subject']) !== '' ? (string) $rt_template['ticket_template_subject'] : (string) $rt_template['ticket_template_name']; + $rt_set['recurring_ticket_subject'] = "'" . escapeSql(mb_substr($subject, 0, 500)) . "'"; + } + $rt_set += [ + 'recurring_ticket_details' => "'" . mysqli_real_escape_string($mysqli, (string) $rt_template['ticket_template_details']) . "'", + 'recurring_ticket_priority' => "'" . escapeSql(ticketPriority($rt_template['ticket_template_priority'] ?? '')) . "'", + 'recurring_ticket_category' => ticketCategoryId($rt_template['ticket_template_category_id']), + 'recurring_ticket_assigned_to' => ticketAgentId($rt_template['ticket_template_assigned_to']), + ]; + if (!isset($rt_set['recurring_ticket_billable']) && $rt_template['ticket_template_billable'] !== null && intval(lookupUserPermission('module_sales')) >= 2) { + $rt_set['recurring_ticket_billable'] = intval($rt_template['ticket_template_billable']) ? 1 : 0; + } + if ($rt_tasks === null) { + $rt_tasks = []; + foreach (ticketTemplateTasks($rt_template['ticket_template_id']) as $task) { + if (ticketTemplateTaskApplies($task, $rt_fill_ins ?? [])) { + $rt_tasks[] = [$task['name'], intval($task['estimate'])]; + } + } + } +} + +$start_date = array_key_exists('start_date', $_POST) ? recurringTicketDate($_POST['start_date']) : date('Y-m-d'); +if (!$start_date || $start_date < date('Y-m-d')) { + $rt_refuse('start_date is its first run - a date, today or later, such as ' . date('Y-m-d') . '.'); +} +if (!isset($rt_set['recurring_ticket_subject'])) { + $rt_refuse('A recurring ticket needs a subject.'); +} +if (!isset($rt_set['recurring_ticket_frequency'])) { + $rt_refuse('frequency is how often it runs, one of: ' . implode(', ', array_keys(RECURRING_TICKET_FREQUENCIES)) . '.'); +} + +$rt_set += [ + 'recurring_ticket_details' => "''", + 'recurring_ticket_priority' => "'Medium'", + 'recurring_ticket_billable' => 0, + 'recurring_ticket_assigned_to' => 0, + 'recurring_ticket_contact_id' => 0, + 'recurring_ticket_asset_id' => 0, + 'recurring_ticket_category' => 0, + 'recurring_ticket_ticket_template_id' => 0, +]; +$rt_set['recurring_ticket_start_date'] = "'$start_date'"; +$rt_set['recurring_ticket_next_run'] = "'$start_date'"; +$rt_set['recurring_ticket_created_by'] = intval($session_user_id); +$rt_set['recurring_ticket_client_id'] = $client_id; + +mysqli_query($mysqli, "INSERT INTO recurring_tickets SET " . implode(', ', array_map(function ($column, $value) { + return "$column = $value"; +}, array_keys($rt_set), $rt_set))); + +$recurring_ticket_id = intval(mysqli_insert_id($mysqli)); + +if ($recurring_ticket_id) { + $insert_id = $recurring_ticket_id; + + $row = recurringTicketRow($recurring_ticket_id); + $rt_subject = (string) $row['recurring_ticket_subject']; + $rt_notify_agent = intval($row['recurring_ticket_assigned_to']); + require 'recurring_ticket_save.php'; + + $return_arr['next_date'] = $start_date; + + $label = escapeSql($rt_subject . ' - ' . $row['recurring_ticket_frequency']); + logAudit("Recurring Ticket", "Create", "Created recurring ticket $label via API ($api_key_name)", $client_id, $recurring_ticket_id); + logAudit("API", "Success", "Created recurring ticket $label via API ($api_key_name)", $client_id); +} + +// Output +require_once '../create_output.php'; diff --git a/api/v1/recurring_tickets/delete.php b/api/v1/recurring_tickets/delete.php new file mode 100644 index 000000000..1844087ae --- /dev/null +++ b/api/v1/recurring_tickets/delete.php @@ -0,0 +1,33 @@ + 0) { + $subject = escapeSql($rt_row['recurring_ticket_subject']); + logAudit("Recurring Ticket", "Delete", "Deleted recurring ticket $subject via API ($api_key_name)", $client_id, $recurring_ticket_id); + logAudit("API", "Success", "Deleted recurring ticket $subject via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/recurring_tickets/raise.php b/api/v1/recurring_tickets/raise.php new file mode 100644 index 000000000..c0c5d73e7 --- /dev/null +++ b/api/v1/recurring_tickets/raise.php @@ -0,0 +1,46 @@ + $task['name'], 'estimate' => intval($task['estimate'])]; + } + $row['asset_ids'] = []; + $assets = mysqli_query($mysqli, "SELECT asset_id FROM recurring_ticket_assets WHERE recurring_ticket_id = $id ORDER BY asset_id"); + while ($asset = mysqli_fetch_row($assets)) { + $row['asset_ids'][] = intval($asset[0]); + } + $row['fill_ins'] = array_map(function ($answer) { + return ['name' => $answer['name'], 'type' => $answer['type'], 'value' => $answer['value']]; + }, ticketFillInsStored('recurring_ticket', $id)); + echo json_encode(['success' => 'True', 'count' => 1, 'data' => [$row]]); + exit(); + } +} else { + $sql = mysqli_query($mysqli, "SELECT * FROM recurring_tickets WHERE 1=1 " . apiClientScopeSql('recurring_ticket_client_id') . " ORDER BY recurring_ticket_id LIMIT $limit OFFSET $offset"); +} + +// Output +require_once "../read_output.php"; diff --git a/api/v1/recurring_tickets/recurring_ticket_model.php b/api/v1/recurring_tickets/recurring_ticket_model.php new file mode 100644 index 000000000..0f361d0a2 --- /dev/null +++ b/api/v1/recurring_tickets/recurring_ticket_model.php @@ -0,0 +1,149 @@ + SQL value, for what was sent +// $rt_assets its other assets (ids, the client's own), or null to leave them +// $rt_tasks its tasks ([name, estimate]), or null to leave them +// $rt_fill_ins the answers to its template's fill-ins (ticketFillInAnswers()), or null to leave them +// $rt_template the template it is raised from, when one was sent (its row) +// +// Anything that won't do is turned down with 400 and why. + +if (!function_exists('apiDeny')) { + http_response_code(404); + exit(); +} + +$rt_row = $rt_row ?? null; +$rt_set = []; +$rt_assets = null; +$rt_tasks = null; +$rt_fill_ins = null; +$rt_template = null; + +$rt_refuse = function ($message) use (&$return_arr) { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $message; + echo json_encode($return_arr); + exit(); +}; +$rt_text = function ($field) { + return trim((string) (is_scalar($_POST[$field] ?? '') ? ($_POST[$field] ?? '') : '')); +}; + +if (array_key_exists('subject', $_POST)) { + if ($rt_text('subject') === '') { + $rt_refuse('A recurring ticket needs a subject.'); + } + $rt_set['recurring_ticket_subject'] = "'" . escapeSql(mb_substr($rt_text('subject'), 0, 500)) . "'"; +} +if (array_key_exists('details', $_POST)) { + $rt_set['recurring_ticket_details'] = "'" . mysqli_real_escape_string($mysqli, (string) (is_scalar($_POST['details']) ? $_POST['details'] : '')) . "'"; +} +if (array_key_exists('priority', $_POST)) { + if (!in_array($_POST['priority'], TICKET_PRIORITIES, true)) { + $rt_refuse('priority is one of: ' . implode(', ', TICKET_PRIORITIES) . '.'); + } + $rt_set['recurring_ticket_priority'] = "'" . escapeSql($_POST['priority']) . "'"; +} +if (array_key_exists('frequency', $_POST)) { + $frequency = recurringTicketFrequency($rt_text('frequency')); + if ($frequency === '') { + $rt_refuse('frequency is how often it runs, one of: ' . implode(', ', array_keys(RECURRING_TICKET_FREQUENCIES)) . '.'); + } + $rt_set['recurring_ticket_frequency'] = "'" . escapeSql($frequency) . "'"; +} + +// Billing is the sales module's to change, as in the form +if (array_key_exists('billable', $_POST)) { + if (intval(lookupUserPermission('module_sales')) < 2) { + apiDeny(apiPermissionText('module_sales', 2)); + } + $rt_set['recurring_ticket_billable'] = intval($_POST['billable']) ? 1 : 0; +} + +if (array_key_exists('assigned_to', $_POST)) { + $assigned_to = ticketAgentId($_POST['assigned_to']); + if (intval($_POST['assigned_to']) && !$assigned_to) { + $rt_refuse('assigned_to is an active agent - see technicians/read.php - or 0 for nobody.'); + } + $rt_set['recurring_ticket_assigned_to'] = $assigned_to; +} + +// What it links to has to be the client's own +foreach (['contact_id' => ['contact', 'recurring_ticket_contact_id'], 'asset_id' => ['asset', 'recurring_ticket_asset_id']] as $field => [$kind, $column]) { + if (array_key_exists($field, $_POST)) { + $id = ticketClientOwnedId($kind, $_POST[$field], $client_id); + if (intval($_POST[$field]) && !$id) { + $rt_refuse("$field isn't one of the client's {$kind}s."); + } + $rt_set[$column] = $id; + } +} +if (array_key_exists('asset_ids', $_POST)) { + $primary = intval($rt_set['recurring_ticket_asset_id'] ?? ($rt_row['recurring_ticket_asset_id'] ?? 0)); + $wanted = array_values(array_diff(array_unique(array_filter(array_map('intval', (array) $_POST['asset_ids']))), [$primary])); + $rt_assets = ticketClientOwnedAssetIds($wanted, $client_id, $primary); + if (count($rt_assets) !== count($wanted)) { + $rt_refuse("asset_ids are the client's own other assets - these aren't: " . implode(', ', array_diff($wanted, $rt_assets)) . '.'); + } +} + +if (array_key_exists('category_id', $_POST)) { + $category_id = ticketCategoryId($_POST['category_id']); + if (intval($_POST['category_id']) && !$category_id) { + $rt_refuse('category_id is a ticket category - see categories/read.php.'); + } + $rt_set['recurring_ticket_category'] = $category_id; +} + +// The template - its fill-ins answered, from what it keeps for those not sent +$template_id = array_key_exists('ticket_template_id', $_POST) ? intval($_POST['ticket_template_id']) : intval($rt_row['recurring_ticket_ticket_template_id'] ?? 0); +if (array_key_exists('ticket_template_id', $_POST)) { + if ($template_id) { + $rt_template = ticketTemplateRow($template_id); + if (!$rt_template || !empty($rt_template['ticket_template_archived_at'])) { + $rt_refuse("There is no ticket template $template_id - it may have been archived. See Admin > Ticket Templates."); + } + } + $rt_set['recurring_ticket_ticket_template_id'] = $template_id; +} +if ($template_id && (array_key_exists('ticket_template_id', $_POST) || array_key_exists('fill_ins', $_POST))) { + $posted = $_POST['fill_ins'] ?? []; + if (!is_array($posted)) { + $rt_refuse("fill_ins is a JSON object of the template's fill-ins and their answers - {\"Name\": \"answer\"}."); + } + $given = []; + if ($rt_row && intval($rt_row['recurring_ticket_ticket_template_id']) === $template_id) { + foreach (ticketFillInsStored('recurring_ticket', $rt_row['recurring_ticket_id']) as $stored) { + $given[$stored['name']] = $stored['value']; + } + } + foreach ($posted as $name => $value) { + $given[$name] = $value; + } + $rt_fill_ins = ticketFillInAnswers(ticketTemplateFillInsFor($template_id), $given, $fill_in_error); + if ($rt_fill_ins === null) { + $rt_refuse(html_entity_decode(strip_tags($fill_in_error), ENT_QUOTES | ENT_HTML5, 'UTF-8')); + } +} + +// Its tasks - names, or {"name": ..., "estimate": minutes} +if (array_key_exists('tasks', $_POST)) { + if (!is_array($_POST['tasks']) || count($_POST['tasks']) > 100) { + $rt_refuse('tasks is a list of up to 100 - each a name, or {"name": "...", "estimate": 15}.'); + } + $rt_tasks = []; + foreach (array_values($_POST['tasks']) as $task) { + $name = trim((string) (is_array($task) ? ($task['name'] ?? '') : (is_scalar($task) ? $task : ''))); + if ($name !== '') { + $rt_tasks[] = [mb_substr($name, 0, 255), max(0, intval(is_array($task) ? ($task['estimate'] ?? 0) : 0))]; + } + } +} diff --git a/api/v1/recurring_tickets/recurring_ticket_save.php b/api/v1/recurring_tickets/recurring_ticket_save.php new file mode 100644 index 000000000..ffeec3a8c --- /dev/null +++ b/api/v1/recurring_tickets/recurring_ticket_save.php @@ -0,0 +1,38 @@ + [$name, $estimate]) { + mysqli_query($mysqli, "INSERT INTO recurring_ticket_tasks SET recurring_ticket_task_name = '" . escapeSql($name) . "', recurring_ticket_task_order = $order, + recurring_ticket_task_completion_estimate = " . intval($estimate) . ", recurring_ticket_task_recurring_ticket_id = $recurring_ticket_id"); + } +} + +if ($rt_fill_ins !== null) { + ticketFillInsStore('recurring_ticket', $recurring_ticket_id, $rt_fill_ins); +} + +// Its agent hears, not the key's own +if ($rt_notify_agent && $rt_notify_agent !== intval($session_user_id)) { + $by = html_entity_decode($api_key_name, ENT_QUOTES, 'UTF-8'); + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Recurring Ticket', notification = '" . escapeSql("Recurring ticket $rt_subject has been assigned to you by the API ($by)") . "', + notification_action = 'recurring_tickets.php?assigned_agent=$rt_notify_agent', notification_user_id = $rt_notify_agent"); + recurringTicketMailAssigned($rt_notify_agent, [$rt_subject], "The API ($by)"); +} diff --git a/api/v1/recurring_tickets/rt_find.php b/api/v1/recurring_tickets/rt_find.php new file mode 100644 index 000000000..2695a3dfb --- /dev/null +++ b/api/v1/recurring_tickets/rt_find.php @@ -0,0 +1,18 @@ + 0 && $required_user !== $session_user_id) { + $refuse = 'This approval is for another agent.'; + } elseif ($required_user === 0 && $created_by === $session_user_id) { + $refuse = "The key's agent asked for this approval - someone else has to give it."; + } + if ($refuse !== '') { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $refuse; + echo json_encode($return_arr); + exit(); + } + + mysqli_query($mysqli, "UPDATE task_approvals SET approval_status = 'approved', approval_approved_by = $session_user_id WHERE approval_id = $approval_id AND approval_status = 'pending'"); + + if (mysqli_affected_rows($mysqli) > 0) { + $update_count = 1; + $ticket_id = intval($task['ticket_id']); + $task_name_sql = escapeSql($task_name); + + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name approved ticket task $task_name_sql', notification_action = 'ticket.php?ticket_id=$ticket_id', notification_client_id = 0, notification_user_id = $created_by"); + + logAudit("Task", "Edit", "$session_name approved task $task_name_sql (approval $approval_id) via API ($api_key_name)", $client_id, intval($task['task_id'])); + logAudit("API", "Success", "Approved task $task_name_sql via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../update_output.php'; diff --git a/api/v1/task_approvals/create.php b/api/v1/task_approvals/create.php new file mode 100644 index 000000000..212709491 --- /dev/null +++ b/api/v1/task_approvals/create.php @@ -0,0 +1,90 @@ + ['any', 'technical', 'billing'], 'internal' => ['any', 'specific']]; + $required_user_id = 0; + + $refuse = $task_locked; + if ($refuse === '' && !empty($task['task_completed_at'])) { + $refuse = 'Task ' . $task['task_name'] . ' is done already.'; + } elseif ($refuse === '' && !isset($types[$scope])) { + $refuse = 'approval_scope is who approves it - client or internal.'; + } elseif ($refuse === '' && !in_array($type, $types[$scope], true)) { + $refuse = "approval_type for $scope is one of: " . implode(', ', $types[$scope]) . '.'; + } elseif ($refuse === '' && $type === 'specific') { + $required_user_id = ticketAgentId($_POST['approval_required_user_id'] ?? 0); + if (!$required_user_id) { + $refuse = 'approval_required_user_id is the agent who has to approve it - an active one, see technicians/read.php.'; + } + } elseif ($refuse === '' && $scope === 'client' && !$client_id) { + $refuse = "An internal ticket has no client to approve it - use approval_scope internal."; + } + if ($refuse !== '') { + http_response_code(400); + $return_arr['success'] = "False"; + $return_arr['message'] = $refuse; + echo json_encode($return_arr); + exit(); + } + + $url_key = randomString(32); + mysqli_query($mysqli, "INSERT INTO task_approvals SET approval_scope = '$scope', approval_type = '$type', approval_required_user_id = " . ($required_user_id ?: 'NULL') . ", + approval_status = 'pending', approval_created_by = $session_user_id, approval_url_key = '$url_key', approval_task_id = $task_id"); + $approval_id = intval(mysqli_insert_id($mysqli)); + + if ($approval_id) { + $insert_id = $approval_id; + + $task_name = escapeSql($task['task_name']); + $ticket_id = intval($task['ticket_id']); + $by = html_entity_decode($api_key_name, ENT_QUOTES, 'UTF-8'); + $by = stripslashes($session_name) . " (the API, $by)"; + + // The agent named hears in the app too + if ($scope === 'internal' && $type === 'specific' && $required_user_id !== $session_user_id) { + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '" . escapeSql("$by needs your approval for ticket " . ticketReference($task) . " task " . $task['task_name']) . "', + notification_action = 'ticket.php?ticket_id=$ticket_id', notification_client_id = 0, notification_user_id = $required_user_id"); + } + + // Who is asked, by email (functions/ticket.php) + $return_arr['emailed'] = intval(ticketMailTaskApproval($approval_id, $by)); + + logAudit("Task", "Edit", "Added a task approver for $task_name via API ($api_key_name)", $client_id, $task_id); + logAudit("API", "Success", "Asked for approval of task $task_name via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../create_output.php'; diff --git a/api/v1/task_approvals/delete.php b/api/v1/task_approvals/delete.php new file mode 100644 index 000000000..4fbd31208 --- /dev/null +++ b/api/v1/task_approvals/delete.php @@ -0,0 +1,36 @@ + 0) { + $name = escapeSql($task['task_name']); + logAudit("Task", "Delete", "Deleted the approval request on task $name via API ($api_key_name)", $client_id, intval($task['task_id'])); + logAudit("API", "Success", "Deleted the approval request on task $name via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/tasks/complete.php b/api/v1/tasks/complete.php new file mode 100644 index 000000000..1d17a20b9 --- /dev/null +++ b/api/v1/tasks/complete.php @@ -0,0 +1,68 @@ + 0) { + $name = escapeSql($task['task_name']); + logAudit("Task", "Delete", "Deleted task $name via API ($api_key_name)", $client_id, $task_id); + logAudit("API", "Success", "Deleted task $name via API ($api_key_name)", $client_id); + } +} + +// Output +require_once '../delete_output.php'; diff --git a/api/v1/tasks/read.php b/api/v1/tasks/read.php new file mode 100644 index 000000000..03d0dcfd4 --- /dev/null +++ b/api/v1/tasks/read.php @@ -0,0 +1,54 @@ + 'True', 'count' => count($tasks), 'data' => array_values($tasks)]); + exit(); +} + +$sql = false; + +// Output +require_once "../read_output.php"; diff --git a/api/v1/tasks/task_find.php b/api/v1/tasks/task_find.php new file mode 100644 index 000000000..fd8fdcc52 --- /dev/null +++ b/api/v1/tasks/task_find.php @@ -0,0 +1,25 @@ +