Metadata-Version: 2.4
Name: django-support-emails
Version: 0.1.0
Summary: Django app for support contact forms: collects visitor email, name, message, sends email to admins and generates support ticket numbers.
Author-email: Chilufya Mukuka <mukukachilu@gmail.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/chilusoft/django-support-emails
Project-URL: Repository, https://github.com/chilusoft/django-support-emails
Keywords: django,support,email,contact-form,ticket
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=4.2
Requires-Dist: djangorestframework>=3.14
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-django>=4.5; extra == "dev"
Dynamic: license-file

# django-support-emails

**django-support-emails** is a reusable Django app that adds a support/contact system to your site. Visitors submit requests through your front end; the app stores each request, assigns a unique ticket number, and sends a confirmation email to the visitor. Your team can list tickets, reply from the admin or via the API, and replies are stored and emailed back to the original sender. The app plugs into your existing Django project and uses your database and email settings.

```
                    +------------------+
                    |     VISITOR      |
                    +--------+---------+
                             |
         POST (email, subject, message)
                             |
                             v
    +------------------------+------------------------+
    |              Your Django project                 |
    |  +------------------+      +------------------+  |
    |  |  django-support-  |      |    Database      |  |
    |  |  emails (API)     |----->|  SupportEmail    |  |
    |  |                  |      |  SupportEmail-   |  |
    |  |  1. Store ticket |      |  Response        |  |
    |  |  2. Assign SUP-*  |      +------------------+  |
    |  |  3. Send confirm  |             ^            |
    |  +--------+---------+              |            |
    |           |                        |            |
    |           | confirmation email    | read/write |
    +-----------|------------------------|------------+
                |                        |
                v                        |
         +-------------+         +-------+--------+
         |  Visitor    |         |    ADMIN      |
         |  (inbox)    |         |  (Django     |
         +-------------+         |   admin/API) |
                                 |              |
                    POST reply   |  List tickets |
                    ------------>|  Send reply   |
                                 +------+-------+
                                        |
                                        | reply stored & emailed
                                        v
                                 +-------------+
                                 |  Visitor    |
                                 |  (inbox)    |
                                 +-------------+
```

## Features

- **Support contact form**: Collect sender email, subject, and message (first/last name are model fields; the default API stores only email, subject, message).
- **Automatic confirmation email**: Sends a reply to the visitor with their support ticket number.
- **Admin responses**: Store and send admin replies linked to the original ticket; the reply is emailed to the original sender.
- **REST API**: List tickets, submit a support request, submit an admin response (Django REST Framework).
- **Django Admin**: Admin registration for `SupportEmail` and `SupportEmailResponse` for viewing and managing tickets.

## Requirements

- Python 3.8+
- Django 4.2+
- djangorestframework 3.14+

## Installation

Install from PyPI:

```bash
pip install django-support-emails
```

Or install in development mode from the project root:

```bash
pip install -e .
```

## Configuration

### 1. Add the app and REST framework

In your project's `settings.py`, add to `INSTALLED_APPS`:

```python
INSTALLED_APPS = [
    # ...
    'rest_framework',
    'django_support_emails',
]
```

Optional: to paginate list endpoints (e.g. 10 per page), add:

```python
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 10,
}
```

### 2. Configure email

Outgoing emails (confirmation to visitor, admin reply to visitor) use Django's email backend. In `settings.py`, for example for Gmail:

```python
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_HOST_USER = "your-email@gmail.com"
EMAIL_HOST_PASSWORD = "your-app-password"  # use an app password, not your normal password
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = "noreply@yourdomain.com"  # optional; default is EMAIL_HOST_USER
```

Use a real SMTP backend in production; in development you can use `django.core.mail.backends.console.Backend` to print emails to the console.

### 3. Database

The app does not define any database settings. It uses your project's `DATABASES` configuration from `settings.py`. Add the app to `INSTALLED_APPS`, run migrations, and all support email data is stored in your existing database.

### 4. Run migrations

```bash
python manage.py migrate
```

### 5. Include the app URLs

In your project's `urls.py`:

```python
from django.urls import path, include

urlpatterns = [
    # ...
    path('support/api/v1/', include('django_support_emails.urls')),
]
```

The base path (`support/api/v1/`) is up to you; the app provides the subpaths below.

## API Endpoints

All endpoints return JSON. The list endpoints use DRF's pagination if you configured `REST_FRAMEWORK` (e.g. `limit` and `offset` query parameters).

| Method | Path | Description |
|--------|------|-------------|
| GET | `.../support-email/get/` | List all support emails (tickets). |
| GET | `.../support-email-response/get/` | List all support email responses. |
| POST | `.../send-support-email/` | Submit a new support request. |
| POST | `.../send-support-email-response/` | Submit an admin response to a ticket. |

### Submit a support request

**POST** `.../send-support-email/`

Request body (JSON):

- `sender_email` (string, required)
- `subject` (string, required)
- `message` (string, required)
- `support_ticket` (string, optional): custom ticket number (e.g. `EXT-12345`). If omitted, a unique number is generated (e.g. `SUP-123456`). If provided, it must be unique or the request returns 400.

Example:

```bash
curl -X POST http://localhost:8000/support/api/v1/send-support-email/ \
  -H "Content-Type: application/json" \
  -d '{"sender_email": "visitor@example.com", "subject": "Help needed", "message": "I need help with..."}'
```

With optional custom ticket number:

```bash
curl -X POST http://localhost:8000/support/api/v1/send-support-email/ \
  -H "Content-Type: application/json" \
  -d '{"sender_email": "visitor@example.com", "subject": "Help", "message": "My message.", "support_ticket": "EXT-999"}'
```

Success: `201 Created` with `{"status": "success"}`.  
The visitor receives a confirmation email with a ticket number (e.g. `SUP-123456`). The ticket is stored in the database.

Error: `400 Bad Request` with `{"status": "failed", "error": "..."}`.

### Submit an admin response

**POST** `.../send-support-email-response/`

Request body (JSON):

- `support_email` (object, required): must contain `id` (the primary key of the `SupportEmail`).
- `message` (string, required): the reply text.

Example:

```bash
curl -X POST http://localhost:8000/support/api/v1/send-support-email-response/ \
  -H "Content-Type: application/json" \
  -d '{"support_email": {"id": 1}, "message": "Thanks for reaching out. We will look into it."}'
```

Success: `201 Created` with `{"status": "success"}`.  
The original sender receives an email with the subject `{ticket_number} : {original_subject}` and the reply body. The response is stored and linked to the ticket.

Error: `400 Bad Request` with `{"status": "failed", "error": "..."}`.

### List support emails

**GET** `.../support-email/get/`

Returns a paginated list of support emails (tickets). Each item includes: `id`, `sender_email`, `support_ticket`, `subject`, `message`, `first_name`, `last_name`, `date_created`, `date_modified`.

### List support email responses

**GET** `.../support-email-response/get/`

Returns a paginated list of responses. Each item includes the nested `support_email` object and `message`, `date_created`, `date_modified`.

## Using from a frontend

Send requests with `Content-Type: application/json`. The POST endpoints do not require CSRF when called from another origin (they use `@csrf_exempt`). For same-origin form submissions you can use Django's CSRF token or keep calling the API via JavaScript with the appropriate headers.

Example (JavaScript):

```javascript
const response = await fetch('/support/api/v1/send-support-email/', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    sender_email: 'visitor@example.com',
    subject: 'Help',
    message: 'My message here.',
  }),
});
const data = await response.json();  // { status: 'success' } or { status: 'failed', error: '...' }
```

## Django Admin

Register the app in `INSTALLED_APPS` (as above); the package already registers `SupportEmail` and `SupportEmailResponse` in the admin. In the admin you can:

- View and search support emails (ticket number, sender, subject, date).
- View support email responses and their linked ticket.

You can use the list API to build your own dashboard and the admin to manage or inspect tickets.

## Models

- **SupportEmail**: `sender_email`, `support_ticket`, `subject`, `message`, `first_name`, `last_name`, `date_created`, `date_modified`.
- **SupportEmailResponse**: `support_email` (FK to SupportEmail), `message`, `date_created`, `date_modified`.

## Publishing to Test PyPI

Use a Test PyPI API token via environment variables (never commit the token):

```bash
# Optional: put these in .env (already in .gitignore)
export TWINE_USERNAME=__token__
export TWINE_PASSWORD=your-test-pypi-token-here
export TWINE_REPOSITORY_URL=https://test.pypi.org/legacy/

# Build and publish
python -m build
twine upload dist/*
```

Install from Test PyPI: `pip install -i https://test.pypi.org/simple/ django-support-emails`

## License

Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for details.
