# Mourasel Platform

A self-hosted, Jira + Xray–style **QA and defect-management platform** — projects, issues with priority/severity/attachments, full test management (cases → sets → plans → cycles → execution), role-based access, invitations, audit history, an executive dashboard, and CSV reporting.

Built to be **light and cross-platform**: Node.js + SQLite, no build step, no external services required. Runs the same on **Windows Server** and **Linux**.

---

## 1. Requirements

- **Node.js 18 or newer** (LTS recommended). Check with `node --version`.
  - Windows: install from https://nodejs.org (the MSI installer includes everything).
  - Linux: install via your package manager or from nodejs.org.
- That's it. The database is a single SQLite file created automatically.

## 2. Install & run

Open a terminal (Windows: PowerShell or Command Prompt) in the project folder:

```bash
# 1. Install dependencies (downloads the correct SQLite binary for your OS)
npm install

# 2. Create your configuration file
#    Windows (PowerShell):   Copy-Item .env.example .env
#    Windows (CMD):          copy .env.example .env
#    Linux / macOS:          cp .env.example .env

# 3. Seed the database (creates the superuser + demo data)
npm run seed

# 4. Start the server
npm start
```

Then open **http://localhost:4000**.

> **Tip:** run `npm install` on the machine that will host the app. The SQLite driver ships as a native binary, and `npm install` fetches the right one for Windows or Linux automatically. Don't copy `node_modules` between operating systems.

### Sign in

| Account | Email | Password |
|---|---|---|
| **Superuser** | `wrimawi@nabeh.sa` | `ChangeMe123!` (from `.env`) |
| Demo QA Manager | `lina.qa@nabeh.sa` | `Passw0rd!` |
| Demo QA Engineer | `sara.qa@nabeh.sa` | `Passw0rd!` |
| Demo Project Manager | `tariq.pm@nabeh.sa` | `Passw0rd!` |

**Change the superuser password** in `.env` before real use, then re-run `npm run seed`.

### Useful commands

```bash
npm start        # start the server
npm run dev      # start with auto-restart on file changes
npm run seed     # create superuser + demo data (safe to re-run; skips if data exists)
npm run reset    # WIPE all data and re-seed from scratch
```

---

## 3. What's included

### Access & people
- **Roles:** Super Admin, QA Manager, QA Lead, QA Engineer, Development Manager, Dev Team Lead, Developer, Project Manager, Business Analyst.
- **Invitation-based onboarding.** The superuser invites a person (first name, last name, email, role, **direct manager/team lead**). An invitation email is **sent from the inviting superadmin's own email address**; the invitee clicks the link and sets their own password.
- **Reporting hierarchy.** Every non-top-level employee must have a direct manager on the system.
- **Enable/disable accounts**, resend invitations, and a full team directory with org relationships.

### Projects
- Superuser **or** Project Managers create projects (key, name, description, **start/end dates, SLA**).
- Assign any resource to any number of projects, each with a project role (QA / Developer / BA / PM / Viewer).
- **Access is scoped:** users only see projects they're assigned to (superuser sees everything).
- Progress bars on the project page, test plans and test cycles.

### Issues / defects (Jira-style, Xray-enhanced)
- Priority (highest→lowest), severity (critical→trivial), type, category, labels, environment, steps/expected/actual.
- **Attachments of any file type** on issues and on comments (screenshots, logs, video, docs…).
- **Claim-before-act rule:** nobody can change a ticket without assigning it to themselves first. Assign-to-me is one click; the server enforces it.
- **Xray-style advanced filtering:** multi-select status/priority/severity/type, project, assignee (me/unassigned), category, free-text search, SLA-breached, date ranges, sorting and pagination.
- Every change is recorded in the **History** tab (who did what, when, old → new values).
- Comments notify and email everyone related to the issue, **from the acting user's email**.

### Test management (Xray-style)
- **Test cases** (with structured steps), **test sets**, **test plans**, and **test cycles**.
- Execute tests in a cycle with statuses **To Do, Executing, Pass, Fail, Blocked, Pending**.
- Execution board with a live progress bar and pass-rate.
- **Fail → raise defect** in one step: a linked defect is created and the project lead is emailed.
- Claim-before-act also applies to test execution.

### Dashboard & reporting
- Executive dashboard: total logged, active backlog, in-progress, ready-for-QA, closed, on-hold, **SLA breached**; a **severity × status matrix**, category donut, test-execution snapshot, live QA hotspots, and per-category summary.
- Scope the dashboard to all projects or a single project.
- **Report builder** with full filter freedom → **export CSV** (opens in Excel) containing defect ID, project, QA reporter, developer/assignee, priority, severity, status, SLA, dates and more — across all active projects or any filtered subset.

### Notifications & email
- In-app notifications for assignments, status changes and comments.
- Ready-to-use HTML **email templates**: invitation, password reset, defect assigned, status changed, new comment, project assignment, test-failure/defect-raised.
- Emails are sent **from the logged-in user who performed the action** (their address as sender/reply-to).

---

## 4. Email (SMTP) setup

Email works out of the box **without** SMTP: every outgoing message is written to the **`/outbox`** folder as an `.html` file (with the intended From/To/Subject in a comment at the top). This keeps the app fully runnable for demos and internal networks.

### Per-domain SMTP accounts

The app can send through **more than one mailbox**. Which account sends a given email is chosen automatically by the **domain of the logged-in user performing the action** — someone signed in as `name@nabeh.sa` sends through the `nabeh.sa` profile, someone signed in as `name@master-works.sa` sends through the `master-works.sa` profile. Emails triggered with no acting user (e.g. a password-reset request, sent before the user is signed in) use the **recipient's** domain instead. Any domain that doesn't match a profile falls back to the legacy single `SMTP_*` account, or to `/outbox` if that isn't set either.

Fill these in `.env` and restart:

```
SMTP_NABEH_HOST=smtp-mail.outlook.com
SMTP_NABEH_PORT=587
SMTP_NABEH_SECURE=false
SMTP_NABEH_USER=your-nabeh-mailbox@nabeh.sa
SMTP_NABEH_PASS=your-app-password

SMTP_MASTERWORKS_HOST=smtp-mail.outlook.com
SMTP_MASTERWORKS_PORT=587
SMTP_MASTERWORKS_SECURE=false
SMTP_MASTERWORKS_USER=your-mailbox@master-works.sa
SMTP_MASTERWORKS_PASS=your-app-password
```

To add another domain, add a `smtpProfile('PREFIX', 'yourdomain.com')` entry in `src/config.js` and the matching `SMTP_PREFIX_*` vars in `.env`.

### Test a mailbox before wiring it into the app

```bash
npm run test-smtp nabeh.sa
npm run test-smtp master-works.sa
```

This connects and authenticates only — it never touches `/outbox` or sends real mail unless you add `-- --send you@yourdomain.com` (the `--` is required so npm passes the flag through). It's the fastest way to find out whether a mailbox's credentials actually work.

### Microsoft 365 with Security Defaults on (error 5.7.139) — use Graph instead

If a send fails with:

```
535 5.7.139 Authentication unsuccessful, user is locked by your organization's security defaults policy
```

…the password is not the problem. The tenant has **Security Defaults** (or an equivalent Conditional Access policy) enabled in Microsoft Entra ID, which blocks legacy authentication — and username+password SMTP AUTH is legacy authentication. It will keep failing no matter how many times the password is reset.

You have two ways out. **Either** re-enable username+password SMTP in the tenant (below), **or** switch that profile to Microsoft Graph (further down).

#### Option A — keep username + password SMTP

Everything in this app already works this way; the change is entirely on the Microsoft side, and needs a tenant administrator:

1. **Turn off Security Defaults.** Entra admin center → *Identity → Overview → Properties → Manage security defaults* → **Disabled**.
2. **Allow SMTP AUTH tenant-wide** (it may also be off at the org level):
   ```powershell
   Connect-ExchangeOnline
   Set-TransportConfig -SmtpClientAuthenticationDisabled $false
   ```
3. **Allow it for the specific mailbox:**
   ```powershell
   Set-CASMailbox -Identity support@yourdomain.com -SmtpClientAuthenticationDisabled $false
   ```
   (Or: Microsoft 365 admin center → *Users → Active users →* the user *→ Mail → Manage email apps →* tick **Authenticated SMTP**.)
4. Allow up to an hour for the change to propagate, then **Settings → the profile → Send test email**.

Settings that work for Microsoft 365: host `smtp.office365.com` (or `smtp-mail.outlook.com` — both reach the same backend), port `587`, SSL **off**, Require TLS **on**, username = the full mailbox address.

Two things to weigh before taking this route:

- **Disabling Security Defaults removes enforced MFA for every account in the tenant**, not just this mailbox. If you have Entra ID P1/P2, prefer replacing it with a Conditional Access policy that keeps MFA everywhere else and carves out only this mailbox.
- **Microsoft is retiring SMTP basic auth for client submission.** This route may already be unavailable in your tenant, and may stop working later even if you enable it today.
- If the sending account itself has MFA enforced, a normal password will not authenticate regardless of the above.

> **Prefer not to touch tenant security?** Any third-party SMTP relay — Amazon SES, SendGrid, Mailgun, Brevo, Postmark — is also plain username+password SMTP and needs **no** tenant changes and **no** code changes: just put its host and API key into the same Settings form. You'll want SPF/DKIM DNS records so mail still passes authentication as your domain.

#### Option B — Microsoft Graph

The supported fix is to send through the **Microsoft Graph API**, which authenticates as a registered application rather than as a legacy mail client. It needs no tenant security downgrade and is unaffected by the retirement of SMTP basic auth. Set it up once:

1. **Entra admin center → App registrations → New registration.** Name it (e.g. "Mourasel Platform mail"), single tenant, no redirect URI needed.
2. On the new app's **Overview**, copy the **Directory (tenant) ID** and **Application (client) ID**.
3. **Certificates & secrets → New client secret.** Copy the secret **Value** immediately — it is only shown once. Note its expiry; mail stops when it lapses.
4. **API permissions → Add a permission → Microsoft Graph → _Application_ permissions → `Mail.Send`.** (Application, *not* Delegated — there is no signed-in user when a notification fires.) Then **Grant admin consent**, and confirm the row shows a green "Granted" tick.
5. In the app: **Settings → the SMTP profile → Authentication: "Microsoft Graph (modern auth)"**, paste the three values, set **Username / sending mailbox** to a real licensed mailbox in the tenant, Save, then **Send test email**.

`Mail.Send` as an application permission lets the app send as *any* mailbox in the tenant. To restrict it to just the one it should use, apply an [application access policy](https://learn.microsoft.com/en-us/graph/auth-limit-mailbox-access) in Exchange Online.

Everything else is unchanged: which profile sends a given email is still chosen by the acting user's domain, replies still route via Reply-To, and a failure still lands the message in `/outbox` with the reason annotated.

> **Microsoft 365 / Outlook.com note:** if a mailbox's SMTP settings page lists **Authentication Method: OAuth2/Modern Auth** (not "Basic"), the tenant may have disabled username+password SMTP AUTH entirely — in which case `npm run test-smtp` will fail with an authentication error even with a correct app password. That means the mailbox needs full OAuth2 (an Azure AD app registration) or the Microsoft Graph `sendMail` API instead of SMTP — a bigger setup than swapping credentials, so check this first.

> **Note on "send from the user's address":** the app sets the message **From** and **Reply-To** to the acting user's email so recipients see who performed the action, even though the SMTP profile authenticates as one shared mailbox per domain. Many providers require the envelope sender to match the authenticated account (or a mailbox it has "Send As" rights to) and may rewrite the visible From. Reply-To will still route replies to the right person regardless.

---

## 5. Configuration reference (`.env`)

| Key | Meaning |
|---|---|
| `PORT` | Port to listen on (default 4000). |
| `JWT_SECRET` | **Change this** to a long random string; secures login tokens. |
| `APP_URL` | Public URL used to build invitation/reset links in emails. |
| `SUPERUSER_EMAIL/PASSWORD/FIRST_NAME/LAST_NAME` | The bootstrap superuser (created on first run). |
| `MAX_UPLOAD_MB` | Max size per uploaded file (default 50). All extensions allowed. |
| `SMTP_*`, `MAIL_FROM` | Email delivery (see above). |

---

## 6. Running in production

- Set a strong `JWT_SECRET` and change the superuser password.
- Set `APP_URL` to the real address (e.g. `https://qa.yourcompany.com`) so email links work.
- Put the app behind a reverse proxy (Nginx / IIS) for HTTPS.
- Keep it running with a process manager:
  - **Linux:** `pm2 start server.js --name qa-platform` (or a `systemd` unit).
  - **Windows:** run as a service with `nssm`, or use `pm2`.
- **Backups:** everything lives in the `data/` folder (SQLite) and `uploads/` (attachments). Back up both.

---

## 7. Project layout

```
qa-platform/
├── server.js              # Express entry point
├── src/
│   ├── config.js          # env-based configuration
│   ├── db.js              # SQLite schema (auto-created)
│   ├── auth.js            # roles, JWT, password hashing, access control
│   ├── email.js           # nodemailer + HTML templates + /outbox fallback
│   ├── helpers.js         # audit log, notifications, keys, CSV, SLA
│   ├── seed.js            # superuser + demo data
│   └── routes/            # auth, users, projects, defects, tests, reports, dashboard, interactions
├── public/                # frontend (vanilla JS SPA, no build step)
│   ├── index.html
│   ├── css/styles.css
│   └── js/                # core + view modules
├── data/                  # SQLite database (created at runtime) — back this up
├── uploads/               # attachments (created at runtime) — back this up
├── outbox/                # captured emails when SMTP is off
└── .env                   # your configuration (copy from .env.example)
```

---

## 8. Notes & scope

This is a focused, production-shaped implementation of the core Jira/Xray workflow — it is not a 1:1 reimplementation of every Jira feature. The architecture is clean and easy to extend (add fields, statuses, workflows, or integrations by editing the relevant route + view). Clear, human-readable error messages are returned throughout the API and surfaced in the UI.

If `npm install` fails on the SQLite driver, ensure you're on Node 18+ and have a normal internet connection so the prebuilt binary can download; on minimal Linux images you may need basic build tools (`apt-get install -y python3 make g++`) as a fallback.
