tungsten-tickets 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .pytest_cache/
8
+ frontend/node_modules/
9
+ storage/
10
+ *.db
11
+ *.sqlite3
12
+ .DS_Store
13
+ .claude/worktrees/
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.5
2
+ Name: tungsten-tickets
3
+ Version: 0.1.0
4
+ Summary: Help desk plugin for Tungsten: tickets, replies, internal notes, SLA and a customer support page.
5
+ Project-URL: Homepage, https://tungsten.prisminfoways.com/
6
+ Project-URL: Documentation, https://tungsten.prisminfoways.com/docs/tickets.html
7
+ Project-URL: Repository, https://github.com/Prism-Infoways/Tungsten
8
+ Author: Prism Infoways
9
+ License: MIT
10
+ Keywords: admin,fastapi,helpdesk,support,tickets,tungsten,tungsten-admin
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: tungsten-admin>=0.1.4
13
+ Description-Content-Type: text/markdown
14
+
15
+ # tungsten-tickets
16
+
17
+ Help desk (ticketing) plugin for [Tungsten](https://tungsten.prisminfoways.com/), the admin panel for FastAPI.
18
+
19
+ ## What you get
20
+
21
+ - **Tickets** with a number (`TCK-00012`), status, priority, category, agent, tags and the customer's name, email and phone.
22
+ - A **conversation** on each ticket: replies to the customer, the customer's messages, **internal notes** only your team sees, and a log of status and agent changes.
23
+ - **Reply** box with **saved replies** (canned answers), file attachments and "then set status".
24
+ - **SLA**: each priority has hours to resolve (urgent 4, high 8, normal 24, low 72). Late tickets show in red and in the *Overdue* tab.
25
+ - Tabs for *Open*, *My tickets*, *Unassigned*, *Overdue*, *Waiting on customer* and *Resolved*; filters; search; export.
26
+ - Bulk actions: assign, resolve, close, delete.
27
+ - **Categories** (Billing, Bug...) that can send new tickets to one agent.
28
+ - Dashboard numbers: open, unassigned, overdue, resolved this week.
29
+ - **Support page** for customers at `<panel>/support`: raise a ticket, then follow and answer it from a private link. No login needed.
30
+ - **Emails** to the customer when the ticket is received, on every reply and when resolved. New tickets and customer replies go to the agent's notification bell.
31
+ - Optional **API**: POST tickets to `<panel>/api/tickets`.
32
+ - Hooks so other plugins (WhatsApp, Slack...) can act on new tickets, replies and status changes.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install tungsten-tickets
38
+ ```
39
+
40
+ ```python
41
+ from tungsten_tickets import TicketsPlugin
42
+
43
+ panel = Panel(..., app_url="https://admin.example.com", auth=Auth(User, mailer=send_mail))
44
+ panel.plugin(TicketsPlugin())
45
+ panel.create_tables(engine) # creates the ticket tables too
46
+ ```
47
+
48
+ `mailer` is your function `send_mail(to, subject, body)`. `app_url` makes the links in emails full links.
49
+
50
+ ### Options
51
+
52
+ ```python
53
+ TicketsPlugin(
54
+ statuses={"open": ("Open", "info"), ...}, # key: (label, color). "resolved" and "closed" mean done
55
+ priorities={"low": ("Low", "gray"), ...},
56
+ sla_hours={"urgent": 4, "high": 8, "normal": 24, "low": 72}, # None for no due time
57
+ number_prefix="TCK-",
58
+ portal=True, portal_path="support", # the public support page
59
+ api_token="long-secret", # turns on POST <panel>/api/tickets
60
+ email_requester=True, # emails to the customer
61
+ notify_agents=True, # bell notifications for agents
62
+ mailer=None, # defaults to Auth(mailer=...)
63
+ navigation_group="Help desk",
64
+ )
65
+ ```
66
+
67
+ ## Open tickets from code
68
+
69
+ ```python
70
+ from tungsten_tickets import add_reply, create_ticket
71
+
72
+ ticket = create_ticket(db, subject="Order late", description="Where is order 12?",
73
+ requester_email="amit@example.com", priority="high", source="email")
74
+ add_reply(db, ticket, "It ships today.", user_id="1", status="waiting")
75
+ db.commit()
76
+ ```
77
+
78
+ ## API
79
+
80
+ ```bash
81
+ curl -X POST https://admin.example.com/admin/api/tickets \
82
+ -H "X-Tickets-Token: long-secret" -H "Content-Type: application/json" \
83
+ -d '{"subject": "Order late", "message": "Where is order 12?", "name": "Amit", "email": "amit@example.com"}'
84
+ ```
85
+
86
+ Answer: `{"id": 1, "number": "TCK-00001", "url": "<customer link>"}`. Send `external_id` to skip duplicates.
87
+
88
+ ## Hooks
89
+
90
+ ```python
91
+ desk = panel.get_plugin("tickets")
92
+ desk.on_ticket_created("whatsapp", lambda db, ticket: ...)
93
+ desk.on_ticket_replied("whatsapp", lambda db, ticket, reply: ...)
94
+ desk.on_status_changed("slack", lambda db, ticket, old_status: ...)
95
+ ```
96
+
97
+ ## Try it
98
+
99
+ ```bash
100
+ pip install -e . -e plugins/tickets uvicorn
101
+ uvicorn plugins.tickets.example:app --reload
102
+ ```
103
+
104
+ Sign in at http://127.0.0.1:8000/admin with admin@example.com / password. The support page is http://127.0.0.1:8000/admin/support.
105
+
106
+ ## More Tungsten plugins
107
+
108
+ | Package | What it adds | Docs |
109
+ | --- | --- | --- |
110
+ | [`tungsten-leads`](https://pypi.org/project/tungsten-leads/) | Leads list, stages, timeline and your own lead form fields | [README](https://github.com/Prism-Infoways/Tungsten/tree/claude/tungsten-admin-panel/plugins/leads) |
111
+ | [`tungsten-meta-leads`](https://pypi.org/project/tungsten-meta-leads/) | Facebook and Instagram lead form leads, with one-click setup | [Guide](https://tungsten.prisminfoways.com/docs/facebook-leads.html) |
112
+ | [`tungsten-whatsapp`](https://pypi.org/project/tungsten-whatsapp/) | WhatsApp for leads: click-to-chat, Cloud API or WhatsApp Web | [Guide](https://tungsten.prisminfoways.com/docs/whatsapp.html) |
113
+ | [`tungsten-mcp`](https://pypi.org/project/tungsten-mcp/) | MCP server, so AI assistants like Claude can read and change your data | [Guide](https://tungsten.prisminfoways.com/docs/mcp.html) |
114
+ | [`tungsten-blog`](https://pypi.org/project/tungsten-blog/) | Blog built for SEO, GEO and AEO, with a live score, sitemap and llms.txt | [Guide](https://tungsten.prisminfoways.com/docs/blog.html) |
115
+ | [`tungsten-seo-audit`](https://pypi.org/project/tungsten-seo-audit/) | SEO audit of your website: score, fix tips, AI search checks, history | [Guide](https://tungsten.prisminfoways.com/docs/seo-audit.html) |
116
+ | [`tungsten-security-audit`](https://pypi.org/project/tungsten-security-audit/) | Security audit with a score and fix tips, plus a login log with lockout | [Guide](https://tungsten.prisminfoways.com/docs/security-audit.html) |
117
+
118
+ Core package: [`tungsten-admin`](https://pypi.org/project/tungsten-admin/). Website and docs: https://tungsten.prisminfoways.com/
@@ -0,0 +1,104 @@
1
+ # tungsten-tickets
2
+
3
+ Help desk (ticketing) plugin for [Tungsten](https://tungsten.prisminfoways.com/), the admin panel for FastAPI.
4
+
5
+ ## What you get
6
+
7
+ - **Tickets** with a number (`TCK-00012`), status, priority, category, agent, tags and the customer's name, email and phone.
8
+ - A **conversation** on each ticket: replies to the customer, the customer's messages, **internal notes** only your team sees, and a log of status and agent changes.
9
+ - **Reply** box with **saved replies** (canned answers), file attachments and "then set status".
10
+ - **SLA**: each priority has hours to resolve (urgent 4, high 8, normal 24, low 72). Late tickets show in red and in the *Overdue* tab.
11
+ - Tabs for *Open*, *My tickets*, *Unassigned*, *Overdue*, *Waiting on customer* and *Resolved*; filters; search; export.
12
+ - Bulk actions: assign, resolve, close, delete.
13
+ - **Categories** (Billing, Bug...) that can send new tickets to one agent.
14
+ - Dashboard numbers: open, unassigned, overdue, resolved this week.
15
+ - **Support page** for customers at `<panel>/support`: raise a ticket, then follow and answer it from a private link. No login needed.
16
+ - **Emails** to the customer when the ticket is received, on every reply and when resolved. New tickets and customer replies go to the agent's notification bell.
17
+ - Optional **API**: POST tickets to `<panel>/api/tickets`.
18
+ - Hooks so other plugins (WhatsApp, Slack...) can act on new tickets, replies and status changes.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install tungsten-tickets
24
+ ```
25
+
26
+ ```python
27
+ from tungsten_tickets import TicketsPlugin
28
+
29
+ panel = Panel(..., app_url="https://admin.example.com", auth=Auth(User, mailer=send_mail))
30
+ panel.plugin(TicketsPlugin())
31
+ panel.create_tables(engine) # creates the ticket tables too
32
+ ```
33
+
34
+ `mailer` is your function `send_mail(to, subject, body)`. `app_url` makes the links in emails full links.
35
+
36
+ ### Options
37
+
38
+ ```python
39
+ TicketsPlugin(
40
+ statuses={"open": ("Open", "info"), ...}, # key: (label, color). "resolved" and "closed" mean done
41
+ priorities={"low": ("Low", "gray"), ...},
42
+ sla_hours={"urgent": 4, "high": 8, "normal": 24, "low": 72}, # None for no due time
43
+ number_prefix="TCK-",
44
+ portal=True, portal_path="support", # the public support page
45
+ api_token="long-secret", # turns on POST <panel>/api/tickets
46
+ email_requester=True, # emails to the customer
47
+ notify_agents=True, # bell notifications for agents
48
+ mailer=None, # defaults to Auth(mailer=...)
49
+ navigation_group="Help desk",
50
+ )
51
+ ```
52
+
53
+ ## Open tickets from code
54
+
55
+ ```python
56
+ from tungsten_tickets import add_reply, create_ticket
57
+
58
+ ticket = create_ticket(db, subject="Order late", description="Where is order 12?",
59
+ requester_email="amit@example.com", priority="high", source="email")
60
+ add_reply(db, ticket, "It ships today.", user_id="1", status="waiting")
61
+ db.commit()
62
+ ```
63
+
64
+ ## API
65
+
66
+ ```bash
67
+ curl -X POST https://admin.example.com/admin/api/tickets \
68
+ -H "X-Tickets-Token: long-secret" -H "Content-Type: application/json" \
69
+ -d '{"subject": "Order late", "message": "Where is order 12?", "name": "Amit", "email": "amit@example.com"}'
70
+ ```
71
+
72
+ Answer: `{"id": 1, "number": "TCK-00001", "url": "<customer link>"}`. Send `external_id` to skip duplicates.
73
+
74
+ ## Hooks
75
+
76
+ ```python
77
+ desk = panel.get_plugin("tickets")
78
+ desk.on_ticket_created("whatsapp", lambda db, ticket: ...)
79
+ desk.on_ticket_replied("whatsapp", lambda db, ticket, reply: ...)
80
+ desk.on_status_changed("slack", lambda db, ticket, old_status: ...)
81
+ ```
82
+
83
+ ## Try it
84
+
85
+ ```bash
86
+ pip install -e . -e plugins/tickets uvicorn
87
+ uvicorn plugins.tickets.example:app --reload
88
+ ```
89
+
90
+ Sign in at http://127.0.0.1:8000/admin with admin@example.com / password. The support page is http://127.0.0.1:8000/admin/support.
91
+
92
+ ## More Tungsten plugins
93
+
94
+ | Package | What it adds | Docs |
95
+ | --- | --- | --- |
96
+ | [`tungsten-leads`](https://pypi.org/project/tungsten-leads/) | Leads list, stages, timeline and your own lead form fields | [README](https://github.com/Prism-Infoways/Tungsten/tree/claude/tungsten-admin-panel/plugins/leads) |
97
+ | [`tungsten-meta-leads`](https://pypi.org/project/tungsten-meta-leads/) | Facebook and Instagram lead form leads, with one-click setup | [Guide](https://tungsten.prisminfoways.com/docs/facebook-leads.html) |
98
+ | [`tungsten-whatsapp`](https://pypi.org/project/tungsten-whatsapp/) | WhatsApp for leads: click-to-chat, Cloud API or WhatsApp Web | [Guide](https://tungsten.prisminfoways.com/docs/whatsapp.html) |
99
+ | [`tungsten-mcp`](https://pypi.org/project/tungsten-mcp/) | MCP server, so AI assistants like Claude can read and change your data | [Guide](https://tungsten.prisminfoways.com/docs/mcp.html) |
100
+ | [`tungsten-blog`](https://pypi.org/project/tungsten-blog/) | Blog built for SEO, GEO and AEO, with a live score, sitemap and llms.txt | [Guide](https://tungsten.prisminfoways.com/docs/blog.html) |
101
+ | [`tungsten-seo-audit`](https://pypi.org/project/tungsten-seo-audit/) | SEO audit of your website: score, fix tips, AI search checks, history | [Guide](https://tungsten.prisminfoways.com/docs/seo-audit.html) |
102
+ | [`tungsten-security-audit`](https://pypi.org/project/tungsten-security-audit/) | Security audit with a score and fix tips, plus a login log with lockout | [Guide](https://tungsten.prisminfoways.com/docs/security-audit.html) |
103
+
104
+ Core package: [`tungsten-admin`](https://pypi.org/project/tungsten-admin/). Website and docs: https://tungsten.prisminfoways.com/
@@ -0,0 +1,86 @@
1
+ """Try the tickets plugin.
2
+
3
+ pip install -e . -e plugins/tickets uvicorn
4
+ uvicorn plugins.tickets.example:app --reload (from the repo root)
5
+
6
+ Open http://127.0.0.1:8000/admin and sign in with admin@example.com / password.
7
+ The customer page is http://127.0.0.1:8000/admin/support
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import datetime as dt
13
+
14
+ from fastapi import FastAPI
15
+ from fastapi.responses import RedirectResponse
16
+ from sqlalchemy import Boolean, String, create_engine, select
17
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
18
+ from tungsten_tickets import SavedReply, TicketCategory, TicketsPlugin, add_reply, create_ticket
19
+
20
+ from tungsten import Auth, Panel, hash_password
21
+
22
+
23
+ class Base(DeclarativeBase):
24
+ pass
25
+
26
+
27
+ class User(Base):
28
+ __tablename__ = "users"
29
+
30
+ id: Mapped[int] = mapped_column(primary_key=True)
31
+ name: Mapped[str] = mapped_column(String(100))
32
+ email: Mapped[str] = mapped_column(String(200), unique=True)
33
+ password: Mapped[str] = mapped_column(String(200))
34
+ is_active: Mapped[bool] = mapped_column(Boolean, default=True)
35
+
36
+
37
+ engine = create_engine("sqlite:///tickets_demo.db")
38
+ Base.metadata.create_all(engine)
39
+ Session = sessionmaker(engine, expire_on_commit=False)
40
+
41
+ panel = Panel(path="/admin", session_factory=Session, secret_key="dev-only", auth=Auth(User),
42
+ brand_name="Tungsten Desk", colors={"primary": "indigo"}, spa=True)
43
+ panel.plugin(TicketsPlugin(api_token="demo-token"))
44
+ panel.create_tables(engine)
45
+
46
+
47
+ def seed() -> None:
48
+ with Session() as db:
49
+ if db.scalar(select(User)) is not None:
50
+ return
51
+ db.info["tungsten_panel"] = panel
52
+ db.add_all([User(name="Asha Admin", email="admin@example.com", password=hash_password("password")),
53
+ User(name="Rohit Support", email="rohit@example.com", password=hash_password("password"))])
54
+ db.add_all([TicketCategory(name="Billing", color="success", assign_to="2", sort=1),
55
+ TicketCategory(name="Technical", color="info", sort=2),
56
+ TicketCategory(name="Sales", color="purple", sort=3)])
57
+ db.add_all([SavedReply(title="Password reset", body="Please use 'Forgot password' on the login page. "
58
+ "The link in the email works for one hour."),
59
+ SavedReply(title="Refund time", body="Refunds reach your bank in 5 to 7 working days.")])
60
+ db.flush()
61
+ rows = [("Charged twice for my plan", "high", 1, "Amit Sharma"),
62
+ ("Can't log in after the update", "urgent", 2, "Priya Patel"),
63
+ ("Need a quote for 20 users", "normal", 3, "Rahul Verma"),
64
+ ("Export to Excel is slow", "low", 2, "Sneha Iyer"),
65
+ ("Invoice has the wrong GST number", "normal", 1, "Vikram Singh")]
66
+ for subject, priority, category, name in rows:
67
+ ticket = create_ticket(db, subject=subject, description=f"Hi, {subject.lower()}. Please help.",
68
+ requester_name=name, requester_email=f"{name.split()[0].lower()}@example.com",
69
+ priority=priority, category_id=category, source="portal")
70
+ if category == 1:
71
+ add_reply(db, ticket, "Sorry about that! We are checking it with the bank.", user_id="2",
72
+ status="in_progress")
73
+ add_reply(db, ticket, "Bank says the second charge is on hold.", user_id="2", internal=True)
74
+ if priority == "urgent": # show one overdue ticket
75
+ ticket.due_at = dt.datetime.now() - dt.timedelta(hours=2)
76
+ db.commit()
77
+
78
+
79
+ seed()
80
+ app = FastAPI()
81
+ panel.mount(app)
82
+
83
+
84
+ @app.get("/")
85
+ def root():
86
+ return RedirectResponse("/admin/")
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "tungsten-tickets"
7
+ version = "0.1.0"
8
+ description = "Help desk plugin for Tungsten: tickets, replies, internal notes, SLA and a customer support page."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Prism Infoways" }]
13
+ keywords = ["tungsten", "tungsten-admin", "helpdesk", "tickets", "support", "fastapi", "admin"]
14
+ dependencies = ["tungsten-admin>=0.1.4"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://tungsten.prisminfoways.com/"
18
+ Documentation = "https://tungsten.prisminfoways.com/docs/tickets.html"
19
+ Repository = "https://github.com/Prism-Infoways/Tungsten"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/tungsten_tickets"]
@@ -0,0 +1,226 @@
1
+ """Ticketing desk (help desk) plugin for Tungsten.
2
+
3
+ from tungsten_tickets import TicketsPlugin
4
+
5
+ panel.plugin(TicketsPlugin())
6
+ panel.create_tables(engine) # also creates the ticket tables
7
+
8
+ Adds a "Help desk" menu: tickets with status, priority, category, agent and SLA
9
+ due times, a conversation with replies and internal notes, saved replies, and a
10
+ public "raise a ticket" page where customers also follow and answer their ticket.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hmac
16
+ import logging
17
+ from pathlib import Path
18
+ from types import SimpleNamespace
19
+ from typing import Any
20
+
21
+ from fastapi import Request
22
+ from fastapi.responses import JSONResponse
23
+ from starlette.concurrency import run_in_threadpool
24
+
25
+ from tungsten import Plugin
26
+ from tungsten.support.evaluate import call
27
+
28
+ from .models import SavedReply, Ticket, TicketCategory, TicketReply, TicketsBase
29
+ from .resources import SavedReplyResource, TicketCategoryResource, TicketResource
30
+ from .service import (
31
+ DEFAULT_PRIORITIES,
32
+ DEFAULT_SLA_HOURS,
33
+ DEFAULT_STATUSES,
34
+ add_event,
35
+ add_reply,
36
+ create_ticket,
37
+ find_ticket,
38
+ set_status,
39
+ )
40
+ from .widgets import TicketStats
41
+
42
+ __version__ = "0.1.0"
43
+
44
+ log = logging.getLogger("tungsten.tickets")
45
+
46
+
47
+ class TicketsPlugin(Plugin):
48
+ """``TicketsPlugin(statuses=..., priorities=..., sla_hours=..., portal=True, api_token=None)``.
49
+
50
+ - ``statuses`` / ``priorities`` map a key to ``(label, color)``. ``resolved`` and ``closed`` count as done.
51
+ - ``sla_hours`` maps a priority to the hours a ticket has to be resolved (``None``: no due time).
52
+ - ``portal`` adds the public pages ``<panel>/support`` (raise a ticket) and the customer's ticket page.
53
+ - ``api_token`` lets websites and apps POST tickets to ``<panel>/api/tickets``
54
+ (send it in the ``X-Tickets-Token`` header).
55
+ - ``email_requester`` emails the customer on new tickets, replies and when resolved, through
56
+ ``mailer`` or the panel's ``Auth(mailer=...)``.
57
+ - ``notify_agents`` puts new tickets and customer replies in the agent's notification bell.
58
+ """
59
+
60
+ id = "tickets"
61
+ metadata = TicketsBase.metadata
62
+ templates = Path(__file__).with_name("templates")
63
+
64
+ def __init__(self, statuses: dict[str, tuple[str, str]] | None = None,
65
+ priorities: dict[str, tuple[str, str]] | None = None, sla_hours: dict[str, Any] | None = None,
66
+ number_prefix: str = "TCK-", portal: bool = True, portal_path: str = "support",
67
+ api_token: str | None = None, email_requester: bool = True, notify_agents: bool = True,
68
+ mailer: Any = None, dashboard_widget: bool = True, navigation_group: str = "Help desk") -> None:
69
+ self.statuses = dict(statuses or DEFAULT_STATUSES)
70
+ self.priorities = dict(priorities or DEFAULT_PRIORITIES)
71
+ self.sla_hours = dict(DEFAULT_SLA_HOURS if sla_hours is None else sla_hours)
72
+ self.number_prefix = number_prefix
73
+ self.portal = portal
74
+ self.portal_path = portal_path.strip("/")
75
+ self.api_token = api_token
76
+ self.email_requester_enabled = email_requester
77
+ self.notify_agents = notify_agents
78
+ self.mailer = mailer
79
+ self.dashboard_widget = dashboard_widget
80
+ self.navigation_group = navigation_group
81
+ self.panel: Any = None
82
+ #: other plugins (WhatsApp, Slack...) hook in with the three methods below
83
+ self.created_listeners: dict[str, Any] = {}
84
+ self.reply_listeners: dict[str, Any] = {}
85
+ self.status_listeners: dict[str, Any] = {}
86
+
87
+ # ------------------------------------------------------------------ hooks for other code
88
+ def on_ticket_created(self, key: str, fn: Any) -> None:
89
+ """Run ``fn(db, ticket)`` after a ticket is opened. The same ``key`` replaces the function."""
90
+ self.created_listeners[key] = fn
91
+
92
+ def on_ticket_replied(self, key: str, fn: Any) -> None:
93
+ """Run ``fn(db, ticket, reply)`` after any reply, customer message or internal note."""
94
+ self.reply_listeners[key] = fn
95
+
96
+ def on_status_changed(self, key: str, fn: Any) -> None:
97
+ """Run ``fn(db, ticket, old_status)`` after a ticket's status changes."""
98
+ self.status_listeners[key] = fn
99
+
100
+ # ------------------------------------------------------------------ setup
101
+ def register(self, panel: Any) -> None:
102
+ self.panel = panel
103
+ for resource in (TicketResource, TicketCategoryResource, SavedReplyResource):
104
+ resource.navigation_group = self.navigation_group
105
+ panel.resources([TicketResource, TicketCategoryResource, SavedReplyResource])
106
+ panel.navigation_group(self.navigation_group, icon="life-buoy")
107
+ if self.dashboard_widget:
108
+ panel.widgets([TicketStats])
109
+ panel.routes(self._routes)
110
+
111
+ # ------------------------------------------------------------------ links
112
+ def _absolute(self, ctx: Any, path: str) -> str | None:
113
+ if self.panel.app_url:
114
+ return f"{self.panel.app_url}{path}"
115
+ if ctx is not None and getattr(ctx, "request", None) is not None:
116
+ return self.panel.absolute_url(ctx, path)
117
+ return None
118
+
119
+ def portal_path_for(self, ticket: Ticket) -> str:
120
+ return self.panel.url(self.portal_path, ticket.number, ticket.access_key)
121
+
122
+ def customer_link(self, ticket: Ticket, ctx: Any = None) -> str | None:
123
+ """The customer's private link to their ticket (None without the portal or a known address)."""
124
+ return self._absolute(ctx, self.portal_path_for(ticket)) if self.portal else None
125
+
126
+ def agent_link(self, ticket: Ticket) -> str:
127
+ return self.panel.url(TicketResource.get_slug(), ticket.id)
128
+
129
+ # ------------------------------------------------------------------ messages
130
+ def notify_agent(self, db: Any, ticket: Ticket, title: str, body: str, ctx: Any = None) -> None:
131
+ """Put a note in the assigned agent's notification bell (not when they did it themselves)."""
132
+ if not self.notify_agents or not ticket.assigned_to:
133
+ return
134
+ if ctx is not None and getattr(ctx, "user", None) is not None \
135
+ and str(self.panel.auth.user_id(ctx.user)) == str(ticket.assigned_to):
136
+ return
137
+ from tungsten import Notification
138
+ from tungsten.models import DatabaseNotification
139
+
140
+ data = Notification(title).body(body).icon("life-buoy").color("info") \
141
+ .action("Open ticket", self.agent_link(ticket)).to_dict()
142
+ db.add(DatabaseNotification(user_id=str(ticket.assigned_to), data=data))
143
+
144
+ def email_requester(self, db: Any, ticket: Ticket, kind: str, ctx: Any = None,
145
+ reply: TicketReply | None = None) -> None:
146
+ """Email the customer: ``received``, ``reply`` or ``resolved``. Mail errors are logged, not raised."""
147
+ if not self.email_requester_enabled or not ticket.requester_email:
148
+ return
149
+ link = self.customer_link(ticket, ctx)
150
+ hello = f"Hello {ticket.requester_name or 'there'},"
151
+ see = f"\n\nSee your ticket and reply here:\n{link}" if link else ""
152
+ if kind == "received":
153
+ subject = f"[{ticket.number}] We got your request: {ticket.subject}"
154
+ body = f"{hello}\n\nThanks for writing to us. Your ticket number is {ticket.number}. " \
155
+ f"We will reply soon.{see}"
156
+ elif kind == "reply" and reply is not None:
157
+ subject = f"[{ticket.number}] {ticket.subject}"
158
+ body = f"{hello}\n\n{reply.body}{see}"
159
+ elif kind == "resolved":
160
+ subject = f"[{ticket.number}] Resolved: {ticket.subject}"
161
+ body = f"{hello}\n\nWe marked your ticket {ticket.number} as resolved. " \
162
+ f"If you still need help, just reply.{see}"
163
+ else:
164
+ return
165
+ mailer = self.mailer or self.panel.auth.mailer
166
+ try:
167
+ call(mailer, to=ticket.requester_email, subject=subject, body=body, url=link, ticket=ticket,
168
+ kind=f"ticket_{kind}")
169
+ except Exception: # a broken mail server must not lose the ticket
170
+ log.exception("Could not email %s about ticket %s", ticket.requester_email, ticket.number)
171
+
172
+ # ------------------------------------------------------------------ routes
173
+ def _routes(self, app: Any, panel: Any) -> None:
174
+ if self.portal:
175
+ from .portal import add_portal_routes
176
+
177
+ add_portal_routes(app, panel, self)
178
+ if self.api_token:
179
+ self._api_route(app, panel)
180
+
181
+ def _api_route(self, app: Any, panel: Any) -> None:
182
+ plugin = self
183
+
184
+ @app.post("/api/tickets")
185
+ async def api_create(request: Request):
186
+ token = request.headers.get("x-tickets-token", "")
187
+ if not hmac.compare_digest(token.encode(), (plugin.api_token or "").encode()):
188
+ return JSONResponse({"error": "Wrong token"}, status_code=401)
189
+ if request.headers.get("content-type", "").startswith("application/json"):
190
+ payload = await request.json()
191
+ else:
192
+ payload = dict(await request.form())
193
+ if not isinstance(payload, dict):
194
+ return JSONResponse({"error": "Send a JSON object"}, status_code=422)
195
+ subject = str(payload.get("subject") or "").strip()
196
+ if not subject:
197
+ return JSONResponse({"error": "Send a subject"}, status_code=422)
198
+ priority = str(payload.get("priority") or "normal")
199
+ if priority not in plugin.priorities:
200
+ return JSONResponse({"error": f"Unknown priority {priority}"}, status_code=422)
201
+
202
+ link_ctx = SimpleNamespace(request=request, user=None) # for full links in emails
203
+
204
+ def save(db: Any) -> dict:
205
+ category_id = None
206
+ if payload.get("category"):
207
+ category = db.query(TicketCategory).filter(TicketCategory.name == str(payload["category"])).first()
208
+ category_id = category.id if category is not None else None
209
+ ticket = create_ticket(
210
+ db, subject=subject, description=payload.get("description") or payload.get("message"),
211
+ requester_name=payload.get("name"), requester_email=payload.get("email"),
212
+ requester_phone=payload.get("phone"), priority=priority, category_id=category_id,
213
+ source=str(payload.get("source") or "api")[:20], external_id=payload.get("external_id"),
214
+ ctx=link_ctx)
215
+ db.commit()
216
+ return {"id": ticket.id, "number": ticket.number, "url": plugin.customer_link(ticket, link_ctx)}
217
+
218
+ result = await run_in_threadpool(panel.with_session, save)
219
+ return JSONResponse(result, status_code=201)
220
+
221
+
222
+ __all__ = [
223
+ "SavedReply", "SavedReplyResource", "Ticket", "TicketCategory", "TicketCategoryResource", "TicketReply",
224
+ "TicketResource", "TicketStats", "TicketsBase", "TicketsPlugin", "add_event", "add_reply", "create_ticket",
225
+ "find_ticket", "set_status",
226
+ ]