django-snapnote 0.3.0__tar.gz → 0.5.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.
Files changed (80) hide show
  1. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/CHANGELOG.md +11 -0
  2. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/PKG-INFO +20 -1
  3. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/README.md +19 -0
  4. django_snapnote-0.5.0/src/snapnote/__init__.py +1 -0
  5. django_snapnote-0.5.0/src/snapnote/admin.py +24 -0
  6. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/conf.py +12 -0
  7. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/forms.py +12 -1
  8. django_snapnote-0.5.0/src/snapnote/locale/es/LC_MESSAGES/django.mo +0 -0
  9. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/locale/es/LC_MESSAGES/django.po +18 -0
  10. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/management/commands/snapnote_export.py +4 -0
  11. django_snapnote-0.5.0/src/snapnote/management/commands/snapnote_retry_jira.py +36 -0
  12. django_snapnote-0.5.0/src/snapnote/migrations/0002_ticket_jira_key.py +19 -0
  13. django_snapnote-0.5.0/src/snapnote/migrations/0003_ticket_jira_error.py +17 -0
  14. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/models.py +28 -1
  15. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/notifiers.py +37 -4
  16. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/templates/snapnote/ticket_detail.html +12 -0
  17. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/templates/snapnote/ticket_list.html +4 -3
  18. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/urls.py +1 -0
  19. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/views.py +26 -0
  20. django_snapnote-0.5.0/tests/test_jira.py +306 -0
  21. django_snapnote-0.3.0/src/snapnote/__init__.py +0 -1
  22. django_snapnote-0.3.0/src/snapnote/admin.py +0 -12
  23. django_snapnote-0.3.0/src/snapnote/locale/es/LC_MESSAGES/django.mo +0 -0
  24. django_snapnote-0.3.0/tests/test_jira.py +0 -98
  25. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/.gitignore +0 -0
  26. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/LICENSE +0 -0
  27. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/e2e/smoke.mjs +0 -0
  28. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/package-lock.json +0 -0
  29. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/package.json +0 -0
  30. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/AnnotationEditor.tsx +0 -0
  31. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/App.tsx +0 -0
  32. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/api.test.ts +0 -0
  33. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/api.ts +0 -0
  34. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/capture.ts +0 -0
  35. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/drawing.test.ts +0 -0
  36. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/drawing.ts +0 -0
  37. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/icons.tsx +0 -0
  38. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/main.tsx +0 -0
  39. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/styles.css +0 -0
  40. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/types.ts +0 -0
  41. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/src/vite-env.d.ts +0 -0
  42. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/tsconfig.json +0 -0
  43. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/frontend/vite.config.ts +0 -0
  44. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/pyproject.toml +0 -0
  45. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/apps.py +0 -0
  46. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/checks.py +0 -0
  47. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/claude/ticket.md +0 -0
  48. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/management/__init__.py +0 -0
  49. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/management/commands/__init__.py +0 -0
  50. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/management/commands/snapnote_install_claude_command.py +0 -0
  51. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/management/commands/snapnote_purge.py +0 -0
  52. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/middleware.py +0 -0
  53. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/migrations/0001_initial.py +0 -0
  54. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/migrations/__init__.py +0 -0
  55. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/permissions.py +0 -0
  56. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/signals.py +0 -0
  57. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/static/snapnote/management.css +0 -0
  58. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/static/snapnote/snapnote.js +0 -0
  59. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/templates/snapnote/base.html +0 -0
  60. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/templates/snapnote/button.html +0 -0
  61. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/templates/snapnote/includes/status_badge.html +0 -0
  62. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/templates/snapnote/ticket_confirm_delete.html +0 -0
  63. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/templatetags/__init__.py +0 -0
  64. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/src/snapnote/templatetags/snapnote_tags.py +0 -0
  65. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/__init__.py +0 -0
  66. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/conftest.py +0 -0
  67. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/helpers.py +0 -0
  68. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/test_button.py +0 -0
  69. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/test_claude_command.py +0 -0
  70. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/test_export.py +0 -0
  71. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/test_management.py +0 -0
  72. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/test_report.py +0 -0
  73. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/testproject/__init__.py +0 -0
  74. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/testproject/hostapp/__init__.py +0 -0
  75. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/testproject/hostapp/apps.py +0 -0
  76. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/testproject/hostapp/models.py +0 -0
  77. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/testproject/settings.py +0 -0
  78. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/testproject/templates/alt_base.html +0 -0
  79. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/testproject/templates/host_base.html +0 -0
  80. {django_snapnote-0.3.0 → django_snapnote-0.5.0}/tests/testproject/urls.py +0 -0
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ - Jira failures are visible: `Ticket.jira_error` (migration `0003`), a "Jira failed" badge in the list and detail,
6
+ a Jira filter in the list and admin, a **Retry Jira** button and `manage.py snapnote_retry_jira`.
7
+ - New setting `SNAPNOTE_BASE_URL`.
8
+
9
+ ## 0.4.0
10
+
11
+ - The Jira notifier stores the issue key in `Ticket.jira_key` (new migration `0002`). It is shown, with a link, in the
12
+ list and detail views and the admin, is searchable, and is included in `snapnote_export`.
13
+
3
14
  ## 0.3.0
4
15
 
5
16
  - `snapnote_install_claude_command`: installs a `/ticket` command for Claude Code (fetch the ticket, fix it, open a PR).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: django-snapnote
3
- Version: 0.3.0
3
+ Version: 0.5.0
4
4
  Summary: Report problems from any page of a Django site: screenshot, annotations and a ticket list.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -62,6 +62,7 @@ Then `python manage.py migrate`. Uploaded images use your `MEDIA_ROOT`/storage.
62
62
  | `SNAPNOTE_MAX_DIMENSION` | `8000` | Max width/height in pixels |
63
63
  | `SNAPNOTE_UPLOAD_TO` | `"snapnote/"` | Prefix in the storage |
64
64
  | `SNAPNOTE_THROTTLE` | `"10/hour"` | Reports per user (`second`, `minute`, `hour`, `day`); uses Django's cache. `None` disables |
65
+ | `SNAPNOTE_BASE_URL` | `""` | Public site URL used to link tickets from Jira issues created by `snapnote_retry_jira` |
65
66
  | `SNAPNOTE_AUTO_INJECT` | `False` | Also add `snapnote.middleware.AutoInjectMiddleware` to `MIDDLEWARE` to insert the button automatically. Incompatible with strict CSP and streaming responses |
66
67
 
67
68
  Customise the look by overriding CSS variables on `#snapnote-root`
@@ -102,6 +103,24 @@ SNAPNOTE_JIRA_PROJECT = "APP" # project key
102
103
  # SNAPNOTE_JIRA_ATTACH_IMAGES = True, SNAPNOTE_JIRA_TIMEOUT = 10
103
104
  ```
104
105
 
106
+ The issue key is saved in `Ticket.jira_key` as soon as Jira creates the issue (even if an attachment
107
+ fails later), shown with a link in the views and admin, and exported by `snapnote_export`.
108
+ Tickets created before enabling the notifier have no key.
109
+
110
+ If Jira fails, the ticket is still created and the error is stored (without credentials, max 300
111
+ characters) in `Ticket.jira_error`: the list and detail views show a "Jira failed" badge with the
112
+ error, the admin has a Jira filter, and users with `change_ticket` get a **Retry Jira** button in the
113
+ detail view. To retry in bulk (for example after a Jira outage):
114
+
115
+ ```bash
116
+ python manage.py snapnote_retry_jira [--dry-run]
117
+ ```
118
+
119
+ Set `SNAPNOTE_BASE_URL = "https://your-site.example.com"` so those issues link back to the ticket.
120
+ A retry never creates a second issue for a ticket that already has a key. If the issue is created but
121
+ an attachment fails, the key is kept and the error is shown next to it. Failures that happened before
122
+ this was recorded (versions up to 0.4.0) cannot be retried automatically.
123
+
105
124
  `manage.py check` warns (`snapnote.W002`) if a required setting is missing. Use a dedicated
106
125
  Jira account with access only to that project. Notifiers run synchronously after commit with the
107
126
  timeout above; for heavy use, wrap it in your own task queue. Screenshots may contain sensitive
@@ -42,6 +42,7 @@ Then `python manage.py migrate`. Uploaded images use your `MEDIA_ROOT`/storage.
42
42
  | `SNAPNOTE_MAX_DIMENSION` | `8000` | Max width/height in pixels |
43
43
  | `SNAPNOTE_UPLOAD_TO` | `"snapnote/"` | Prefix in the storage |
44
44
  | `SNAPNOTE_THROTTLE` | `"10/hour"` | Reports per user (`second`, `minute`, `hour`, `day`); uses Django's cache. `None` disables |
45
+ | `SNAPNOTE_BASE_URL` | `""` | Public site URL used to link tickets from Jira issues created by `snapnote_retry_jira` |
45
46
  | `SNAPNOTE_AUTO_INJECT` | `False` | Also add `snapnote.middleware.AutoInjectMiddleware` to `MIDDLEWARE` to insert the button automatically. Incompatible with strict CSP and streaming responses |
46
47
 
47
48
  Customise the look by overriding CSS variables on `#snapnote-root`
@@ -82,6 +83,24 @@ SNAPNOTE_JIRA_PROJECT = "APP" # project key
82
83
  # SNAPNOTE_JIRA_ATTACH_IMAGES = True, SNAPNOTE_JIRA_TIMEOUT = 10
83
84
  ```
84
85
 
86
+ The issue key is saved in `Ticket.jira_key` as soon as Jira creates the issue (even if an attachment
87
+ fails later), shown with a link in the views and admin, and exported by `snapnote_export`.
88
+ Tickets created before enabling the notifier have no key.
89
+
90
+ If Jira fails, the ticket is still created and the error is stored (without credentials, max 300
91
+ characters) in `Ticket.jira_error`: the list and detail views show a "Jira failed" badge with the
92
+ error, the admin has a Jira filter, and users with `change_ticket` get a **Retry Jira** button in the
93
+ detail view. To retry in bulk (for example after a Jira outage):
94
+
95
+ ```bash
96
+ python manage.py snapnote_retry_jira [--dry-run]
97
+ ```
98
+
99
+ Set `SNAPNOTE_BASE_URL = "https://your-site.example.com"` so those issues link back to the ticket.
100
+ A retry never creates a second issue for a ticket that already has a key. If the issue is created but
101
+ an attachment fails, the key is kept and the error is shown next to it. Failures that happened before
102
+ this was recorded (versions up to 0.4.0) cannot be retried automatically.
103
+
85
104
  `manage.py check` warns (`snapnote.W002`) if a required setting is missing. Use a dedicated
86
105
  Jira account with access only to that project. Notifiers run synchronously after commit with the
87
106
  timeout above; for heavy use, wrap it in your own task queue. Screenshots may contain sensitive
@@ -0,0 +1 @@
1
+ __version__ = "0.5.0"
@@ -0,0 +1,24 @@
1
+ from django.contrib import admin
2
+ from django.utils.translation import gettext_lazy as _
3
+
4
+ from .models import Ticket
5
+
6
+
7
+ class JiraFilter(admin.SimpleListFilter):
8
+ title = "Jira"
9
+ parameter_name = "jira"
10
+
11
+ def lookups(self, request, model_admin):
12
+ return [("ok", _("In Jira")), ("failed", _("Jira failed")), ("none", _("No Jira"))]
13
+
14
+ def queryset(self, request, queryset):
15
+ return queryset.jira(self.value())
16
+
17
+
18
+ @admin.register(Ticket)
19
+ class TicketAdmin(admin.ModelAdmin):
20
+ list_display = ("id", "title", "status", "jira_key", "jira_error", "reported_by", "created_at")
21
+ list_filter = ("status", JiraFilter, "created_at")
22
+ search_fields = ("title", "description", "page_url", "jira_key")
23
+ raw_id_fields = ("reported_by", "closed_by")
24
+ readonly_fields = ("created_at", "updated_at")
@@ -22,6 +22,9 @@ DEFAULTS = {
22
22
  "JIRA_LABELS": ["snapnote"],
23
23
  "JIRA_ATTACH_IMAGES": True,
24
24
  "JIRA_TIMEOUT": 10,
25
+ # Public site URL (e.g. "https://intranet.example.com"), used to link tickets from Jira issues
26
+ # created outside a request (snapnote_retry_jira).
27
+ "BASE_URL": "",
25
28
  }
26
29
 
27
30
 
@@ -32,3 +35,12 @@ def get(name):
32
35
  def get_callable(name):
33
36
  value = get(name)
34
37
  return import_string(value) if isinstance(value, str) else value
38
+
39
+
40
+ JIRA_NOTIFIER = "snapnote.notifiers.jira_issue"
41
+ JIRA_REQUIRED = ("JIRA_URL", "JIRA_EMAIL", "JIRA_API_TOKEN", "JIRA_PROJECT")
42
+
43
+
44
+ def jira_enabled():
45
+ """True if the Jira notifier is active and fully configured."""
46
+ return JIRA_NOTIFIER in get("NOTIFIERS") and all(get(name) for name in JIRA_REQUIRED)
@@ -74,10 +74,21 @@ class TicketFilterForm(forms.Form):
74
74
  label=_("Status"), required=False, choices=[("", _("All"))] + Ticket.Status.choices
75
75
  )
76
76
 
77
+ jira = forms.ChoiceField(
78
+ label="Jira",
79
+ required=False,
80
+ choices=[
81
+ ("", _("All")),
82
+ ("ok", _("In Jira")),
83
+ ("failed", _("Jira failed")),
84
+ ("none", _("No Jira")),
85
+ ],
86
+ )
87
+
77
88
  def filter(self, queryset):
78
89
  if not self.is_valid():
79
90
  return queryset
80
- queryset = queryset.search(self.cleaned_data["q"])
91
+ queryset = queryset.search(self.cleaned_data["q"]).jira(self.cleaned_data["jira"])
81
92
  if self.cleaned_data["status"]:
82
93
  queryset = queryset.filter(status=self.cleaned_data["status"])
83
94
  return queryset
@@ -184,3 +184,21 @@ msgstr "Confirmar"
184
184
 
185
185
  msgid "Are you sure you want to delete \"%(object)s\"?"
186
186
  msgstr "¿Seguro que quieres eliminar \"%(object)s\"?"
187
+
188
+ msgid "Jira key"
189
+ msgstr "Clave de Jira"
190
+
191
+ msgid "Jira error"
192
+ msgstr "Error de Jira"
193
+
194
+ msgid "In Jira"
195
+ msgstr "En Jira"
196
+
197
+ msgid "Jira failed"
198
+ msgstr "Jira falló"
199
+
200
+ msgid "No Jira"
201
+ msgstr "Sin Jira"
202
+
203
+ msgid "Retry Jira"
204
+ msgstr "Reintentar Jira"
@@ -77,6 +77,8 @@ class Command(BaseCommand):
77
77
  "title": ticket.title,
78
78
  "status": ticket.status,
79
79
  "page_url": ticket.page_url,
80
+ "jira_key": ticket.jira_key or None,
81
+ "jira_error": ticket.jira_error or None,
80
82
  "reported_by": str(ticket.reported_by) if ticket.reported_by_id else None,
81
83
  "created_at": ticket.created_at.isoformat(),
82
84
  "closed_at": ticket.closed_at.isoformat() if ticket.closed_at else None,
@@ -87,6 +89,8 @@ class Command(BaseCommand):
87
89
 
88
90
  lines = [f"# Ticket #{ticket.pk}", "", NOTICE, "---", ""]
89
91
  lines += [f"- Status: {ticket.status}", f"- Page: {ticket.page_url}"]
92
+ if ticket.jira_key:
93
+ lines += [f"- Jira: {ticket.jira_key}"]
90
94
  lines += [
91
95
  f"- Reported by: {meta['reported_by'] or '-'}",
92
96
  f"- Created: {meta['created_at']}",
@@ -0,0 +1,36 @@
1
+ from django.core.management.base import BaseCommand, CommandError
2
+
3
+ from snapnote import conf
4
+ from snapnote.models import Ticket
5
+ from snapnote.notifiers import jira_issue
6
+
7
+
8
+ class Command(BaseCommand):
9
+ help = "Retries creating the Jira issue of tickets whose creation failed (see the Jira column)."
10
+
11
+ def add_arguments(self, parser):
12
+ parser.add_argument("--dry-run", action="store_true")
13
+
14
+ def handle(self, *args, dry_run, **options):
15
+ if not conf.jira_enabled():
16
+ raise CommandError(
17
+ "The Jira notifier is not enabled or not fully configured "
18
+ "(SNAPNOTE_NOTIFIERS and SNAPNOTE_JIRA_* settings)."
19
+ )
20
+ base = conf.get("BASE_URL").rstrip("/")
21
+ done = failed = 0
22
+ for ticket in Ticket.objects.jira("failed").order_by("pk"):
23
+ if dry_run:
24
+ self.stdout.write(f"Would retry ticket {ticket.pk}: {ticket.jira_error}")
25
+ continue
26
+ path = ticket.get_absolute_url() if conf.get("ENABLE_MANAGEMENT_VIEWS") else ""
27
+ try:
28
+ key = jira_issue(ticket, f"{base}{path}" if base and path else "")
29
+ except Exception:
30
+ failed += 1
31
+ self.stderr.write(f"Ticket {ticket.pk} failed again: {ticket.jira_error}")
32
+ else:
33
+ done += 1
34
+ self.stdout.write(f"Ticket {ticket.pk} -> {key}")
35
+ if not dry_run:
36
+ self.stdout.write(f"Created {done} issue(s), {failed} failed.")
@@ -0,0 +1,19 @@
1
+ # Generated by Django 5.2.19 on 2026-11-13 13:29
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+ dependencies = [
8
+ ("snapnote", "0001_initial"),
9
+ ]
10
+
11
+ operations = [
12
+ migrations.AddField(
13
+ model_name="ticket",
14
+ name="jira_key",
15
+ field=models.CharField(
16
+ blank=True, db_index=True, max_length=50, verbose_name="Jira key"
17
+ ),
18
+ ),
19
+ ]
@@ -0,0 +1,17 @@
1
+ # Generated by Django 5.2.19 on 2026-11-13 13:52
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+ dependencies = [
8
+ ("snapnote", "0002_ticket_jira_key"),
9
+ ]
10
+
11
+ operations = [
12
+ migrations.AddField(
13
+ model_name="ticket",
14
+ name="jira_error",
15
+ field=models.CharField(blank=True, max_length=300, verbose_name="Jira error"),
16
+ ),
17
+ ]
@@ -17,6 +17,16 @@ def annotations_upload_to(instance, filename):
17
17
 
18
18
 
19
19
  class TicketQuerySet(models.QuerySet):
20
+ def jira(self, status):
21
+ """Filters by Jira state: "ok" (issue created), "failed" or "none" (never attempted)."""
22
+ if status == "ok":
23
+ return self.exclude(jira_key="")
24
+ if status == "failed":
25
+ return self.filter(jira_key="").exclude(jira_error="")
26
+ if status == "none":
27
+ return self.filter(jira_key="", jira_error="")
28
+ return self
29
+
20
30
  def search(self, term):
21
31
  term = (term or "").strip()
22
32
  if not term:
@@ -32,7 +42,7 @@ class TicketQuerySet(models.QuerySet):
32
42
  ):
33
43
  lookup = "unaccent__icontains"
34
44
  query = models.Q()
35
- for field in ("title", "description", "page_url"):
45
+ for field in ("title", "description", "page_url", "jira_key"):
36
46
  query |= models.Q(**{f"{field}__{lookup}": term})
37
47
  return self.filter(query)
38
48
 
@@ -75,6 +85,10 @@ class Ticket(models.Model):
75
85
  blank=True,
76
86
  related_name="+",
77
87
  )
88
+ # Key of the Jira issue created by snapnote.notifiers.jira_issue (e.g. "APP-7").
89
+ jira_key = models.CharField(_("Jira key"), max_length=50, blank=True, db_index=True)
90
+ # Last error from the Jira notifier (empty when it worked or was never attempted).
91
+ jira_error = models.CharField(_("Jira error"), max_length=300, blank=True)
78
92
  created_at = models.DateTimeField(_("created at"), auto_now_add=True)
79
93
  updated_at = models.DateTimeField(_("updated at"), auto_now=True)
80
94
 
@@ -100,6 +114,19 @@ class Ticket(models.Model):
100
114
  path = parts.path or "/"
101
115
  return f"{path}?{parts.query}" if parts.query else path
102
116
 
117
+ @property
118
+ def jira_url(self):
119
+ """Link to the Jira issue, or "" if there is none or Jira is not configured."""
120
+ base = conf.get("JIRA_URL").rstrip("/")
121
+ return f"{base}/browse/{self.jira_key}" if self.jira_key and base else ""
122
+
123
+ @property
124
+ def jira_status(self):
125
+ """ "ok", "partial" (issue created but an attachment failed), "failed" or ""."""
126
+ if self.jira_key:
127
+ return "partial" if self.jira_error else "ok"
128
+ return "failed" if self.jira_error else ""
129
+
103
130
  @property
104
131
  def safe_page_url(self):
105
132
  """page_url if its scheme is http(s), else empty (never render javascript: links)."""
@@ -1,6 +1,7 @@
1
1
  import base64
2
2
  import json
3
3
  import logging
4
+ import urllib.error
4
5
  import urllib.request
5
6
  import uuid
6
7
 
@@ -34,7 +35,7 @@ def email(ticket, absolute_url):
34
35
  )
35
36
 
36
37
 
37
- JIRA_REQUIRED = ("JIRA_URL", "JIRA_EMAIL", "JIRA_API_TOKEN", "JIRA_PROJECT")
38
+ JIRA_REQUIRED = conf.JIRA_REQUIRED
38
39
 
39
40
 
40
41
  def _jira_request(path, data, content_type, extra_headers=None):
@@ -54,6 +55,24 @@ def _jira_request(path, data, content_type, extra_headers=None):
54
55
  return json.loads(response.read() or b"{}")
55
56
 
56
57
 
58
+ def short_error(exc):
59
+ """One short line describing a failure, safe to show to staff (no credentials)."""
60
+ if isinstance(exc, urllib.error.HTTPError):
61
+ try:
62
+ body = exc.read().decode(errors="replace")
63
+ except Exception:
64
+ body = ""
65
+ text = f"HTTP {exc.code}: {body}"
66
+ elif isinstance(exc, urllib.error.URLError):
67
+ text = f"Connection error: {exc.reason}"
68
+ else:
69
+ text = f"{type(exc).__name__}: {exc}"
70
+ for secret in (conf.get("JIRA_API_TOKEN"), conf.get("JIRA_EMAIL")):
71
+ if secret:
72
+ text = text.replace(secret, "***")
73
+ return " ".join(text.split())[:300]
74
+
75
+
57
76
  def _adf_paragraph(*parts):
58
77
  """A paragraph in Atlassian Document Format; parts are text or (text, url) links."""
59
78
  content = []
@@ -109,8 +128,18 @@ def jira_issue(ticket, absolute_url):
109
128
  "description": {"type": "doc", "version": 1, "content": blocks},
110
129
  }
111
130
  }
112
- issue = _jira_request("/rest/api/3/issue", json.dumps(payload).encode(), "application/json")
113
- key = issue["key"]
131
+ try:
132
+ issue = _jira_request("/rest/api/3/issue", json.dumps(payload).encode(), "application/json")
133
+ key = issue["key"]
134
+ except Exception as exc:
135
+ ticket.jira_error = short_error(exc)
136
+ ticket.save(update_fields=["jira_error"])
137
+ raise
138
+ # Saved right away: the attachments below are best effort and must not lose the key.
139
+ ticket.jira_key = key
140
+ ticket.jira_error = ""
141
+ ticket.save(update_fields=["jira_key", "jira_error"])
142
+ failures = []
114
143
  if conf.get("JIRA_ATTACH_IMAGES"):
115
144
  for name in ("screenshot", "annotations"):
116
145
  image = getattr(ticket, name)
@@ -127,11 +156,15 @@ def jira_issue(ticket, absolute_url):
127
156
  content_type,
128
157
  {"X-Atlassian-Token": "no-check"},
129
158
  )
130
- except Exception:
159
+ except Exception as exc:
131
160
  # The issue exists already; a missing image must not fail the notifier.
161
+ failures.append(f"{name}: {short_error(exc)}")
132
162
  logger.exception(
133
163
  "Could not attach %s of ticket %s to Jira issue %s", name, ticket.pk, key
134
164
  )
165
+ if failures:
166
+ ticket.jira_error = ("Attachments failed - " + "; ".join(failures))[:300]
167
+ ticket.save(update_fields=["jira_error"])
135
168
  return key
136
169
 
137
170
 
@@ -23,6 +23,18 @@
23
23
  <tr><th>{% trans "Reported by" %}</th><td>{{ ticket.reported_by|default:"-" }}</td></tr>
24
24
  <tr><th>{% trans "Created at" %}</th><td>{{ ticket.created_at }}</td></tr>
25
25
  {% if ticket.closed_at %}<tr><th>{% trans "Closed" %}</th><td>{{ ticket.closed_at }} ({{ ticket.closed_by|default:"-" }})</td></tr>{% endif %}
26
+ {% if ticket.jira_key or ticket.jira_error %}<tr><th>Jira</th><td>
27
+ {% if ticket.jira_key %}
28
+ {% if ticket.jira_url %}<a href="{{ ticket.jira_url }}" rel="noopener noreferrer">{{ ticket.jira_key }}</a>{% else %}{{ ticket.jira_key }}{% endif %}
29
+ {% if ticket.jira_error %}<span class="snapnote-badge snapnote-badge-open">{{ ticket.jira_error }}</span>{% endif %}
30
+ {% else %}
31
+ <span class="snapnote-badge snapnote-badge-open">{% trans "Jira failed" %}</span>
32
+ <code>{{ ticket.jira_error }}</code>
33
+ {% if perms.snapnote.change_ticket and jira_enabled %}
34
+ <form method="post" action="{% url 'snapnote:ticket_jira_retry' ticket.pk %}" style="display:inline">{% csrf_token %}<button class="snapnote-btn" type="submit">{% trans "Retry Jira" %}</button></form>
35
+ {% endif %}
36
+ {% endif %}
37
+ </td></tr>{% endif %}
26
38
  <tr><th>{% trans "Page" %}</th><td>{% if ticket.safe_page_url %}<a href="{{ ticket.safe_page_url }}" rel="noopener noreferrer">{{ ticket.page_url }}</a>{% else %}{{ ticket.page_url }}{% endif %}</td></tr>
27
39
  <tr><th>{% trans "Description" %}</th><td>{{ ticket.description|linebreaksbr|default:"-" }}</td></tr>
28
40
  </table>
@@ -5,13 +5,13 @@
5
5
  <div class="snapnote-wrap">
6
6
  <h1>{% trans "Tickets" %}</h1>
7
7
  <form method="get" class="snapnote-filter">
8
- {{ filter_form.q }} {{ filter_form.status }}
8
+ {{ filter_form.q }} {{ filter_form.status }}{% if jira_enabled %} {{ filter_form.jira }}{% endif %}
9
9
  <button type="submit" class="snapnote-btn">{% trans "Filter" %}</button>
10
10
  </form>
11
11
  <table class="snapnote-table">
12
12
  <thead><tr>
13
13
  <th>#</th><th>{% trans "Title" %}</th><th>{% trans "Page" %}</th>
14
- <th>{% trans "Reported by" %}</th><th>{% trans "Status" %}</th><th>{% trans "Created at" %}</th>
14
+ <th>Jira</th><th>{% trans "Reported by" %}</th><th>{% trans "Status" %}</th><th>{% trans "Created at" %}</th>
15
15
  </tr></thead>
16
16
  <tbody>
17
17
  {% for ticket in object_list %}
@@ -19,12 +19,13 @@
19
19
  <td>{{ ticket.pk }}</td>
20
20
  <td><a href="{{ ticket.get_absolute_url }}">{{ ticket.title }}</a></td>
21
21
  <td>{{ ticket.page_path }}</td>
22
+ <td>{% if ticket.jira_url %}<a href="{{ ticket.jira_url }}" rel="noopener noreferrer">{{ ticket.jira_key }}</a>{% elif ticket.jira_key %}{{ ticket.jira_key }}{% elif ticket.jira_error %}<span class="snapnote-badge snapnote-badge-open" title="{{ ticket.jira_error }}">{% trans "Jira failed" %}</span>{% else %}-{% endif %}</td>
22
23
  <td>{{ ticket.reported_by|default:"-" }}</td>
23
24
  <td>{% include "snapnote/includes/status_badge.html" %}</td>
24
25
  <td>{{ ticket.created_at }}</td>
25
26
  </tr>
26
27
  {% empty %}
27
- <tr><td colspan="6" class="snapnote-empty">{% trans "No tickets found." %}</td></tr>
28
+ <tr><td colspan="7" class="snapnote-empty">{% trans "No tickets found." %}</td></tr>
28
29
  {% endfor %}
29
30
  </tbody>
30
31
  </table>
@@ -10,5 +10,6 @@ urlpatterns = [
10
10
  path("<int:pk>/", views.TicketDetailView.as_view(), name="ticket_detail"),
11
11
  path("<int:pk>/close/", views.StatusChangeView.as_view(close=True), name="ticket_close"),
12
12
  path("<int:pk>/reopen/", views.StatusChangeView.as_view(close=False), name="ticket_reopen"),
13
+ path("<int:pk>/jira/retry/", views.JiraRetryView.as_view(), name="ticket_jira_retry"),
13
14
  path("<int:pk>/delete/", views.TicketDeleteView.as_view(), name="ticket_delete"),
14
15
  ]
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import time
2
3
 
3
4
  from django.contrib.auth.mixins import PermissionRequiredMixin
@@ -13,6 +14,8 @@ from .forms import TicketFilterForm, TicketReportForm
13
14
  from .models import Ticket
14
15
  from .signals import ticket_created
15
16
 
17
+ logger = logging.getLogger("snapnote")
18
+
16
19
  PERIODS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400}
17
20
 
18
21
 
@@ -74,6 +77,7 @@ class ManagementMixin(PermissionRequiredMixin):
74
77
  def get_context_data(self, **kwargs):
75
78
  context = super().get_context_data(**kwargs)
76
79
  context["snapnote_base_template"] = conf.get("BASE_TEMPLATE") or "snapnote/base.html"
80
+ context["jira_enabled"] = conf.jira_enabled()
77
81
  return context
78
82
 
79
83
 
@@ -121,3 +125,25 @@ class StatusChangeView(ManagementMixin, View):
121
125
  else:
122
126
  ticket.reopen()
123
127
  return HttpResponseRedirect(reverse("snapnote:ticket_detail", kwargs={"pk": ticket.pk}))
128
+
129
+
130
+ class JiraRetryView(ManagementMixin, View):
131
+ """Retries creating the Jira issue of a ticket whose creation failed."""
132
+
133
+ permission_required = "snapnote.change_ticket"
134
+ http_method_names = ["post"]
135
+
136
+ def post(self, request, pk):
137
+ from .notifiers import jira_issue
138
+
139
+ if not conf.jira_enabled():
140
+ raise Http404
141
+ ticket = get_object_or_404(Ticket, pk=pk)
142
+ if not ticket.jira_key: # never create a second issue for the same ticket
143
+ try:
144
+ jira_issue(ticket, request.build_absolute_uri(ticket.get_absolute_url()))
145
+ except Exception:
146
+ logger.exception(
147
+ "Jira retry failed for ticket %s", ticket.pk
148
+ ) # also stored in jira_error
149
+ return HttpResponseRedirect(reverse("snapnote:ticket_detail", kwargs={"pk": ticket.pk}))
@@ -0,0 +1,306 @@
1
+ import json
2
+ from unittest import mock
3
+
4
+ import pytest
5
+ from django.core.checks import run_checks
6
+
7
+ from snapnote import notifiers
8
+
9
+
10
+ @pytest.fixture
11
+ def jira(settings):
12
+ settings.SNAPNOTE_JIRA_URL = "https://acme.atlassian.net/"
13
+ settings.SNAPNOTE_JIRA_EMAIL = "bot@acme.com"
14
+ settings.SNAPNOTE_JIRA_API_TOKEN = "secret"
15
+ settings.SNAPNOTE_JIRA_PROJECT = "APP"
16
+
17
+
18
+ class FakeResponse:
19
+ def __init__(self, body):
20
+ self.body = body
21
+
22
+ def __enter__(self):
23
+ return self
24
+
25
+ def __exit__(self, *args):
26
+ return False
27
+
28
+ def read(self):
29
+ return json.dumps(self.body).encode()
30
+
31
+
32
+ def fake_urlopen(calls, fail_attachments=False):
33
+ def urlopen(request, timeout=None):
34
+ calls.append(request)
35
+ if "attachments" in request.full_url and fail_attachments:
36
+ raise OSError("boom")
37
+ return FakeResponse({"key": "APP-7"})
38
+
39
+ return urlopen
40
+
41
+
42
+ def test_creates_issue_and_attaches_images(jira, make_ticket, png):
43
+ ticket = make_ticket(
44
+ title="Broken", description="It fails", screenshot=png(), annotations=png("a.png")
45
+ )
46
+ calls = []
47
+ with mock.patch("urllib.request.urlopen", fake_urlopen(calls)):
48
+ key = notifiers.jira_issue(ticket, "http://testserver/snapnote/1/")
49
+ assert key == "APP-7"
50
+ ticket.refresh_from_db()
51
+ assert ticket.jira_key == "APP-7"
52
+ assert ticket.jira_url == "https://acme.atlassian.net/browse/APP-7"
53
+ create, shot, ann = calls
54
+ assert create.full_url == "https://acme.atlassian.net/rest/api/3/issue"
55
+ assert create.get_header("Authorization").startswith("Basic ")
56
+ fields = json.loads(create.data)["fields"]
57
+ assert fields["project"] == {"key": "APP"} and fields["issuetype"] == {"name": "Bug"}
58
+ assert fields["summary"] == "Broken" and fields["labels"] == ["snapnote"]
59
+ text = json.dumps(fields["description"])
60
+ assert "It fails" in text and "http://testserver/snapnote/1/" in text
61
+ assert shot.full_url.endswith("/issue/APP-7/attachments")
62
+ assert shot.get_header("X-atlassian-token") == "no-check"
63
+ assert ann.full_url.endswith("/issue/APP-7/attachments")
64
+
65
+
66
+ def test_no_attachments_when_disabled_or_absent(jira, settings, make_ticket, png):
67
+ settings.SNAPNOTE_JIRA_ATTACH_IMAGES = False
68
+ calls = []
69
+ with mock.patch("urllib.request.urlopen", fake_urlopen(calls)):
70
+ notifiers.jira_issue(make_ticket(screenshot=png()), "")
71
+ assert len(calls) == 1
72
+
73
+
74
+ def test_attachment_failure_does_not_fail_notifier(jira, make_ticket, png):
75
+ calls = []
76
+ with mock.patch("urllib.request.urlopen", fake_urlopen(calls, fail_attachments=True)):
77
+ assert notifiers.jira_issue(make_ticket(screenshot=png()), "") == "APP-7"
78
+
79
+
80
+ def test_javascript_page_url_is_not_a_link(jira, make_ticket):
81
+ calls = []
82
+ with mock.patch("urllib.request.urlopen", fake_urlopen(calls)):
83
+ notifiers.jira_issue(make_ticket(page_url="javascript:alert(1)"), "")
84
+ assert '"link"' not in calls[0].data.decode()
85
+
86
+
87
+ def test_jira_failure_is_contained_by_runner(jira, settings, make_ticket):
88
+ settings.SNAPNOTE_NOTIFIERS = ["snapnote.notifiers.jira_issue"]
89
+ with mock.patch("urllib.request.urlopen", side_effect=OSError("down")):
90
+ notifiers.run_notifiers(None, make_ticket(), "") # must not raise
91
+
92
+
93
+ def test_check_warns_when_misconfigured(settings):
94
+ settings.SNAPNOTE_NOTIFIERS = ["snapnote.notifiers.jira_issue"]
95
+ warnings = [m for m in run_checks() if m.id == "snapnote.W002"]
96
+ assert warnings and "SNAPNOTE_JIRA_URL" in warnings[0].hint
97
+
98
+
99
+ def test_check_silent_when_configured(jira, settings):
100
+ settings.SNAPNOTE_NOTIFIERS = ["snapnote.notifiers.jira_issue"]
101
+ assert not [m for m in run_checks() if m.id == "snapnote.W002"]
102
+
103
+
104
+ def test_key_is_saved_even_if_attachments_fail(jira, make_ticket, png):
105
+ ticket = make_ticket(screenshot=png())
106
+ with mock.patch("urllib.request.urlopen", fake_urlopen([], fail_attachments=True)):
107
+ notifiers.jira_issue(ticket, "")
108
+ ticket.refresh_from_db()
109
+ assert ticket.jira_key == "APP-7"
110
+
111
+
112
+ def test_no_key_when_jira_fails(jira, make_ticket):
113
+ ticket = make_ticket()
114
+ with mock.patch("urllib.request.urlopen", side_effect=OSError("down")):
115
+ notifiers.run_notifiers(None, ticket, "")
116
+ ticket.refresh_from_db()
117
+ assert ticket.jira_key == "" and ticket.jira_url == ""
118
+
119
+
120
+ def test_key_shown_in_views_admin_and_export(jira, manager_client, make_ticket, tmp_path):
121
+ from django.core.management import call_command
122
+
123
+ ticket = make_ticket(jira_key="APP-7")
124
+ link = 'href="https://acme.atlassian.net/browse/APP-7"'
125
+ assert link in manager_client.get(ticket.get_absolute_url()).content.decode()
126
+ assert link in manager_client.get("/snapnote/").content.decode()
127
+ assert list(type(ticket).objects.search("APP-7")) == [ticket]
128
+ call_command("snapnote_export", ticket.pk, output=str(tmp_path))
129
+ folder = tmp_path / f"ticket-{ticket.pk}"
130
+ assert "APP-7" in (folder / "ticket.md").read_text()
131
+ assert '"jira_key": "APP-7"' in (folder / "ticket.json").read_text()
132
+
133
+
134
+ # --- failure visibility and retry -------------------------------------------------------------
135
+
136
+
137
+ def http_error(code=500, body=b'{"errorMessages":["boom"]}'):
138
+ import io
139
+ import urllib.error
140
+
141
+ return urllib.error.HTTPError("https://x", code, "err", {}, io.BytesIO(body))
142
+
143
+
144
+ @pytest.fixture
145
+ def jira_on(jira, settings):
146
+ settings.SNAPNOTE_NOTIFIERS = ["snapnote.notifiers.jira_issue"]
147
+
148
+
149
+ def test_failure_is_recorded_without_credentials(jira, settings, make_ticket):
150
+ ticket = make_ticket()
151
+ body = b'{"errorMessages":["bad token secret for bot@acme.com"]}'
152
+ with mock.patch("urllib.request.urlopen", side_effect=http_error(401, body)):
153
+ with pytest.raises(Exception, match="401|err"):
154
+ notifiers.jira_issue(ticket, "")
155
+ ticket.refresh_from_db()
156
+ assert ticket.jira_status == "failed" and ticket.jira_key == ""
157
+ assert ticket.jira_error.startswith("HTTP 401")
158
+ assert "secret" not in ticket.jira_error.replace("bad token secret", "") # token never leaks
159
+ assert "bot@acme.com" not in ticket.jira_error
160
+ assert len(ticket.jira_error) <= 300
161
+
162
+
163
+ def test_connection_error_and_truncation(jira, make_ticket):
164
+ import urllib.error
165
+
166
+ ticket = make_ticket()
167
+ with mock.patch("urllib.request.urlopen", side_effect=urllib.error.URLError("x" * 1000)):
168
+ notifiers.run_notifiers # noqa: B018
169
+ with pytest.raises(urllib.error.URLError):
170
+ notifiers.jira_issue(ticket, "")
171
+ ticket.refresh_from_db()
172
+ assert ticket.jira_error.startswith("Connection error") and len(ticket.jira_error) == 300
173
+
174
+
175
+ def test_success_clears_a_previous_error(jira, make_ticket):
176
+ ticket = make_ticket(jira_error="HTTP 500: old")
177
+ with mock.patch("urllib.request.urlopen", fake_urlopen([])):
178
+ notifiers.jira_issue(ticket, "")
179
+ ticket.refresh_from_db()
180
+ assert ticket.jira_status == "ok" and ticket.jira_error == ""
181
+
182
+
183
+ def test_attachment_failure_marks_partial(jira, make_ticket, png):
184
+ ticket = make_ticket(screenshot=png())
185
+ with mock.patch("urllib.request.urlopen", fake_urlopen([], fail_attachments=True)):
186
+ notifiers.jira_issue(ticket, "")
187
+ ticket.refresh_from_db()
188
+ assert ticket.jira_status == "partial" and ticket.jira_key == "APP-7"
189
+ assert ticket.jira_error.startswith("Attachments failed")
190
+
191
+
192
+ def test_report_still_succeeds_and_records_the_error(
193
+ jira_on, user_client, django_capture_on_commit_callbacks
194
+ ):
195
+ from snapnote.models import Ticket
196
+
197
+ with mock.patch("urllib.request.urlopen", side_effect=http_error()):
198
+ with django_capture_on_commit_callbacks(execute=True):
199
+ response = user_client.post(
200
+ "/snapnote/report/", {"title": "t", "page_url": "http://a/"}
201
+ )
202
+ assert response.status_code == 201
203
+ assert Ticket.objects.get().jira_status == "failed"
204
+
205
+
206
+ def test_status_property_and_queryset_filter(make_ticket):
207
+ from snapnote.models import Ticket
208
+
209
+ ok = make_ticket(jira_key="A-1")
210
+ partial = make_ticket(jira_key="A-2", jira_error="Attachments failed")
211
+ failed = make_ticket(jira_error="HTTP 500")
212
+ none = make_ticket()
213
+ assert [t.jira_status for t in (ok, partial, failed, none)] == ["ok", "partial", "failed", ""]
214
+ assert set(Ticket.objects.jira("ok")) == {ok, partial}
215
+ assert list(Ticket.objects.jira("failed")) == [failed]
216
+ assert list(Ticket.objects.jira("none")) == [none]
217
+ assert Ticket.objects.jira("").count() == 4
218
+
219
+
220
+ def test_detail_shows_failure_and_retry_button(jira_on, manager_client, make_ticket):
221
+ ticket = make_ticket(jira_error="HTTP 500: boom")
222
+ html = manager_client.get(ticket.get_absolute_url()).content.decode()
223
+ assert "Jira failed" in html and "HTTP 500: boom" in html
224
+ assert f"/snapnote/{ticket.pk}/jira/retry/" in html
225
+
226
+
227
+ def test_retry_button_hidden_without_change_permission(jira_on, client, db, make_ticket):
228
+ from django.contrib.auth import get_user_model
229
+ from django.contrib.auth.models import Permission
230
+
231
+ User = get_user_model()
232
+ viewer = User.objects.create_user(**{User.USERNAME_FIELD: "viewer"}, password="x")
233
+ viewer.user_permissions.add(Permission.objects.get(codename="view_ticket"))
234
+ client.force_login(viewer)
235
+ ticket = make_ticket(jira_error="HTTP 500")
236
+ html = client.get(ticket.get_absolute_url()).content.decode()
237
+ assert "Jira failed" in html and "jira/retry" not in html
238
+ assert client.post(f"/snapnote/{ticket.pk}/jira/retry/").status_code == 403
239
+
240
+
241
+ def test_retry_view_creates_the_issue_once(jira_on, manager_client, make_ticket):
242
+ ticket = make_ticket(jira_error="HTTP 500")
243
+ url = f"/snapnote/{ticket.pk}/jira/retry/"
244
+ calls = []
245
+ with mock.patch("urllib.request.urlopen", fake_urlopen(calls)):
246
+ response = manager_client.post(url)
247
+ manager_client.post(url) # second click must not create a second issue
248
+ assert response["Location"] == ticket.get_absolute_url()
249
+ ticket.refresh_from_db()
250
+ assert ticket.jira_key == "APP-7" and ticket.jira_error == "" and len(calls) == 1
251
+ assert "http://testserver/snapnote/" in calls[0].data.decode()
252
+
253
+
254
+ def test_retry_view_failure_keeps_the_error(jira_on, manager_client, make_ticket):
255
+ ticket = make_ticket(jira_error="HTTP 500")
256
+ with mock.patch("urllib.request.urlopen", side_effect=http_error(503)):
257
+ assert manager_client.post(f"/snapnote/{ticket.pk}/jira/retry/").status_code == 302
258
+ ticket.refresh_from_db()
259
+ assert ticket.jira_error.startswith("HTTP 503") and ticket.jira_key == ""
260
+
261
+
262
+ def test_retry_view_is_404_when_jira_is_not_configured(manager_client, make_ticket):
263
+ ticket = make_ticket(jira_error="HTTP 500")
264
+ assert manager_client.post(f"/snapnote/{ticket.pk}/jira/retry/").status_code == 404
265
+ assert manager_client.get(f"/snapnote/{ticket.pk}/jira/retry/").status_code in (404, 405)
266
+
267
+
268
+ def test_list_shows_failure_and_filters(jira_on, manager_client, make_ticket):
269
+ make_ticket(title="bad", jira_error="HTTP 500")
270
+ make_ticket(title="good", jira_key="APP-1")
271
+ html = manager_client.get("/snapnote/").content.decode()
272
+ assert "Jira failed" in html
273
+ titles = [
274
+ t.title for t in manager_client.get("/snapnote/", {"jira": "failed"}).context["object_list"]
275
+ ]
276
+ assert titles == ["bad"]
277
+
278
+
279
+ def test_admin_filter(client, superuser, make_ticket):
280
+ client.force_login(superuser)
281
+ make_ticket(title="bad", jira_error="HTTP 500")
282
+ make_ticket(title="good", jira_key="APP-1")
283
+ page = client.get("/admin/snapnote/ticket/", {"jira": "failed"})
284
+ assert page.status_code == 200
285
+ assert [t.title for t in page.context["cl"].result_list] == ["bad"]
286
+
287
+
288
+ def test_retry_command(jira_on, settings, make_ticket):
289
+ from django.core.management import call_command
290
+ from django.core.management.base import CommandError
291
+
292
+ settings.SNAPNOTE_BASE_URL = "https://intranet.example.com/"
293
+ bad = make_ticket(jira_error="HTTP 500")
294
+ ok = make_ticket(jira_key="A-1")
295
+ calls = []
296
+ with mock.patch("urllib.request.urlopen", fake_urlopen(calls)):
297
+ call_command("snapnote_retry_jira", dry_run=True)
298
+ assert calls == []
299
+ call_command("snapnote_retry_jira")
300
+ bad.refresh_from_db()
301
+ ok.refresh_from_db()
302
+ assert bad.jira_key == "APP-7" and ok.jira_key == "A-1" and len(calls) == 1
303
+ assert "https://intranet.example.com/snapnote/" in calls[0].data.decode()
304
+ settings.SNAPNOTE_NOTIFIERS = ["snapnote.notifiers.email"]
305
+ with pytest.raises(CommandError):
306
+ call_command("snapnote_retry_jira")
@@ -1 +0,0 @@
1
- __version__ = "0.3.0"
@@ -1,12 +0,0 @@
1
- from django.contrib import admin
2
-
3
- from .models import Ticket
4
-
5
-
6
- @admin.register(Ticket)
7
- class TicketAdmin(admin.ModelAdmin):
8
- list_display = ("id", "title", "status", "reported_by", "created_at")
9
- list_filter = ("status", "created_at")
10
- search_fields = ("title", "description", "page_url")
11
- raw_id_fields = ("reported_by", "closed_by")
12
- readonly_fields = ("created_at", "updated_at")
@@ -1,98 +0,0 @@
1
- import json
2
- from unittest import mock
3
-
4
- import pytest
5
- from django.core.checks import run_checks
6
-
7
- from snapnote import notifiers
8
-
9
-
10
- @pytest.fixture
11
- def jira(settings):
12
- settings.SNAPNOTE_JIRA_URL = "https://acme.atlassian.net/"
13
- settings.SNAPNOTE_JIRA_EMAIL = "bot@acme.com"
14
- settings.SNAPNOTE_JIRA_API_TOKEN = "secret"
15
- settings.SNAPNOTE_JIRA_PROJECT = "APP"
16
-
17
-
18
- class FakeResponse:
19
- def __init__(self, body):
20
- self.body = body
21
-
22
- def __enter__(self):
23
- return self
24
-
25
- def __exit__(self, *args):
26
- return False
27
-
28
- def read(self):
29
- return json.dumps(self.body).encode()
30
-
31
-
32
- def fake_urlopen(calls, fail_attachments=False):
33
- def urlopen(request, timeout=None):
34
- calls.append(request)
35
- if "attachments" in request.full_url and fail_attachments:
36
- raise OSError("boom")
37
- return FakeResponse({"key": "APP-7"})
38
-
39
- return urlopen
40
-
41
-
42
- def test_creates_issue_and_attaches_images(jira, make_ticket, png):
43
- ticket = make_ticket(
44
- title="Broken", description="It fails", screenshot=png(), annotations=png("a.png")
45
- )
46
- calls = []
47
- with mock.patch("urllib.request.urlopen", fake_urlopen(calls)):
48
- key = notifiers.jira_issue(ticket, "http://testserver/snapnote/1/")
49
- assert key == "APP-7"
50
- create, shot, ann = calls
51
- assert create.full_url == "https://acme.atlassian.net/rest/api/3/issue"
52
- assert create.get_header("Authorization").startswith("Basic ")
53
- fields = json.loads(create.data)["fields"]
54
- assert fields["project"] == {"key": "APP"} and fields["issuetype"] == {"name": "Bug"}
55
- assert fields["summary"] == "Broken" and fields["labels"] == ["snapnote"]
56
- text = json.dumps(fields["description"])
57
- assert "It fails" in text and "http://testserver/snapnote/1/" in text
58
- assert shot.full_url.endswith("/issue/APP-7/attachments")
59
- assert shot.get_header("X-atlassian-token") == "no-check"
60
- assert ann.full_url.endswith("/issue/APP-7/attachments")
61
-
62
-
63
- def test_no_attachments_when_disabled_or_absent(jira, settings, make_ticket, png):
64
- settings.SNAPNOTE_JIRA_ATTACH_IMAGES = False
65
- calls = []
66
- with mock.patch("urllib.request.urlopen", fake_urlopen(calls)):
67
- notifiers.jira_issue(make_ticket(screenshot=png()), "")
68
- assert len(calls) == 1
69
-
70
-
71
- def test_attachment_failure_does_not_fail_notifier(jira, make_ticket, png):
72
- calls = []
73
- with mock.patch("urllib.request.urlopen", fake_urlopen(calls, fail_attachments=True)):
74
- assert notifiers.jira_issue(make_ticket(screenshot=png()), "") == "APP-7"
75
-
76
-
77
- def test_javascript_page_url_is_not_a_link(jira, make_ticket):
78
- calls = []
79
- with mock.patch("urllib.request.urlopen", fake_urlopen(calls)):
80
- notifiers.jira_issue(make_ticket(page_url="javascript:alert(1)"), "")
81
- assert '"link"' not in calls[0].data.decode()
82
-
83
-
84
- def test_jira_failure_is_contained_by_runner(jira, settings, make_ticket):
85
- settings.SNAPNOTE_NOTIFIERS = ["snapnote.notifiers.jira_issue"]
86
- with mock.patch("urllib.request.urlopen", side_effect=OSError("down")):
87
- notifiers.run_notifiers(None, make_ticket(), "") # must not raise
88
-
89
-
90
- def test_check_warns_when_misconfigured(settings):
91
- settings.SNAPNOTE_NOTIFIERS = ["snapnote.notifiers.jira_issue"]
92
- warnings = [m for m in run_checks() if m.id == "snapnote.W002"]
93
- assert warnings and "SNAPNOTE_JIRA_URL" in warnings[0].hint
94
-
95
-
96
- def test_check_silent_when_configured(jira, settings):
97
- settings.SNAPNOTE_NOTIFIERS = ["snapnote.notifiers.jira_issue"]
98
- assert not [m for m in run_checks() if m.id == "snapnote.W002"]
File without changes