# Altria CRM — cPanel Deployment Guide

Deployment package for **crm.altriacallcenter.com** (cPanel user `altriaca`, Python 3.11).

This package contains the **full application**. Extracting it over your existing
installation updates every code file and leaves your server-only files
(`.env.production`, integration `.env` files, uploaded media) untouched.

---

## What is new in this release

| Area | Change |
|---|---|
| Client portal | Dashboard stat cards (Total / Open / Resolved / Escalated) are now clickable and filter My Tickets |
| SLA | Policies can be **edited** and **deleted**; Active/Inactive can be set |
| SLA | Every **new client automatically gets a full 4-tier SLA policy set**, scaled to its service tier |
| Users | **Delete User** button with a styled confirmation dialog |
| Users | Deleting a client now **deactivates** that client's users instead of orphaning them |
| Email → ticket | **Automatic priority** from the subject line (critical / high / medium / low) |
| Email → ticket | **Automatic SLA assignment** — response and resolution deadlines are set on creation |
| Email → ticket | Stricter threading — only genuine replies join an existing ticket |
| AI | **AI Auto-Reply Agent** — reads incoming email, identifies the concern, writes a human-style reply |
| AI | Admin UI to enable auto-reply and switch between Draft-only and Auto-send |
| Watcher | `watch_emails` re-reads the account list each cycle, so new mailboxes are picked up without a restart |

### Database changes (migrations included)

| App | Migration | Adds |
|---|---|---|
| `core` | `0008_systemconfig_autoreply_confidence_and_more` | `autoreply_enabled`, `autoreply_confidence` on SystemConfig |
| `ai_services` | `0001_initial` | `ScheduledReply` table (queued auto-replies) |

Both are additive. **No existing table or column is altered or dropped.**

---

## Before you start

1. **Take a backup.** In cPanel → File Manager, compress the current
   `crm.altriacallcenter.com` folder and download it. Also export the
   `altriaca_altriacrm` database from phpMyAdmin.
2. Confirm you can reach cPanel → **Setup Python App** →
   `CRM.ALTRIACALLCENTER.COM`.

> Deploy outside business hours where possible — the app restarts at step 6.

---

## Step 1 — Upload and extract

1. cPanel → **File Manager** → go to `/home/altriaca/`.
2. Upload `crm-deploy.zip`.
3. Right-click it → **Extract** → extract into `/home/altriaca/`.
4. Choose **Overwrite** when prompted. Files are replaced; your
   `.env.production` and integration `.env` files are not in this package and
   remain exactly as they are.
5. Delete the uploaded zip when finished.

---

## Step 2 — Enter the virtual environment

cPanel → **Setup Python App** → open the application, then copy the command
shown at the top of the page and run it in **Terminal**:

```
source /home/altriaca/virtualenv/crm.altriacallcenter.com/3.11/bin/activate && cd /home/altriaca/crm.altriacallcenter.com
```

---

## Step 3 — Install dependencies

```
pip install -r requirements.txt
```

Or use the **Run Pip Install** button on the Setup Python App page.

> `requirements.txt` in this package is saved as UTF-8. The previous copy was
> UTF-16, which some versions of pip fail to read. No package versions changed.

---

## Step 4 — Run database migrations

```
python manage.py migrate --settings=altria_crm.settings_production
```

Expected output includes:

```
Applying core.0008_systemconfig_autoreply_confidence_and_more... OK
Applying ai_services.0001_initial... OK
```

Alternative: cPanel → Setup Python App → **Execute python script**, enter
`manage.py migrate` and click **Run Script**. (`DJANGO_SETTINGS_MODULE` is
already set to `altria_crm.settings_production` in your environment variables,
so the `--settings` flag is optional there.)

---

## Step 5 — Collect static files

```
python manage.py collectstatic --noinput --settings=altria_crm.settings_production
```

---

## Step 6 — Restart the application

cPanel → **Setup Python App** → **RESTART**.

---

## Step 7 — Verify

1. Open <https://crm.altriacallcenter.com/> — the sign-in page should load.
2. Sign in as an administrator.
3. **Hard-refresh your browser** (`Ctrl` + `F5`) so the new frontend loads. The
   JavaScript file is renamed each build, so a normal refresh may serve the old
   cached copy.
4. Check the following:

| Check | Where | Expect |
|---|---|---|
| New frontend is live | Client portal dashboard | The four stat cards are clickable |
| SLA editing works | SLA | Each policy row has **Edit** and **Delete** |
| User deletion works | Users & Audit → Edit | A **Delete User** button appears |
| AI settings appear | Integrations → AI Settings | An **AI Auto-Reply to Emails** card is shown |
| Nothing is broken | Tickets | Existing tickets still open and display normally |

If the page loads but looks unchanged, it is almost always browser cache —
hard-refresh again or try a private window.

---

## Step 8 — Email fetching (confirm your cron job)

Email-to-ticket conversion runs from cron, not from the web app. Confirm the
job still exists in cPanel → **Cron Jobs**. A typical entry running every
minute:

```
/home/altriaca/virtualenv/crm.altriacallcenter.com/3.11/bin/python /home/altriaca/crm.altriacallcenter.com/manage.py fetch_emails >/dev/null 2>&1
```

`DJANGO_SETTINGS_MODULE` is supplied by the application environment. If your
cron job does not inherit it, prefix the command with
`DJANGO_SETTINGS_MODULE=altria_crm.settings_production`.

The same cron job now also sends any AI auto-replies that are due, so no extra
job is required.

---

## Step 9 — Turn on the AI Auto-Reply Agent (optional)

The agent is **off by default**. Nothing is sent to customers until you enable it.

1. Sign in as an administrator → **Integrations** → **AI Settings**.
2. Turn on **Enable AI Assistant**, choose your provider, paste the API key, **Save**.
3. Click **Test Connection**.
4. Turn on **AI Auto-Reply to Emails**.
5. **Leave "Draft only" switched ON to begin with.**

In Draft-only mode every AI reply is saved on the ticket as an internal note for
an agent to review. Read a few days of drafts before switching Draft-only off.
Once it is off, replies are sent automatically 5–10 minutes after an email
arrives, from the assigned agent's name, with the mailbox name as the sender.

> The API key can be stored in the admin UI — you do not need to add an
> `ANTHROPIC_API_KEY` environment variable in cPanel.

---

## Rolling back

1. Extract your pre-deployment backup over `/home/altriaca/crm.altriacallcenter.com/`.
2. Restart the application.

The two new migrations only **add** a table and two columns, so older code runs
against the migrated database without error. Reversing the migrations is not
required for a rollback.

---

## Troubleshooting

| Symptom | Cause and fix |
|---|---|
| 500 error after deploy | Check `stderr.log` in the application root. Most often a missed `pip install` (step 3) or a skipped migration (step 4). |
| `no such column: core_systemconfig.autoreply_enabled` | Migrations did not run. Repeat step 4. |
| `ModuleNotFoundError: ai_services.auto_reply` | Extraction was incomplete. Re-extract and confirm `ai_services/auto_reply.py` and `ai_services/reply_playbook.py` exist. |
| Interface looks unchanged | Browser cache. Hard-refresh with `Ctrl` + `F5`. |
| Emails are not becoming tickets | The cron job in step 8 is missing or failing. Run `python manage.py fetch_emails` manually to see the error. |
| AI never replies | Check: AI enabled with a valid key, Auto-Reply on, Draft-only off, and the ticket has an assigned agent. Automated senders (no-reply, DMARC, newsletters) are never replied to by design. |
| Client created without SLA policies | Check the client has a tier set. Policies are generated on creation only — add them manually under SLA for clients created earlier. |

---

## Files intentionally excluded from this package

These are server-owned and must never be overwritten by a deployment:

- `.env.production`
- `pfsense_integration/.env`
- `vicidial_integration/.env`
- `media/` (uploads)
- `stderr.log`, `tmp/`

Local development files (`.venv`, `db.sqlite3`, `.env`, seed scripts,
`__pycache__`) are also excluded.
