tungsten-quick-create 0.1.0__py3-none-any.whl

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,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,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,5 @@
1
+ tungsten_quick_create/__init__.py,sha256=2urXYzhbaH7ugUm0yAbIy8-l6P1JFJl79X2Bv1Sa3ZU,14442
2
+ tungsten_quick_create/templates/tungsten_quick_create/button.html,sha256=n0_r07rPPZCp9T2eBtsEvB9pfbHA5sUYDP9F4k6VlZ8,2885
3
+ tungsten_quick_create-0.1.0.dist-info/METADATA,sha256=CYehNkvTQhPSRdsdJKp5MPpxwEonfLQt8SOY58yKgcQ,3654
4
+ tungsten_quick_create-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
5
+ tungsten_quick_create-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any