tungsten-quick-create 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,101 @@
1
+ Metadata-Version: 2.5
2
+ Name: tungsten-quick-create
3
+ Version: 0.1.0
4
+ Summary: Quick Create plugin for Tungsten: a + New button in the top bar to add any record from any page.
5
+ Project-URL: Homepage, https://tungsten.prisminfoways.com/
6
+ Project-URL: Documentation, https://tungsten.prisminfoways.com/docs/quick-create
7
+ Project-URL: Repository, https://github.com/Prism-Infoways/Tungsten
8
+ Author: Prism Infoways
9
+ License: MIT
10
+ Keywords: admin,fastapi,productivity,quick-create,shortcut,tungsten,tungsten-admin
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: tungsten-admin>=0.1.7
13
+ Description-Content-Type: text/markdown
14
+
15
+ # tungsten-quick-create
16
+
17
+ Quick Create plugin for [Tungsten](https://tungsten.prisminfoways.com/), the admin panel for FastAPI.
18
+
19
+ A **+ New** button in the top bar. Pick what you want to add (a product, a lead, a ticket, an
20
+ employee, an invoice...) and its form opens in a side panel, on top of the page you are on. Save,
21
+ and you are still where you were.
22
+
23
+ ## What you get
24
+
25
+ - A **+ New** button on every page, listing every resource the signed-in user may create.
26
+ - Works with **other plugins** out of the box: leads, tickets, HR, finance, blog and your own resources all show up.
27
+ - Respects **permissions**: a user only sees what they may create (roles, policies and tenants).
28
+ - The form opens in a **side panel** (or a popup) with live fields, uploads and validation, like the normal create page.
29
+ - **Create & create another** for adding many records in a row.
30
+ - After saving: a toast with an **Open** link to the new record, and any table on the page refreshes.
31
+ - Grouped by sidebar group, with a **search box** when the list is long.
32
+ - Optional **keyboard shortcut**.
33
+ - Safe: a database error or a broken policy shows a message and never breaks the page.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install tungsten-quick-create
39
+ ```
40
+
41
+ ```python
42
+ from tungsten_quick_create import QuickCreatePlugin
43
+
44
+ panel.plugin(QuickCreatePlugin())
45
+ ```
46
+
47
+ No tables, no settings needed.
48
+
49
+ ### Options
50
+
51
+ ```python
52
+ QuickCreatePlugin(
53
+ include=None, # only these resources (classes or slugs), in this order
54
+ exclude=(), # hide these resources (classes or slugs)
55
+ label="New", # "" shows just the + icon
56
+ icon="plus",
57
+ slide_over=True, # False: a centred popup
58
+ width="4xl", # sm, md, lg, xl, 2xl, 3xl, 4xl, 5xl
59
+ create_another=True, # the "Create & create another" button
60
+ open_after_create=False, # True: go to the new record after saving
61
+ group=True, # split the menu by sidebar group
62
+ search_from=8, # show a search box once the menu has this many entries
63
+ shortcut=None, # e.g. "mod+shift+n" (mod is Ctrl, or Cmd on a Mac)
64
+ )
65
+ ```
66
+
67
+ ### Hide one resource
68
+
69
+ ```python
70
+ class AuditLogResource(Resource):
71
+ quick_create = False
72
+ ```
73
+
74
+ Resources without a create page (`pages = ("index",)`) never show up.
75
+
76
+ ### Add your own entries (for plugin authors)
77
+
78
+ Anything that is not a resource form can be a link in the menu:
79
+
80
+ ```python
81
+ quick = panel.get_plugin("quick-create")
82
+ if quick is not None:
83
+ quick.add_link("event", "Event", "/admin/calendar?new=1", icon="calendar", group="Planning")
84
+ quick.add_link("upload", "Upload file", lambda ctx: ctx.url("media", "upload"), icon="upload",
85
+ visible=lambda user: user.is_staff)
86
+ ```
87
+
88
+ The same key replaces an entry; `quick.remove_link("event")` removes it.
89
+
90
+ ## Try it
91
+
92
+ ```bash
93
+ pip install -e . -e plugins/quick-create uvicorn
94
+ uvicorn plugins.quick-create.example:app --reload # from the repo root
95
+ ```
96
+
97
+ Open http://127.0.0.1:8000/admin and sign in with admin@example.com / password.
98
+
99
+ ## License
100
+
101
+ MIT
@@ -0,0 +1,87 @@
1
+ # tungsten-quick-create
2
+
3
+ Quick Create plugin for [Tungsten](https://tungsten.prisminfoways.com/), the admin panel for FastAPI.
4
+
5
+ A **+ New** button in the top bar. Pick what you want to add (a product, a lead, a ticket, an
6
+ employee, an invoice...) and its form opens in a side panel, on top of the page you are on. Save,
7
+ and you are still where you were.
8
+
9
+ ## What you get
10
+
11
+ - A **+ New** button on every page, listing every resource the signed-in user may create.
12
+ - Works with **other plugins** out of the box: leads, tickets, HR, finance, blog and your own resources all show up.
13
+ - Respects **permissions**: a user only sees what they may create (roles, policies and tenants).
14
+ - The form opens in a **side panel** (or a popup) with live fields, uploads and validation, like the normal create page.
15
+ - **Create & create another** for adding many records in a row.
16
+ - After saving: a toast with an **Open** link to the new record, and any table on the page refreshes.
17
+ - Grouped by sidebar group, with a **search box** when the list is long.
18
+ - Optional **keyboard shortcut**.
19
+ - Safe: a database error or a broken policy shows a message and never breaks the page.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install tungsten-quick-create
25
+ ```
26
+
27
+ ```python
28
+ from tungsten_quick_create import QuickCreatePlugin
29
+
30
+ panel.plugin(QuickCreatePlugin())
31
+ ```
32
+
33
+ No tables, no settings needed.
34
+
35
+ ### Options
36
+
37
+ ```python
38
+ QuickCreatePlugin(
39
+ include=None, # only these resources (classes or slugs), in this order
40
+ exclude=(), # hide these resources (classes or slugs)
41
+ label="New", # "" shows just the + icon
42
+ icon="plus",
43
+ slide_over=True, # False: a centred popup
44
+ width="4xl", # sm, md, lg, xl, 2xl, 3xl, 4xl, 5xl
45
+ create_another=True, # the "Create & create another" button
46
+ open_after_create=False, # True: go to the new record after saving
47
+ group=True, # split the menu by sidebar group
48
+ search_from=8, # show a search box once the menu has this many entries
49
+ shortcut=None, # e.g. "mod+shift+n" (mod is Ctrl, or Cmd on a Mac)
50
+ )
51
+ ```
52
+
53
+ ### Hide one resource
54
+
55
+ ```python
56
+ class AuditLogResource(Resource):
57
+ quick_create = False
58
+ ```
59
+
60
+ Resources without a create page (`pages = ("index",)`) never show up.
61
+
62
+ ### Add your own entries (for plugin authors)
63
+
64
+ Anything that is not a resource form can be a link in the menu:
65
+
66
+ ```python
67
+ quick = panel.get_plugin("quick-create")
68
+ if quick is not None:
69
+ quick.add_link("event", "Event", "/admin/calendar?new=1", icon="calendar", group="Planning")
70
+ quick.add_link("upload", "Upload file", lambda ctx: ctx.url("media", "upload"), icon="upload",
71
+ visible=lambda user: user.is_staff)
72
+ ```
73
+
74
+ The same key replaces an entry; `quick.remove_link("event")` removes it.
75
+
76
+ ## Try it
77
+
78
+ ```bash
79
+ pip install -e . -e plugins/quick-create uvicorn
80
+ uvicorn plugins.quick-create.example:app --reload # from the repo root
81
+ ```
82
+
83
+ Open http://127.0.0.1:8000/admin and sign in with admin@example.com / password.
84
+
85
+ ## License
86
+
87
+ MIT
@@ -0,0 +1,121 @@
1
+ """Try the quick create plugin.
2
+
3
+ pip install -e . -e plugins/quick-create uvicorn
4
+ uvicorn example:app --app-dir plugins/quick-create --reload (from the repo root)
5
+
6
+ Open http://127.0.0.1:8000/admin and sign in with admin@example.com / password,
7
+ then click "+ New" in the top bar. With tungsten-tickets or tungsten-leads
8
+ installed, their forms show up in the menu too.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from fastapi import FastAPI
14
+ from fastapi.responses import RedirectResponse
15
+ from sqlalchemy import Boolean, Numeric, String, create_engine, select
16
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
17
+ from tungsten_quick_create import QuickCreatePlugin
18
+
19
+ from tungsten import Auth, Panel, Resource, hash_password
20
+ from tungsten.forms import Select, TextInput
21
+ from tungsten.tables import TextColumn
22
+
23
+
24
+ class Base(DeclarativeBase):
25
+ pass
26
+
27
+
28
+ class User(Base):
29
+ __tablename__ = "users"
30
+
31
+ id: Mapped[int] = mapped_column(primary_key=True)
32
+ name: Mapped[str] = mapped_column(String(100))
33
+ email: Mapped[str] = mapped_column(String(200), unique=True)
34
+ password: Mapped[str] = mapped_column(String(200))
35
+ is_active: Mapped[bool] = mapped_column(Boolean, default=True)
36
+
37
+
38
+ class Product(Base):
39
+ __tablename__ = "products"
40
+
41
+ id: Mapped[int] = mapped_column(primary_key=True)
42
+ name: Mapped[str] = mapped_column(String(100))
43
+ price: Mapped[float] = mapped_column(Numeric(10, 2), default=0)
44
+
45
+
46
+ class Customer(Base):
47
+ __tablename__ = "customers"
48
+
49
+ id: Mapped[int] = mapped_column(primary_key=True)
50
+ name: Mapped[str] = mapped_column(String(100))
51
+ city: Mapped[str | None] = mapped_column(String(60), nullable=True)
52
+
53
+
54
+ class ProductResource(Resource):
55
+ model = Product
56
+ icon = "package"
57
+ navigation_group = "Shop"
58
+
59
+ @classmethod
60
+ def form(cls, form):
61
+ return form.schema([TextInput("name").required(), TextInput("price").numeric().required()]).columns(2)
62
+
63
+ @classmethod
64
+ def table(cls, table):
65
+ return table.columns([TextColumn("name").searchable(), TextColumn("price")])
66
+
67
+
68
+ class CustomerResource(Resource):
69
+ model = Customer
70
+ icon = "users"
71
+ navigation_group = "Shop"
72
+
73
+ @classmethod
74
+ def form(cls, form):
75
+ return form.schema([TextInput("name").required(),
76
+ Select("city").options({"Delhi": "Delhi", "Mumbai": "Mumbai", "Pune": "Pune"})])
77
+
78
+ @classmethod
79
+ def table(cls, table):
80
+ return table.columns([TextColumn("name").searchable(), TextColumn("city")])
81
+
82
+
83
+ engine = create_engine("sqlite:///quick_create_demo.db")
84
+ Base.metadata.create_all(engine)
85
+ Session = sessionmaker(engine, expire_on_commit=False)
86
+
87
+ panel = Panel(path="/admin", session_factory=Session, secret_key="dev-only", auth=Auth(User),
88
+ brand_name="Tungsten", navigation_groups=["Shop"])
89
+ panel.resources([ProductResource, CustomerResource])
90
+
91
+ try: # other plugins join the menu by themselves
92
+ from tungsten_tickets import TicketsPlugin
93
+
94
+ panel.plugin(TicketsPlugin(portal=False))
95
+ except ImportError:
96
+ pass
97
+ try:
98
+ from tungsten_leads import LeadsPlugin
99
+
100
+ panel.plugin(LeadsPlugin())
101
+ except ImportError:
102
+ pass
103
+
104
+ quick = QuickCreatePlugin(shortcut="mod+shift+n")
105
+ panel.plugin(quick)
106
+ quick.add_link("docs", "Read the docs", "https://tungsten.prisminfoways.com/docs/quick-create", icon="book-open",
107
+ group="Help")
108
+ panel.create_tables(engine)
109
+
110
+ with Session() as db:
111
+ if db.scalar(select(User)) is None:
112
+ db.add(User(name="Asha Admin", email="admin@example.com", password=hash_password("password")))
113
+ db.commit()
114
+
115
+ app = FastAPI()
116
+ panel.mount(app)
117
+
118
+
119
+ @app.get("/")
120
+ def root():
121
+ 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-quick-create"
7
+ version = "0.1.0"
8
+ description = "Quick Create plugin for Tungsten: a + New button in the top bar to add any record from any page."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Prism Infoways" }]
13
+ keywords = ["tungsten", "tungsten-admin", "quick-create", "shortcut", "productivity", "fastapi", "admin"]
14
+ dependencies = ["tungsten-admin>=0.1.7"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://tungsten.prisminfoways.com/"
18
+ Documentation = "https://tungsten.prisminfoways.com/docs/quick-create"
19
+ Repository = "https://github.com/Prism-Infoways/Tungsten"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/tungsten_quick_create"]
@@ -0,0 +1,322 @@
1
+ """Quick Create plugin for Tungsten: a "+ New" button in the top bar.
2
+
3
+ from tungsten_quick_create import QuickCreatePlugin
4
+
5
+ panel.plugin(QuickCreatePlugin())
6
+
7
+ The button lists every resource the signed-in user may create (your own and
8
+ those of other plugins: leads, tickets, employees, invoices, posts...). Picking
9
+ one opens its create form in a side panel, so a record can be added from any
10
+ page without losing your place.
11
+
12
+ Other plugins add their own entries with :meth:`QuickCreatePlugin.add_link`, and
13
+ a resource leaves the menu with ``quick_create = False``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from collections.abc import Callable, Iterable
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from fastapi import Request
25
+ from fastapi.responses import Response
26
+ from markupsafe import Markup
27
+
28
+ from tungsten import Notification, Plugin
29
+ from tungsten.forms.form import ValidationError
30
+ from tungsten.i18n import translate as __
31
+ from tungsten.routes import Forbidden, NotFound, Routes
32
+ from tungsten.support.evaluate import call
33
+
34
+ __version__ = "0.1.0"
35
+
36
+ log = logging.getLogger("tungsten.quick_create")
37
+
38
+ WIDTHS = ("sm", "md", "lg", "xl", "2xl", "3xl", "4xl", "5xl")
39
+ FORM_ID = "tw-quick-create-form"
40
+
41
+
42
+ @dataclass
43
+ class QuickLink:
44
+ """An extra menu entry that is a plain link (another plugin's "New event", "Upload file"...)."""
45
+
46
+ key: str
47
+ label: str
48
+ url: str | Callable[..., str]
49
+ icon: str | None = None
50
+ group: str | None = None
51
+ sort: int = 0
52
+ #: ``visible(ctx=..., user=...)``: hide the entry for some users
53
+ visible: Callable[..., Any] | bool = True
54
+
55
+
56
+ class QuickCreatePlugin(Plugin):
57
+ """``QuickCreatePlugin(include=None, exclude=(), label="New", ...)``.
58
+
59
+ - ``include`` lists the resources (classes or slugs) to show, in that order. Default: every one.
60
+ - ``exclude`` hides resources (classes or slugs).
61
+ - ``label`` / ``icon`` style the top bar button. ``label=""`` shows the icon alone.
62
+ - ``slide_over`` opens forms in a side panel (``False``: a centred popup); ``width`` is its size.
63
+ - ``create_another`` adds a "Create & create another" button.
64
+ - ``open_after_create`` goes to the new record after saving instead of staying on the page.
65
+ - ``group`` splits the menu by navigation group; ``search_from`` shows a filter box once the
66
+ menu has that many entries.
67
+ - ``shortcut`` opens the menu from the keyboard, e.g. ``"mod+shift+n"``.
68
+ """
69
+
70
+ id = "quick-create"
71
+ templates = Path(__file__).with_name("templates")
72
+
73
+ def __init__(self, include: Iterable[Any] | None = None, exclude: Iterable[Any] = (), label: str = "New",
74
+ icon: str = "plus", slide_over: bool = True, width: str = "4xl", create_another: bool = True,
75
+ open_after_create: bool = False, group: bool = True, search_from: int = 8,
76
+ shortcut: str | None = None) -> None:
77
+ if width not in WIDTHS:
78
+ raise ValueError(f"width must be one of {', '.join(WIDTHS)}")
79
+ self.include = list(include) if include is not None else None
80
+ self.exclude = list(exclude)
81
+ self.label = label
82
+ self.icon = icon
83
+ self.slide_over = slide_over
84
+ self.width = width
85
+ self.create_another = create_another
86
+ self.open_after_create = open_after_create
87
+ self.group = group
88
+ self.search_from = search_from
89
+ self.shortcut = shortcut
90
+ self.links: dict[str, QuickLink] = {}
91
+ self.panel: Any = None
92
+
93
+ # ------------------------------------------------------------------ hooks for other code
94
+ def add_link(self, key: str, label: str, url: str | Callable[..., str], icon: str | None = None,
95
+ group: str | None = None, sort: int = 0, visible: Callable[..., Any] | bool = True) -> None:
96
+ """Add a menu entry that opens ``url`` (a string, or ``url(ctx=...)``). The same ``key`` replaces it."""
97
+ self.links[key] = QuickLink(key, label, url, icon, group, sort, visible)
98
+
99
+ def remove_link(self, key: str) -> None:
100
+ self.links.pop(key, None)
101
+
102
+ #: how many "New ..." shortcuts the installed app gets (phones show about four)
103
+ pwa_shortcut_limit = 4
104
+
105
+ def pwa_shortcuts(self, panel: Any) -> list[dict[str, str]]:
106
+ """App shortcuts for tungsten-pwa: "New ..." for the first resources, then plain links.
107
+
108
+ They open the normal create page, which checks the user's permissions as always.
109
+ """
110
+ out = [{"name": __("New :label", label=r.get_label()), "url": panel.url(r.get_slug(), "create")}
111
+ for r in self.resources() if r.has_page("create")]
112
+ out += [{"name": __(link.label), "url": link.url} for link in sorted(self.links.values(), key=lambda l: l.sort)
113
+ if isinstance(link.url, str) and link.visible is True]
114
+ return out[:self.pwa_shortcut_limit]
115
+
116
+ # ------------------------------------------------------------------ setup
117
+ def register(self, panel: Any) -> None:
118
+ self.panel = panel
119
+ panel.render_hook("topbar.end", self._button)
120
+ panel.routes(self._routes)
121
+
122
+ # ------------------------------------------------------------------ which resources
123
+ @staticmethod
124
+ def _matches(resource: Any, ref: Any) -> bool:
125
+ return resource is ref or (isinstance(ref, str) and resource.get_slug() == ref)
126
+
127
+ def resources(self) -> list[Any]:
128
+ """Resources that can be quick-created at all (before checking the user's permissions)."""
129
+ found = [r for r in self.panel.get_resources()
130
+ if "create" in r.pages and getattr(r, "quick_create", True) is not False
131
+ and not any(self._matches(r, ref) for ref in self.exclude)]
132
+ if self.include is None:
133
+ return found
134
+ ordered = []
135
+ for ref in self.include:
136
+ for r in found:
137
+ if self._matches(r, ref) and r not in ordered:
138
+ ordered.append(r)
139
+ return ordered
140
+
141
+ def allowed(self, ctx: Any, resource: Any) -> bool:
142
+ """The user may open the list (live form updates need it) and create."""
143
+ try:
144
+ return bool(resource.can(ctx, "view_any") and resource.can(ctx, "create"))
145
+ except Exception: # a broken policy hides one entry, not the whole top bar
146
+ log.exception("Quick create: permission check failed for %s", resource.get_slug())
147
+ return False
148
+
149
+ def items(self, ctx: Any) -> list[dict[str, Any]]:
150
+ """The menu entries for this user: ``{"label", "icon", "group", "url" | "modal_url"}``."""
151
+ out: list[dict[str, Any]] = []
152
+ for n, r in enumerate(self.resources()):
153
+ if not self.allowed(ctx, r):
154
+ continue
155
+ sort = n if self.include is not None else r.navigation_sort
156
+ out.append({"key": r.get_slug(), "label": r.get_label(), "icon": r.icon or "file-text",
157
+ "group": r.navigation_group, "sort": sort,
158
+ "modal_url": self.panel.url("_quick-create", r.get_slug())})
159
+ for link in self.links.values():
160
+ try:
161
+ shown = call(link.visible, ctx=ctx, user=ctx.user) if callable(link.visible) else link.visible
162
+ if not shown:
163
+ continue
164
+ url = call(link.url, ctx=ctx, user=ctx.user) if callable(link.url) else link.url
165
+ except Exception:
166
+ log.exception("Quick create: link %r failed", link.key)
167
+ continue
168
+ if url:
169
+ out.append({"key": link.key, "label": __(link.label), "icon": link.icon or "plus",
170
+ "group": link.group, "sort": link.sort, "url": url})
171
+ if self.include is None:
172
+ out.sort(key=lambda i: (i["sort"], i["label"].lower()))
173
+ return out
174
+
175
+ def grouped(self, items: list[dict[str, Any]]) -> list[tuple[str, list[dict[str, Any]]]]:
176
+ """Entries split by navigation group, in the order the sidebar shows the groups."""
177
+ if not self.group:
178
+ return [("", items)]
179
+ order = [g.label for g in self.panel._nav_groups]
180
+ groups: dict[str, list] = {}
181
+ for item in items:
182
+ groups.setdefault(item["group"] or "", []).append(item)
183
+ if len(groups) < 2:
184
+ return [("", items)]
185
+ rank = {label: n for n, label in enumerate(order)}
186
+ keys = sorted(groups, key=lambda g: (g != "", rank.get(g, len(rank)), g))
187
+ return [(__(g) if g else "", groups[g]) for g in keys]
188
+
189
+ # ------------------------------------------------------------------ top bar button
190
+ def _button(self, ctx: Any) -> Markup:
191
+ if ctx.user is None and self.panel.auth.enabled:
192
+ return Markup("")
193
+ try:
194
+ items = self.items(ctx)
195
+ except Exception: # never break every page because of the menu
196
+ log.exception("Quick create: could not build the menu")
197
+ return Markup("")
198
+ if not items:
199
+ return Markup("")
200
+ return Markup(self.panel.renderer.render(
201
+ "tungsten_quick_create/button.html", plugin=self, groups=self.grouped(items), count=len(items),
202
+ all_labels=[i["label"].lower() for i in items],
203
+ label=__(self.label) if self.label else "", ctx=ctx, panel=self.panel))
204
+
205
+ # ------------------------------------------------------------------ routes
206
+ def _routes(self, app: Any, panel: Any) -> None:
207
+ routes = Routes(panel)
208
+ plugin = self
209
+
210
+ @app.get("/_quick-create/{slug}")
211
+ async def quick_create_open(request: Request, slug: str):
212
+ return await routes.run(request, plugin.handle, slug=slug)
213
+
214
+ @app.post("/_quick-create/{slug}")
215
+ async def quick_create_save(request: Request, slug: str):
216
+ return await routes.run(request, plugin.handle, read_form=True, slug=slug)
217
+
218
+ def _resource(self, ctx: Any, slug: str) -> Any:
219
+ resource = next((r for r in self.resources() if r.get_slug() == slug), None)
220
+ if resource is None:
221
+ raise NotFound()
222
+ if not self.allowed(ctx, resource):
223
+ raise Forbidden()
224
+ return resource
225
+
226
+ def _form(self, ctx: Any, resource: Any) -> Any:
227
+ form = resource.host().form(ctx, "create")
228
+ form.id = FORM_ID
229
+ return form
230
+
231
+ def handle(self, ctx: Any, fd: Any, slug: str) -> Response:
232
+ resource = self._resource(ctx, slug)
233
+ host = resource.host()
234
+ form = self._form(ctx, resource)
235
+ if fd is None:
236
+ form.fill()
237
+ return self._modal(ctx, resource, form)
238
+ form.load(fd)
239
+ try:
240
+ data = form.validate()
241
+ except ValidationError:
242
+ return self._modal(ctx, resource, form)
243
+ try:
244
+ record = host.create(ctx, data, form)
245
+ self.panel.log_activity(ctx, "created", record)
246
+ ctx.db.commit()
247
+ except ValidationError as exc: # a resource hook refused the data
248
+ ctx.db.rollback()
249
+ form.errors = exc.errors
250
+ return self._modal(ctx, resource, form)
251
+ except (NotFound, Forbidden, PermissionError):
252
+ raise
253
+ except Exception:
254
+ ctx.db.rollback()
255
+ log.exception("Quick create: could not save %s", slug)
256
+ Notification("Not saved").body("Something went wrong while saving. Please check the form and try again.") \
257
+ .danger().send(ctx)
258
+ return self._modal(ctx, resource, form)
259
+ link = self._record_url(ctx, resource, record)
260
+ note = Notification("Created").body(__(":label was created.", label=resource.get_label())).success()
261
+ if link and not self.open_after_create:
262
+ note.action(__("Open"), link)
263
+ note.send(ctx)
264
+ if self.open_after_create and link:
265
+ return ctx.go(link)
266
+ ctx.dispatch("tw-refresh") # tables on the page behind show the new record
267
+ if fd.get("_tw_another") and self.create_another:
268
+ fresh = self._form(ctx, resource)
269
+ fresh.fill()
270
+ return self._modal(ctx, resource, fresh)
271
+ ctx.dispatch("tw-close-modal")
272
+ return ctx.html("")
273
+
274
+ @staticmethod
275
+ def _record_url(ctx: Any, resource: Any, record: Any) -> str | None:
276
+ host = resource.host()
277
+ try:
278
+ if resource.has_page("view") and resource.can(ctx, "view", record):
279
+ return host.view_url(ctx, record)
280
+ if resource.has_page("edit") and resource.can(ctx, "update", record):
281
+ return host.edit_url(ctx, record)
282
+ except Exception:
283
+ log.exception("Quick create: could not link to the new record")
284
+ return None
285
+
286
+ def _live_note(self, ctx: Any) -> str | None:
287
+ """With the environment indicator plugin on live, say so in the form, so nobody adds test data there."""
288
+ indicator = self.panel.get_plugin("environment-indicator")
289
+ if indicator is None or not hasattr(indicator, "current"):
290
+ return None
291
+ try:
292
+ env = indicator.current(ctx)
293
+ except Exception: # never break the form because of the note
294
+ log.exception("Quick create: could not read the environment")
295
+ return None
296
+ if getattr(env, "is_production", False):
297
+ return __("You are on :env. This record goes into real data.", env=env.label)
298
+ return None
299
+
300
+ def _modal(self, ctx: Any, resource: Any, form: Any) -> Response:
301
+ m = {
302
+ "endpoint": self.panel.url("_quick-create", resource.get_slug()),
303
+ "heading": __("Create :label", label=resource.get_label().lower()),
304
+ "description": self._live_note(ctx),
305
+ "icon": resource.icon,
306
+ "icon_color": "primary",
307
+ "submit_label": __("Create"),
308
+ "cancel_label": __("Cancel"),
309
+ "color": "primary",
310
+ "width": self.width,
311
+ "slide_over": self.slide_over,
312
+ "confirm_only": False,
313
+ "content": None,
314
+ "multipart": False,
315
+ "create_another_label": __("Create & create another") if self.create_another else None,
316
+ }
317
+ html = self.panel.renderer.render("tungsten/actions/modal.html", m=m, form=form, hidden={}, records=[],
318
+ ctx=ctx)
319
+ return ctx.html(html)
320
+
321
+
322
+ __all__ = ["QuickCreatePlugin", "QuickLink"]
@@ -0,0 +1,51 @@
1
+ {#
2
+ The "+ New" button in the top bar. vars: plugin, groups [(label, items)], count, label
3
+ #}
4
+ {% import "tungsten/components/ui.html" as ui %}
5
+ <div data-tw-quick-create>
6
+ {% call(part) ui.dropdown(width='w-64') %}
7
+ {% if part == 'trigger' %}
8
+ <button type="button" class="{{ ui.button_classes('primary') }}" aria-haspopup="menu" title="{{ __('Quick create') }}"
9
+ aria-label="{{ label or __('Quick create') }}"{% if plugin.shortcut %} data-tw-keys="{{ plugin.shortcut }}"{% endif %}>
10
+ {{ icon(plugin.icon, 'h-4 w-4') }}{% if label %}<span class="hidden md:block">{{ label }}</span>{% endif %}
11
+ </button>
12
+ {% else %}
13
+ <div x-data="{ q: '', m(t) { const q = this.q.toLowerCase().trim(); return !q || t.includes(q); } }" role="menu">
14
+ {% if count >= plugin.search_from %}
15
+ <div class="p-1">
16
+ <input type="search" x-model="q" placeholder="{{ __('Search...') }}" aria-label="{{ __('Search') }}" autocomplete="off"
17
+ @keydown.enter.prevent="const b = $el.closest('[role=menu]').querySelector('[data-tw-qc-item]:not([style*=\'display: none\'])'); b && b.click()"
18
+ x-init="$watch('open', v => v ? $nextTick(() => $el.focus()) : (q = ''))"
19
+ class="w-full rounded-md border-0 bg-gray-50 px-3 py-2 text-sm ring-1 ring-inset ring-gray-950/10 dark:bg-white/5 dark:ring-white/10">
20
+ </div>
21
+ {% endif %}
22
+ <div style="max-height: 24rem; overflow-y: auto;">
23
+ {% for group_label, items in groups %}
24
+ <div x-show="{{ items | map(attribute='label') | map('lower') | list | tojson | forceescape }}.some(t => m(t))">
25
+ {% if group_label %}<p class="px-2 pb-1 pt-2 text-xs font-semibold uppercase tracking-wide text-gray-400">{{ group_label }}</p>{% endif %}
26
+ {% for item in items %}
27
+ {% set needle = item.label | lower | tojson %}
28
+ {% if item.modal_url %}
29
+ <button type="button" role="menuitem" data-tw-qc-item class="{{ ui.button_classes('gray', 'dropdown') }}"
30
+ x-show="m({{ needle | forceescape }})"
31
+ hx-get="{{ item.modal_url }}" hx-target="#tw-modal" hx-swap="innerHTML">
32
+ {{ icon(item.icon, 'h-4 w-4 text-gray-400') }}<span class="flex-1 truncate">{{ item.label }}</span>
33
+ </button>
34
+ {% else %}
35
+ <a href="{{ item.url }}" role="menuitem" data-tw-qc-item class="{{ ui.button_classes('gray', 'dropdown') }}"
36
+ x-show="m({{ needle | forceescape }})">
37
+ {{ icon(item.icon, 'h-4 w-4 text-gray-400') }}<span class="flex-1 truncate">{{ item.label }}</span>
38
+ </a>
39
+ {% endif %}
40
+ {% endfor %}
41
+ </div>
42
+ {% endfor %}
43
+ </div>
44
+ {% if count >= plugin.search_from %}
45
+ <p x-show="!{{ all_labels | tojson | forceescape }}.some(t => m(t))" x-cloak
46
+ class="px-3 py-3 text-center text-sm text-gray-500">{{ __('No matches') }}</p>
47
+ {% endif %}
48
+ </div>
49
+ {% endif %}
50
+ {% endcall %}
51
+ </div>
@@ -0,0 +1,174 @@
1
+ """A tiny panel with a few resources and the quick create plugin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ import pytest
8
+ from fastapi import FastAPI
9
+ from fastapi.testclient import TestClient
10
+ from sqlalchemy import Boolean, String, create_engine
11
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
12
+ from tungsten_quick_create import QuickCreatePlugin
13
+
14
+ from tungsten import Auth, Panel, Resource, hash_password
15
+ from tungsten.forms import TextInput
16
+ from tungsten.forms.form import ValidationError
17
+
18
+
19
+ class PanelClient:
20
+ """TestClient that sends the CSRF token and HTMX headers, like the browser does."""
21
+
22
+ def __init__(self, client: TestClient) -> None:
23
+ self.client = client
24
+ self.token: str | None = None
25
+
26
+ def get(self, url: str, htmx: bool = False, **kw):
27
+ headers = {"HX-Request": "true"} if htmx else {}
28
+ r = self.client.get(url, headers=headers, **kw)
29
+ m = re.search(r'"X-CSRF-Token": "([^"]+)"', r.text) or re.search(r'name="_token" value="([^"]+)"', r.text)
30
+ if m:
31
+ self.token = m.group(1)
32
+ return r
33
+
34
+ def post(self, url: str, data=None, **kw):
35
+ headers = {"HX-Request": "true", **({"X-CSRF-Token": self.token} if self.token else {})}
36
+ return self.client.post(url, data=data, headers=headers, **kw)
37
+
38
+ def login(self, email: str = "admin@example.com", password: str = "password"):
39
+ self.get("/admin/login")
40
+ return self.client.post("/admin/login", data={"_token": self.token, "email": email, "password": password},
41
+ follow_redirects=False)
42
+
43
+
44
+ class Base(DeclarativeBase):
45
+ pass
46
+
47
+
48
+ class User(Base):
49
+ __tablename__ = "users"
50
+
51
+ id: Mapped[int] = mapped_column(primary_key=True)
52
+ name: Mapped[str] = mapped_column(String(100))
53
+ email: Mapped[str] = mapped_column(String(200), unique=True)
54
+ password: Mapped[str] = mapped_column(String(200))
55
+ is_active: Mapped[bool] = mapped_column(Boolean, default=True)
56
+
57
+
58
+ class Product(Base):
59
+ __tablename__ = "products"
60
+
61
+ id: Mapped[int] = mapped_column(primary_key=True)
62
+ name: Mapped[str] = mapped_column(String(100), unique=True)
63
+ sku: Mapped[str | None] = mapped_column(String(40), nullable=True)
64
+
65
+
66
+ class Note(Base):
67
+ __tablename__ = "notes"
68
+
69
+ id: Mapped[int] = mapped_column(primary_key=True)
70
+ text: Mapped[str] = mapped_column(String(200))
71
+
72
+
73
+ class Log(Base):
74
+ __tablename__ = "logs"
75
+
76
+ id: Mapped[int] = mapped_column(primary_key=True)
77
+ line: Mapped[str] = mapped_column(String(200))
78
+
79
+
80
+ class AdminsOnly:
81
+ """Only the admin may create; everyone may look."""
82
+
83
+ @staticmethod
84
+ def view_any(user):
85
+ return True
86
+
87
+ @staticmethod
88
+ def create(user):
89
+ return user is not None and user.email == "admin@example.com"
90
+
91
+
92
+ class ProductResource(Resource):
93
+ model = Product
94
+ icon = "package"
95
+ navigation_group = "Shop"
96
+ policy = AdminsOnly
97
+
98
+ @classmethod
99
+ def form(cls, form):
100
+ return form.schema([TextInput("name").required(), TextInput("sku")])
101
+
102
+ @classmethod
103
+ def before_create(cls, data):
104
+ if data.get("sku") == "BAD":
105
+ raise ValidationError({"sku": ["This SKU is blocked."]})
106
+
107
+
108
+ class NoteResource(Resource):
109
+ """A modal-only resource: it still has a create form."""
110
+
111
+ model = Note
112
+ icon = "sticky-note"
113
+ simple = True
114
+
115
+ @classmethod
116
+ def form(cls, form):
117
+ return form.schema([TextInput("text").required()])
118
+
119
+
120
+ class LogResource(Resource):
121
+ """Read-only: no create page, so never in the menu."""
122
+
123
+ model = Log
124
+ pages = ("index",)
125
+
126
+
127
+ class HiddenResource(Resource):
128
+ model = Log
129
+ slug = "hidden-logs"
130
+ quick_create = False
131
+
132
+
133
+ @pytest.fixture()
134
+ def make_panel(tmp_path):
135
+ def build(**options):
136
+ engine = create_engine(f"sqlite:///{tmp_path / 'qc.db'}")
137
+ Base.metadata.create_all(engine)
138
+ factory = sessionmaker(engine, expire_on_commit=False)
139
+ with factory() as db:
140
+ if db.query(User).count() == 0:
141
+ db.add(User(name="Asha Admin", email="admin@example.com", password=hash_password("password")))
142
+ db.add(User(name="Ravi Staff", email="ravi@example.com", password=hash_password("password")))
143
+ db.commit()
144
+ panel = Panel(path="/admin", session_factory=factory, secret_key="test", auth=Auth(User))
145
+ panel.resources([ProductResource, NoteResource, LogResource, HiddenResource])
146
+ panel.plugin(QuickCreatePlugin(**options))
147
+ panel.create_tables(engine)
148
+ panel.db = factory # type: ignore[attr-defined]
149
+ return panel
150
+
151
+ return build
152
+
153
+
154
+ @pytest.fixture()
155
+ def panel(make_panel):
156
+ return make_panel()
157
+
158
+
159
+ def client_for(panel) -> PanelClient:
160
+ app = FastAPI()
161
+ panel.mount(app)
162
+ return PanelClient(TestClient(app))
163
+
164
+
165
+ @pytest.fixture()
166
+ def client(panel):
167
+ return client_for(panel)
168
+
169
+
170
+ @pytest.fixture()
171
+ def admin(client):
172
+ assert client.login().status_code == 303
173
+ client.get("/admin/")
174
+ return client
@@ -0,0 +1,321 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ import pytest
6
+ from conftest import Note, Product, client_for
7
+ from tungsten_quick_create import QuickCreatePlugin
8
+
9
+
10
+ def toasts(response) -> list[dict]:
11
+ trigger = json.loads(response.headers.get("HX-Trigger") or "{}")
12
+ return trigger.get("tw-notify") or []
13
+
14
+
15
+ def events(response) -> dict:
16
+ return json.loads(response.headers.get("HX-Trigger") or "{}")
17
+
18
+
19
+ # ---------------------------------------------------------------------- the button
20
+ def test_button_lists_creatable_resources(admin):
21
+ html = admin.get("/admin/").text
22
+ assert "data-tw-quick-create" in html
23
+ assert "/admin/_quick-create/products" in html
24
+ assert "/admin/_quick-create/notes" in html # modal-only resources too
25
+ assert "/admin/_quick-create/logs" not in html # no create page
26
+ assert "/admin/_quick-create/hidden-logs" not in html # quick_create = False
27
+
28
+
29
+ def test_button_respects_permissions(client):
30
+ assert client.login("ravi@example.com").status_code == 303
31
+ html = client.get("/admin/").text
32
+ assert "/admin/_quick-create/products" not in html # policy says admins only
33
+ assert "/admin/_quick-create/notes" in html
34
+
35
+
36
+ def test_no_button_when_nothing_to_create(make_panel):
37
+ panel = make_panel(include=["products"])
38
+ client = client_for(panel)
39
+ client.login("ravi@example.com")
40
+ assert "data-tw-quick-create" not in client.get("/admin/").text
41
+
42
+
43
+ def test_signed_out_users_see_no_button_and_get_login(client):
44
+ r = client.get("/admin/_quick-create/products", follow_redirects=False)
45
+ assert r.status_code in (302, 303)
46
+ assert "/admin/login" in r.headers["location"]
47
+
48
+
49
+ def test_include_sets_the_order(make_panel):
50
+ panel = make_panel(include=["notes", "products", "missing"])
51
+ client = client_for(panel)
52
+ client.login()
53
+ html = client.get("/admin/").text
54
+ assert html.index("_quick-create/notes") < html.index("_quick-create/products")
55
+
56
+
57
+ def test_exclude_by_class_or_slug(make_panel):
58
+ from conftest import NoteResource
59
+
60
+ client = client_for(make_panel(exclude=[NoteResource, "products"]))
61
+ client.login()
62
+ assert "data-tw-quick-create" not in client.get("/admin/").text
63
+
64
+
65
+ def test_groups_and_search_box(make_panel):
66
+ client = client_for(make_panel(search_from=2))
67
+ client.login()
68
+ html = client.get("/admin/").text
69
+ assert "Shop" in html # products sit in the "Shop" group
70
+ assert 'x-model="q"' in html
71
+ client = client_for(make_panel(search_from=50, group=False))
72
+ client.login()
73
+ assert 'x-model="q"' not in client.get("/admin/").text
74
+
75
+
76
+ def test_bad_width_is_refused():
77
+ with pytest.raises(ValueError):
78
+ QuickCreatePlugin(width="huge")
79
+
80
+
81
+ # ---------------------------------------------------------------------- links from other plugins
82
+ def test_links_from_other_plugins(panel):
83
+ plugin = panel.get_plugin("quick-create")
84
+ plugin.add_link("event", "Event", "/admin/calendar?new=1", icon="calendar")
85
+ plugin.add_link("upload", "Upload file", lambda ctx: "/admin/media/upload")
86
+ plugin.add_link("secret", "Secret", "/admin/secret", visible=lambda user: user.email == "nobody@example.com")
87
+ plugin.add_link("broken", "Broken", lambda ctx: 1 / 0)
88
+ client = client_for(panel)
89
+ client.login()
90
+ html = client.get("/admin/").text
91
+ assert "/admin/calendar?new=1" in html
92
+ assert "/admin/media/upload" in html
93
+ assert "/admin/secret" not in html
94
+ assert "Broken" not in html # a failing link is skipped, the page still works
95
+ plugin.remove_link("event")
96
+ assert "/admin/calendar?new=1" not in client.get("/admin/").text
97
+
98
+
99
+ def test_app_shortcuts_for_the_installed_app(panel):
100
+ plugin = panel.get_plugin("quick-create")
101
+ plugin.add_link("event", "Event", "/admin/calendar?new=1")
102
+ plugin.add_link("upload", "Upload file", lambda ctx: "/admin/media/upload") # needs a request: skipped
103
+ shortcuts = plugin.pwa_shortcuts(panel)
104
+ # modal-only notes have no create page to open from the home screen
105
+ assert shortcuts == [{"name": "New Product", "url": "/admin/products/create"},
106
+ {"name": "Event", "url": "/admin/calendar?new=1"}]
107
+ plugin.pwa_shortcut_limit = 1
108
+ assert len(plugin.pwa_shortcuts(panel)) == 1
109
+
110
+
111
+ def test_app_shortcuts_reach_the_pwa_manifest(panel):
112
+ pytest.importorskip("tungsten_pwa")
113
+ from tungsten_pwa import PWAPlugin
114
+
115
+ panel.plugin(PWAPlugin())
116
+ manifest = client_for(panel).get("/admin/_tw/pwa/manifest.webmanifest").json()
117
+ assert {"name": "New Product", "url": "/admin/products/create"} == {
118
+ k: manifest["shortcuts"][0][k] for k in ("name", "url")}
119
+
120
+
121
+ # ---------------------------------------------------------------------- the form
122
+ def test_open_form_in_side_panel(admin):
123
+ r = admin.get("/admin/_quick-create/products", htmx=True)
124
+ assert r.status_code == 200
125
+ assert "tw-quick-create-form" in r.text
126
+ assert 'hx-post="/admin/_quick-create/products"' in r.text
127
+ assert "Create &amp; create another" in r.text or "Create & create another" in r.text
128
+ assert "justify-end" in r.text # slide over
129
+
130
+
131
+ def test_create_closes_and_refreshes(admin, panel):
132
+ r = admin.post("/admin/_quick-create/products", {"name": "Pen", "sku": "P-1"})
133
+ assert r.status_code == 200
134
+ ev = events(r)
135
+ assert "tw-close-modal" in ev and "tw-refresh" in ev
136
+ toast = toasts(r)[0]
137
+ assert toast["status"] == "success"
138
+ assert toast["actions"][0]["url"].startswith("/admin/products/")
139
+ with panel.db() as db:
140
+ assert db.query(Product).filter_by(name="Pen").one().sku == "P-1"
141
+
142
+
143
+ def test_validation_errors_keep_the_form_open(admin, panel):
144
+ r = admin.post("/admin/_quick-create/products", {"name": "", "sku": "X"})
145
+ assert r.status_code == 200
146
+ assert "tw-quick-create-form" in r.text
147
+ assert 'value="X"' in r.text # typed data is kept
148
+ with panel.db() as db:
149
+ assert db.query(Product).count() == 0
150
+
151
+
152
+ def test_hook_validation_error_shows_on_the_field(admin, panel):
153
+ r = admin.post("/admin/_quick-create/products", {"name": "Pen", "sku": "BAD"})
154
+ assert "This SKU is blocked." in r.text
155
+ with panel.db() as db:
156
+ assert db.query(Product).count() == 0
157
+
158
+
159
+ def test_database_error_is_a_toast_not_a_crash(admin, panel):
160
+ admin.post("/admin/_quick-create/products", {"name": "Pen"})
161
+ r = admin.post("/admin/_quick-create/products", {"name": "Pen"}) # unique name
162
+ assert r.status_code == 200
163
+ assert toasts(r)[0]["status"] == "danger"
164
+ assert "tw-quick-create-form" in r.text
165
+ with panel.db() as db:
166
+ assert db.query(Product).count() == 1
167
+
168
+
169
+ def test_create_another_reopens_an_empty_form(admin, panel):
170
+ r = admin.post("/admin/_quick-create/notes", {"text": "first", "_tw_another": "1"})
171
+ assert "tw-close-modal" not in events(r)
172
+ assert "tw-refresh" in events(r)
173
+ assert "tw-quick-create-form" in r.text and "first" not in r.text
174
+ with panel.db() as db:
175
+ assert db.query(Note).count() == 1
176
+
177
+
178
+ def test_simple_resource_has_no_record_link(admin):
179
+ r = admin.post("/admin/_quick-create/notes", {"text": "hello"})
180
+ assert not toasts(r)[0].get("actions")
181
+
182
+
183
+ def test_open_after_create_goes_to_the_record(make_panel):
184
+ client = client_for(make_panel(open_after_create=True))
185
+ client.login()
186
+ client.get("/admin/")
187
+ r = client.post("/admin/_quick-create/products", {"name": "Pen"})
188
+ assert r.headers["HX-Redirect"].startswith("/admin/products/")
189
+
190
+
191
+ def test_forbidden_and_unknown(client):
192
+ client.login("ravi@example.com")
193
+ client.get("/admin/")
194
+ r = client.get("/admin/_quick-create/products", htmx=True)
195
+ assert r.status_code == 204 and toasts(r)[0]["status"] == "danger"
196
+ r = client.post("/admin/_quick-create/products", {"name": "Sneaky"})
197
+ assert r.status_code == 204
198
+ for slug in ("logs", "hidden-logs", "nope"):
199
+ assert client.get(f"/admin/_quick-create/{slug}", htmx=True).status_code == 204
200
+
201
+
202
+ def test_post_needs_csrf(admin, panel):
203
+ admin.token = "wrong"
204
+ r = admin.post("/admin/_quick-create/products", {"name": "Pen"})
205
+ assert r.status_code == 419
206
+ with panel.db() as db:
207
+ assert db.query(Product).count() == 0
208
+
209
+
210
+ def test_live_form_refresh_works_in_the_panel(admin):
211
+ """Fields that update live post to the core form endpoint with the resource as host."""
212
+ r = admin.post("/admin/_tw/form", {"_tw_kind": "host", "_tw_host": "resource:products", "_tw_op": "create",
213
+ "_tw_record": "", "_tw_form_id": "tw-quick-create-form", "name": "Pen"})
214
+ assert r.status_code == 200
215
+ assert 'id="tw-quick-create-form"' in r.text
216
+
217
+
218
+ def test_broken_policy_hides_only_that_entry(make_panel):
219
+ from conftest import NoteResource
220
+
221
+ class Boom:
222
+ @staticmethod
223
+ def create(user):
224
+ raise RuntimeError("policy bug")
225
+
226
+ NoteResource.policy = Boom
227
+ try:
228
+ client = client_for(make_panel())
229
+ client.login()
230
+ html = client.get("/admin/").text
231
+ assert "_quick-create/products" in html
232
+ assert "_quick-create/notes" not in html
233
+ finally:
234
+ NoteResource.policy = None
235
+
236
+
237
+ # ---------------------------------------------------------------------- with other plugins
238
+ OFFICIAL = [("tungsten_leads", "LeadsPlugin"), ("tungsten_tickets", "TicketsPlugin"), ("tungsten_hr", "HRPlugin"),
239
+ ("tungsten_finance", "FinancePlugin"), ("tungsten_blog", "BlogPlugin"),
240
+ ("tungsten_seo_audit", "SeoAuditPlugin"), ("tungsten_security_audit", "SecurityAuditPlugin")]
241
+
242
+
243
+ @pytest.fixture()
244
+ def full_panel(make_panel):
245
+ import importlib
246
+
247
+ panel = make_panel()
248
+ added = []
249
+ for module, name in OFFICIAL:
250
+ try:
251
+ plugin_class = getattr(importlib.import_module(module), name)
252
+ except ImportError:
253
+ continue
254
+ panel.plugin(plugin_class())
255
+ added.append(module)
256
+ if not added:
257
+ pytest.skip("no other official plugins installed")
258
+ panel.create_tables(panel.db.kw["bind"])
259
+ return panel
260
+
261
+
262
+ def test_every_official_plugin_form_opens(full_panel):
263
+ client = client_for(full_panel)
264
+ client.login()
265
+ html = client.get("/admin/").text
266
+ slugs = [r.get_slug() for r in full_panel.get_plugin("quick-create").resources()]
267
+ assert len(slugs) > 5
268
+ for slug in slugs:
269
+ assert f"/admin/_quick-create/{slug}" in html
270
+ r = client.get(f"/admin/_quick-create/{slug}", htmx=True)
271
+ assert r.status_code == 200, slug
272
+ assert "tw-quick-create-form" in r.text, slug
273
+
274
+
275
+ def test_create_ticket_and_lead_from_anywhere(full_panel):
276
+ pytest.importorskip("tungsten_tickets")
277
+ pytest.importorskip("tungsten_leads")
278
+ from tungsten_leads import Lead
279
+ from tungsten_tickets import Ticket
280
+
281
+ client = client_for(full_panel)
282
+ client.login()
283
+ client.get("/admin/")
284
+ r = client.post("/admin/_quick-create/tickets", {"subject": "Printer broken", "status": "open",
285
+ "priority": "normal"})
286
+ assert toasts(r)[0]["status"] == "success", r.text[:500]
287
+ r = client.post("/admin/_quick-create/leads", {"name": "Meena", "status": "new", "source": "website"})
288
+ assert toasts(r)[0]["status"] == "success", r.text[:500]
289
+ with full_panel.db() as db:
290
+ ticket = db.query(Ticket).one()
291
+ assert ticket.number and ticket.due_at is not None # the plugin's own hooks ran
292
+ assert db.query(Lead).one().name == "Meena"
293
+
294
+
295
+ def test_live_note_with_environment_indicator(make_panel):
296
+ from tungsten import Plugin
297
+
298
+ class Env:
299
+ def __init__(self, live):
300
+ self.is_production, self.label = live, "Live" if live else "Local"
301
+
302
+ class FakeIndicator(Plugin):
303
+ id = "environment-indicator"
304
+ live = True
305
+
306
+ def current(self, ctx=None):
307
+ return Env(self.live)
308
+
309
+ panel = make_panel()
310
+ indicator = FakeIndicator()
311
+ panel.plugin(indicator)
312
+ client = client_for(panel)
313
+ assert client.login().status_code == 303
314
+ client.get("/admin/")
315
+ assert "This record goes into real data" in client.get("/admin/_quick-create/products", htmx=True).text
316
+ indicator.live = False
317
+ assert "real data" not in client.get("/admin/_quick-create/products", htmx=True).text
318
+
319
+
320
+ def test_no_live_note_without_indicator(admin):
321
+ assert "real data" not in admin.get("/admin/_quick-create/products", htmx=True).text