simple-module-analytics 0.0.15__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.
- simple_module_analytics-0.0.15.dist-info/METADATA +57 -0
- simple_module_analytics-0.0.15.dist-info/RECORD +50 -0
- simple_module_analytics-0.0.15.dist-info/WHEEL +4 -0
- simple_module_analytics-0.0.15.dist-info/entry_points.txt +2 -0
- sm_analytics/__init__.py +1 -0
- sm_analytics/collection/__init__.py +1 -0
- sm_analytics/collection/privacy.py +85 -0
- sm_analytics/collection/retention.py +33 -0
- sm_analytics/collection/service.py +105 -0
- sm_analytics/core/__init__.py +1 -0
- sm_analytics/core/constants.py +15 -0
- sm_analytics/core/geo.py +133 -0
- sm_analytics/core/runtime.py +58 -0
- sm_analytics/core/settings.py +22 -0
- sm_analytics/core/tenancy.py +26 -0
- sm_analytics/index.ts +3 -0
- sm_analytics/locales/de.json +118 -0
- sm_analytics/locales/en.json +118 -0
- sm_analytics/models/__init__.py +87 -0
- sm_analytics/module.py +103 -0
- sm_analytics/package.json +21 -0
- sm_analytics/pages/Dashboard.tsx +164 -0
- sm_analytics/reporting/__init__.py +1 -0
- sm_analytics/reporting/reports.py +145 -0
- sm_analytics/ui/components/DateRangeControl.tsx +126 -0
- sm_analytics/ui/components/DeleteProperty.tsx +68 -0
- sm_analytics/ui/components/FilterChips.tsx +74 -0
- sm_analytics/ui/components/PropertyEditor.tsx +189 -0
- sm_analytics/ui/components/PropertySettings.tsx +120 -0
- sm_analytics/ui/components/RankingPanel.tsx +119 -0
- sm_analytics/ui/components/RecentActivity.tsx +63 -0
- sm_analytics/ui/components/ReportExport.tsx +63 -0
- sm_analytics/ui/components/ReportFilters.tsx +119 -0
- sm_analytics/ui/components/ReportView.tsx +86 -0
- sm_analytics/ui/components/TrafficChart.tsx +123 -0
- sm_analytics/ui/utils/api.ts +52 -0
- sm_analytics/ui/utils/csrf.ts +46 -0
- sm_analytics/ui/utils/hostTracker.ts +52 -0
- sm_analytics/ui/utils/i18n.ts +89 -0
- sm_analytics/ui/utils/reportExport.ts +48 -0
- sm_analytics/ui/utils/tracker.ts +102 -0
- sm_analytics/ui/utils/trackingPaths.ts +36 -0
- sm_analytics/ui/utils/types.ts +55 -0
- sm_analytics/ui/utils/useAnalytics.ts +111 -0
- sm_analytics/web/__init__.py +1 -0
- sm_analytics/web/deps.py +30 -0
- sm_analytics/web/endpoints/__init__.py +1 -0
- sm_analytics/web/endpoints/admin.py +115 -0
- sm_analytics/web/endpoints/public.py +76 -0
- sm_analytics/web/schemas.py +132 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Bounded SQL aggregates; reporting never loads the event history into Python."""
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, date, datetime, timedelta
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import case, func, select
|
|
6
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
7
|
+
|
|
8
|
+
from sm_analytics.models import AnalyticsEvent as E
|
|
9
|
+
from sm_analytics.models import AnalyticsProperty
|
|
10
|
+
|
|
11
|
+
DIMENSIONS = (
|
|
12
|
+
"path",
|
|
13
|
+
"referrer",
|
|
14
|
+
"utm_source",
|
|
15
|
+
"utm_medium",
|
|
16
|
+
"utm_campaign",
|
|
17
|
+
"browser",
|
|
18
|
+
"os",
|
|
19
|
+
"device",
|
|
20
|
+
"country",
|
|
21
|
+
"region",
|
|
22
|
+
"city",
|
|
23
|
+
"event",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def utc_day(dialect: str, column):
|
|
28
|
+
return func.date(func.timezone("UTC", column) if dialect == "postgresql" else column)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def report(
|
|
32
|
+
db: AsyncSession,
|
|
33
|
+
tenant: str,
|
|
34
|
+
prop: AnalyticsProperty,
|
|
35
|
+
*,
|
|
36
|
+
start: date,
|
|
37
|
+
end: date,
|
|
38
|
+
now: datetime | None = None,
|
|
39
|
+
filters: dict | None = None,
|
|
40
|
+
) -> dict:
|
|
41
|
+
# shortcut: raw history scans; add daily rollups when long-range reports need low latency.
|
|
42
|
+
now = now or datetime.now(UTC)
|
|
43
|
+
begin = datetime.combine(start, datetime.min.time(), UTC)
|
|
44
|
+
finish = datetime.combine(end + timedelta(days=1), datetime.min.time(), UTC)
|
|
45
|
+
criteria = [
|
|
46
|
+
E.tenant_id == tenant,
|
|
47
|
+
E.property_id == prop.id,
|
|
48
|
+
E.created_at >= begin,
|
|
49
|
+
E.created_at < finish,
|
|
50
|
+
]
|
|
51
|
+
for key, value in (filters or {}).items():
|
|
52
|
+
if key in {"path", "event", "country", "region", "city"} and value is not None:
|
|
53
|
+
criteria.append(getattr(E, "name" if key == "event" else key) == value)
|
|
54
|
+
pageviews = func.coalesce(func.sum(case((E.kind == "pageview", 1), else_=0)), 0)
|
|
55
|
+
events = func.coalesce(func.sum(case((E.kind == "event", 1), else_=0)), 0)
|
|
56
|
+
row = (
|
|
57
|
+
await db.execute(
|
|
58
|
+
select(
|
|
59
|
+
pageviews,
|
|
60
|
+
events,
|
|
61
|
+
func.count(func.distinct(E.visitor)),
|
|
62
|
+
func.count(func.distinct(E.session_id)),
|
|
63
|
+
).where(*criteria)
|
|
64
|
+
)
|
|
65
|
+
).one()
|
|
66
|
+
totals = dict(zip(("pageviews", "events", "visitors", "sessions"), map(int, row), strict=True))
|
|
67
|
+
day = utc_day(db.get_bind().dialect.name, E.created_at)
|
|
68
|
+
daily = (
|
|
69
|
+
await db.execute(
|
|
70
|
+
select(day, pageviews, events).where(*criteria).group_by(day).order_by(day)
|
|
71
|
+
)
|
|
72
|
+
).all()
|
|
73
|
+
by_day = {str(d): {"pageviews": int(p), "events": int(e)} for d, p, e in daily}
|
|
74
|
+
series = []
|
|
75
|
+
current = start
|
|
76
|
+
while current <= end:
|
|
77
|
+
key = current.isoformat()
|
|
78
|
+
series.append({"date": key, **by_day.get(key, {"pageviews": 0, "events": 0})})
|
|
79
|
+
current += timedelta(days=1)
|
|
80
|
+
breakdowns = {}
|
|
81
|
+
for dimension in DIMENSIONS:
|
|
82
|
+
col = getattr(E, "name" if dimension == "event" else dimension)
|
|
83
|
+
extra = [E.kind == "event"] if dimension == "event" else []
|
|
84
|
+
label = (
|
|
85
|
+
getattr(E, f"{dimension}_name") if dimension in {"country", "region", "city"} else col
|
|
86
|
+
)
|
|
87
|
+
rows = (
|
|
88
|
+
await db.execute(
|
|
89
|
+
select(col, func.max(label), func.count())
|
|
90
|
+
.where(*criteria, *extra)
|
|
91
|
+
.group_by(col)
|
|
92
|
+
.order_by(func.count().desc(), col)
|
|
93
|
+
.limit(50)
|
|
94
|
+
)
|
|
95
|
+
).all()
|
|
96
|
+
breakdowns[dimension] = [
|
|
97
|
+
{"value": v, "label": name or v or "Unknown", "count": n} for v, name, n in rows
|
|
98
|
+
]
|
|
99
|
+
event_name = (filters or {}).get("event")
|
|
100
|
+
for key in prop.event_allowlist.get(event_name, []):
|
|
101
|
+
value = E.properties[key].as_string()
|
|
102
|
+
rows = (
|
|
103
|
+
await db.execute(
|
|
104
|
+
select(value, func.count())
|
|
105
|
+
.where(*criteria, E.kind == "event", value.is_not(None))
|
|
106
|
+
.group_by(value)
|
|
107
|
+
.order_by(func.count().desc())
|
|
108
|
+
.limit(50)
|
|
109
|
+
)
|
|
110
|
+
).all()
|
|
111
|
+
breakdowns[f"property:{key}"] = [
|
|
112
|
+
{"value": str(v), "label": str(v), "count": n} for v, n in rows
|
|
113
|
+
]
|
|
114
|
+
recent_criteria = [*criteria, E.created_at >= now - timedelta(minutes=5)]
|
|
115
|
+
active = await db.scalar(select(func.count(func.distinct(E.visitor))).where(*recent_criteria))
|
|
116
|
+
recent = (
|
|
117
|
+
await db.scalars(select(E).where(*recent_criteria).order_by(E.created_at.desc()).limit(50))
|
|
118
|
+
).all()
|
|
119
|
+
return {
|
|
120
|
+
"totals": totals,
|
|
121
|
+
"series": series,
|
|
122
|
+
"breakdowns": breakdowns,
|
|
123
|
+
"recent": {
|
|
124
|
+
"visitors": active,
|
|
125
|
+
"events": [
|
|
126
|
+
{
|
|
127
|
+
key: getattr(e, key)
|
|
128
|
+
for key in (
|
|
129
|
+
"event_id",
|
|
130
|
+
"kind",
|
|
131
|
+
"path",
|
|
132
|
+
"name",
|
|
133
|
+
"created_at",
|
|
134
|
+
"country",
|
|
135
|
+
"region",
|
|
136
|
+
"city",
|
|
137
|
+
"country_name",
|
|
138
|
+
"region_name",
|
|
139
|
+
"city_name",
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
for e in recent
|
|
143
|
+
],
|
|
144
|
+
},
|
|
145
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { Button } from '@simple-module-py/ui/components/ui/button';
|
|
2
|
+
import { Input } from '@simple-module-py/ui/components/ui/input';
|
|
3
|
+
import { Label } from '@simple-module-py/ui/components/ui/label';
|
|
4
|
+
import {
|
|
5
|
+
Popover,
|
|
6
|
+
PopoverContent,
|
|
7
|
+
PopoverTrigger,
|
|
8
|
+
} from '@simple-module-py/ui/components/ui/popover';
|
|
9
|
+
import { useId, useState } from 'react';
|
|
10
|
+
import { keys, useT } from '../utils/i18n';
|
|
11
|
+
import type { Filters } from '../utils/types';
|
|
12
|
+
|
|
13
|
+
export function DateRangeControl({
|
|
14
|
+
value,
|
|
15
|
+
onChange,
|
|
16
|
+
}: {
|
|
17
|
+
value: Filters;
|
|
18
|
+
onChange: (next: Filters) => void;
|
|
19
|
+
}) {
|
|
20
|
+
const { t } = useT();
|
|
21
|
+
const id = useId();
|
|
22
|
+
const [open, setOpen] = useState(false);
|
|
23
|
+
const [start, setStart] = useState(value.start);
|
|
24
|
+
const [end, setEnd] = useState(value.end);
|
|
25
|
+
const span = (Date.parse(end) - Date.parse(start)) / 86400000;
|
|
26
|
+
const valid = start >= '0001-01-01' && end <= '9999-12-30' && span >= 0 && span <= 365;
|
|
27
|
+
const apply = (from: string, to: string) => {
|
|
28
|
+
onChange({ ...value, start: from, end: to });
|
|
29
|
+
setOpen(false);
|
|
30
|
+
};
|
|
31
|
+
return (
|
|
32
|
+
<Popover
|
|
33
|
+
open={open}
|
|
34
|
+
onOpenChange={(next) => {
|
|
35
|
+
setStart(value.start);
|
|
36
|
+
setEnd(value.end);
|
|
37
|
+
setOpen(next);
|
|
38
|
+
}}
|
|
39
|
+
>
|
|
40
|
+
<PopoverTrigger asChild>
|
|
41
|
+
<Button
|
|
42
|
+
variant="outline"
|
|
43
|
+
aria-label={t(keys.analytics.ui.date_range)}
|
|
44
|
+
className="max-w-full tabular-nums"
|
|
45
|
+
>
|
|
46
|
+
<span className="truncate">
|
|
47
|
+
{value.start} – {value.end}
|
|
48
|
+
</span>
|
|
49
|
+
</Button>
|
|
50
|
+
</PopoverTrigger>
|
|
51
|
+
<PopoverContent align="end" className="w-[min(24rem,calc(100vw-2rem))]">
|
|
52
|
+
<div className="grid grid-cols-2 gap-2">
|
|
53
|
+
{(
|
|
54
|
+
[
|
|
55
|
+
['today', 1],
|
|
56
|
+
['last_7_days', 7],
|
|
57
|
+
['last_30_days', 30],
|
|
58
|
+
['last_90_days', 90],
|
|
59
|
+
] as const
|
|
60
|
+
).map(([label, days]) => (
|
|
61
|
+
<Button
|
|
62
|
+
key={label}
|
|
63
|
+
variant="outline"
|
|
64
|
+
onClick={() => {
|
|
65
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
66
|
+
const from = new Date(`${today}T00:00:00Z`);
|
|
67
|
+
from.setUTCDate(from.getUTCDate() - days + 1);
|
|
68
|
+
apply(from.toISOString().slice(0, 10), today);
|
|
69
|
+
}}
|
|
70
|
+
>
|
|
71
|
+
{t(keys.analytics.ui[label])}
|
|
72
|
+
</Button>
|
|
73
|
+
))}
|
|
74
|
+
</div>
|
|
75
|
+
<form
|
|
76
|
+
className="mt-4 space-y-3"
|
|
77
|
+
onSubmit={(event) => {
|
|
78
|
+
event.preventDefault();
|
|
79
|
+
if (valid) apply(start, end);
|
|
80
|
+
}}
|
|
81
|
+
>
|
|
82
|
+
<h2 className="text-sm font-medium">{t(keys.analytics.ui.custom_range)}</h2>
|
|
83
|
+
<div className="grid gap-3 sm:grid-cols-2">
|
|
84
|
+
<div className="min-w-0 space-y-1">
|
|
85
|
+
<Label htmlFor={`${id}-start`}>{t(keys.analytics.start)}</Label>
|
|
86
|
+
<Input
|
|
87
|
+
id={`${id}-start`}
|
|
88
|
+
type="date"
|
|
89
|
+
aria-describedby={`${id}-help`}
|
|
90
|
+
min="0001-01-01"
|
|
91
|
+
max={end || '9999-12-30'}
|
|
92
|
+
value={start}
|
|
93
|
+
onChange={(event) => setStart(event.target.value)}
|
|
94
|
+
required
|
|
95
|
+
/>
|
|
96
|
+
</div>
|
|
97
|
+
<div className="min-w-0 space-y-1">
|
|
98
|
+
<Label htmlFor={`${id}-end`}>{t(keys.analytics.end)}</Label>
|
|
99
|
+
<Input
|
|
100
|
+
id={`${id}-end`}
|
|
101
|
+
type="date"
|
|
102
|
+
aria-describedby={`${id}-help`}
|
|
103
|
+
min={start || '0001-01-01'}
|
|
104
|
+
max="9999-12-30"
|
|
105
|
+
value={end}
|
|
106
|
+
onChange={(event) => setEnd(event.target.value)}
|
|
107
|
+
required
|
|
108
|
+
/>
|
|
109
|
+
</div>
|
|
110
|
+
</div>
|
|
111
|
+
<p id={`${id}-help`} className="text-xs text-muted-foreground">
|
|
112
|
+
{t(keys.analytics.ui.date_help)}
|
|
113
|
+
</p>
|
|
114
|
+
<div className="flex justify-end gap-2">
|
|
115
|
+
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
|
|
116
|
+
{t(keys.analytics.cancel)}
|
|
117
|
+
</Button>
|
|
118
|
+
<Button type="submit" disabled={!valid} aria-describedby={`${id}-help`}>
|
|
119
|
+
{t(keys.analytics.ui.apply)}
|
|
120
|
+
</Button>
|
|
121
|
+
</div>
|
|
122
|
+
</form>
|
|
123
|
+
</PopoverContent>
|
|
124
|
+
</Popover>
|
|
125
|
+
);
|
|
126
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AlertDialog,
|
|
3
|
+
AlertDialogAction,
|
|
4
|
+
AlertDialogCancel,
|
|
5
|
+
AlertDialogContent,
|
|
6
|
+
AlertDialogDescription,
|
|
7
|
+
AlertDialogFooter,
|
|
8
|
+
AlertDialogHeader,
|
|
9
|
+
AlertDialogTitle,
|
|
10
|
+
AlertDialogTrigger,
|
|
11
|
+
} from '@simple-module-py/ui/components/ui/alert-dialog';
|
|
12
|
+
import { Button } from '@simple-module-py/ui/components/ui/button';
|
|
13
|
+
import { useState } from 'react';
|
|
14
|
+
import { keys, useT } from '../utils/i18n';
|
|
15
|
+
|
|
16
|
+
export function DeleteProperty({ onDelete }: { onDelete: () => Promise<void> }) {
|
|
17
|
+
const { t } = useT();
|
|
18
|
+
const [open, setOpen] = useState(false);
|
|
19
|
+
const [busy, setBusy] = useState(false);
|
|
20
|
+
const [error, setError] = useState('');
|
|
21
|
+
return (
|
|
22
|
+
<AlertDialog
|
|
23
|
+
open={open}
|
|
24
|
+
onOpenChange={(next) => {
|
|
25
|
+
if (!busy) {
|
|
26
|
+
setOpen(next);
|
|
27
|
+
setError('');
|
|
28
|
+
}
|
|
29
|
+
}}
|
|
30
|
+
>
|
|
31
|
+
<AlertDialogTrigger asChild>
|
|
32
|
+
<Button variant="destructive">{t(keys.analytics.delete)}</Button>
|
|
33
|
+
</AlertDialogTrigger>
|
|
34
|
+
<AlertDialogContent>
|
|
35
|
+
<AlertDialogHeader>
|
|
36
|
+
<AlertDialogTitle>{t(keys.analytics.delete_title)}</AlertDialogTitle>
|
|
37
|
+
<AlertDialogDescription>{t(keys.analytics.delete_description)}</AlertDialogDescription>
|
|
38
|
+
</AlertDialogHeader>
|
|
39
|
+
{error && (
|
|
40
|
+
<p role="alert" className="text-sm text-destructive">
|
|
41
|
+
{error}
|
|
42
|
+
</p>
|
|
43
|
+
)}
|
|
44
|
+
<AlertDialogFooter>
|
|
45
|
+
<AlertDialogCancel disabled={busy}>{t(keys.analytics.cancel)}</AlertDialogCancel>
|
|
46
|
+
<AlertDialogAction
|
|
47
|
+
disabled={busy}
|
|
48
|
+
onClick={async (event) => {
|
|
49
|
+
event.preventDefault();
|
|
50
|
+
setBusy(true);
|
|
51
|
+
setError('');
|
|
52
|
+
try {
|
|
53
|
+
await onDelete();
|
|
54
|
+
setOpen(false);
|
|
55
|
+
} catch (reason) {
|
|
56
|
+
setError(reason instanceof Error ? reason.message : t(keys.analytics.error));
|
|
57
|
+
} finally {
|
|
58
|
+
setBusy(false);
|
|
59
|
+
}
|
|
60
|
+
}}
|
|
61
|
+
>
|
|
62
|
+
{t(busy ? keys.analytics.deleting : keys.analytics.delete)}
|
|
63
|
+
</AlertDialogAction>
|
|
64
|
+
</AlertDialogFooter>
|
|
65
|
+
</AlertDialogContent>
|
|
66
|
+
</AlertDialog>
|
|
67
|
+
);
|
|
68
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { Button } from '@simple-module-py/ui/components/ui/button';
|
|
2
|
+
import { X } from 'lucide-react';
|
|
3
|
+
import { keys, useT } from '../utils/i18n';
|
|
4
|
+
import type { Filters, Report } from '../utils/types';
|
|
5
|
+
|
|
6
|
+
export function FilterChips({
|
|
7
|
+
value,
|
|
8
|
+
onChange,
|
|
9
|
+
report,
|
|
10
|
+
}: {
|
|
11
|
+
value: Filters;
|
|
12
|
+
onChange: (next: Filters) => void;
|
|
13
|
+
report: Report | null;
|
|
14
|
+
}) {
|
|
15
|
+
const { t } = useT();
|
|
16
|
+
const fields = ['path', 'event', 'country', 'region', 'city'] as const;
|
|
17
|
+
const labels = {
|
|
18
|
+
path: keys.analytics.page_filter,
|
|
19
|
+
event: keys.analytics.event_filter,
|
|
20
|
+
country: keys.analytics.country,
|
|
21
|
+
region: keys.analytics.region,
|
|
22
|
+
city: keys.analytics.city,
|
|
23
|
+
};
|
|
24
|
+
if (!fields.some((field) => value[field])) return null;
|
|
25
|
+
return (
|
|
26
|
+
<div className="flex flex-wrap items-center gap-2">
|
|
27
|
+
{fields
|
|
28
|
+
.filter((field) => value[field])
|
|
29
|
+
.map((field) => {
|
|
30
|
+
const name = t(labels[field]);
|
|
31
|
+
const label =
|
|
32
|
+
field !== 'path' && field !== 'event' && value[field] === '__unknown__'
|
|
33
|
+
? t(keys.analytics.unknown)
|
|
34
|
+
: report?.breakdowns[field]?.find((row) => row.value === value[field])?.label ||
|
|
35
|
+
value[field];
|
|
36
|
+
return (
|
|
37
|
+
<Button
|
|
38
|
+
key={field}
|
|
39
|
+
variant="outline"
|
|
40
|
+
size="sm"
|
|
41
|
+
className="h-auto max-w-full gap-2 py-1 text-xs"
|
|
42
|
+
aria-label={t(keys.analytics.ui.clear_filter, { name })}
|
|
43
|
+
onClick={() =>
|
|
44
|
+
onChange({
|
|
45
|
+
...value,
|
|
46
|
+
[field]: '',
|
|
47
|
+
...(field === 'country'
|
|
48
|
+
? { region: '', city: '' }
|
|
49
|
+
: field === 'region'
|
|
50
|
+
? { city: '' }
|
|
51
|
+
: {}),
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
>
|
|
55
|
+
<span className="min-w-0 whitespace-normal break-all text-left">
|
|
56
|
+
{name}: {label}
|
|
57
|
+
</span>
|
|
58
|
+
<X className="size-3 shrink-0" aria-hidden="true" />
|
|
59
|
+
</Button>
|
|
60
|
+
);
|
|
61
|
+
})}
|
|
62
|
+
<Button
|
|
63
|
+
variant="ghost"
|
|
64
|
+
size="sm"
|
|
65
|
+
className="h-7 text-xs text-muted-foreground"
|
|
66
|
+
onClick={() =>
|
|
67
|
+
onChange({ ...value, path: '', event: '', country: '', region: '', city: '' })
|
|
68
|
+
}
|
|
69
|
+
>
|
|
70
|
+
{t(keys.analytics.clear_filters)}
|
|
71
|
+
</Button>
|
|
72
|
+
</div>
|
|
73
|
+
);
|
|
74
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { Button } from '@simple-module-py/ui/components/ui/button';
|
|
2
|
+
import { Input } from '@simple-module-py/ui/components/ui/input';
|
|
3
|
+
import { Label } from '@simple-module-py/ui/components/ui/label';
|
|
4
|
+
import { Textarea } from '@simple-module-py/ui/components/ui/textarea';
|
|
5
|
+
import { useId, useState } from 'react';
|
|
6
|
+
import { keys, useT } from '../utils/i18n';
|
|
7
|
+
import type { Property, PropertyInput } from '../utils/types';
|
|
8
|
+
|
|
9
|
+
const UTM = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
|
|
10
|
+
const lines = (text: string) =>
|
|
11
|
+
text
|
|
12
|
+
.split('\n')
|
|
13
|
+
.map((line) => line.trim())
|
|
14
|
+
.filter(Boolean);
|
|
15
|
+
|
|
16
|
+
export function PropertyEditor({
|
|
17
|
+
property,
|
|
18
|
+
onSave,
|
|
19
|
+
onCancel,
|
|
20
|
+
}: {
|
|
21
|
+
property?: Property;
|
|
22
|
+
onSave: (input: PropertyInput) => Promise<void>;
|
|
23
|
+
onCancel: () => void;
|
|
24
|
+
}) {
|
|
25
|
+
const { t } = useT();
|
|
26
|
+
const id = useId();
|
|
27
|
+
const [name, setName] = useState(property?.name ?? '');
|
|
28
|
+
const [kind, setKind] = useState<'public' | 'application'>(property?.kind ?? 'public');
|
|
29
|
+
const [origins, setOrigins] = useState(property?.origins.join('\n') ?? window.location.origin);
|
|
30
|
+
const [routes, setRoutes] = useState(property?.route_patterns.join('\n') ?? '');
|
|
31
|
+
const [events, setEvents] = useState(
|
|
32
|
+
Object.entries(property?.event_allowlist ?? {})
|
|
33
|
+
.map(([event, fields]) => `${event}: ${fields.join(', ')}`)
|
|
34
|
+
.join('\n'),
|
|
35
|
+
);
|
|
36
|
+
const [utm, setUtm] = useState(property?.utm_parameters ?? []);
|
|
37
|
+
const [enabled, setEnabled] = useState(property?.enabled ?? false);
|
|
38
|
+
const [busy, setBusy] = useState(false);
|
|
39
|
+
const [error, setError] = useState('');
|
|
40
|
+
async function submit(event: React.FormEvent) {
|
|
41
|
+
event.preventDefault();
|
|
42
|
+
setError('');
|
|
43
|
+
const allowlist: Record<string, string[]> = {};
|
|
44
|
+
for (const line of lines(events)) {
|
|
45
|
+
const [eventName, fields, extra] = line.split(':');
|
|
46
|
+
if (!eventName.trim() || fields === undefined || extra !== undefined) {
|
|
47
|
+
setError(t(keys.analytics.event_format_error));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
allowlist[eventName.trim()] = fields
|
|
51
|
+
.split(',')
|
|
52
|
+
.map((field) => field.trim())
|
|
53
|
+
.filter(Boolean);
|
|
54
|
+
}
|
|
55
|
+
setBusy(true);
|
|
56
|
+
try {
|
|
57
|
+
await onSave({
|
|
58
|
+
name,
|
|
59
|
+
kind,
|
|
60
|
+
origins: lines(origins),
|
|
61
|
+
route_patterns: lines(routes),
|
|
62
|
+
event_allowlist: allowlist,
|
|
63
|
+
utm_parameters: utm,
|
|
64
|
+
enabled,
|
|
65
|
+
});
|
|
66
|
+
} catch (reason) {
|
|
67
|
+
setError(reason instanceof Error ? reason.message : t(keys.analytics.error));
|
|
68
|
+
} finally {
|
|
69
|
+
setBusy(false);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return (
|
|
73
|
+
<section className="rounded-lg border bg-card p-5" aria-labelledby={`${id}-title`}>
|
|
74
|
+
<h2 id={`${id}-title`} className="mb-4 text-lg font-semibold">
|
|
75
|
+
{t(property ? keys.analytics.edit_property : keys.analytics.new_property)}
|
|
76
|
+
</h2>
|
|
77
|
+
<form onSubmit={submit} className="space-y-5">
|
|
78
|
+
{error && (
|
|
79
|
+
<p role="alert" className="text-sm text-destructive">
|
|
80
|
+
{error}
|
|
81
|
+
</p>
|
|
82
|
+
)}
|
|
83
|
+
<div className="grid gap-4 sm:grid-cols-2">
|
|
84
|
+
<div className="space-y-2">
|
|
85
|
+
<Label htmlFor={`${id}-name`}>{t(keys.analytics.name)}</Label>
|
|
86
|
+
<Input
|
|
87
|
+
id={`${id}-name`}
|
|
88
|
+
value={name}
|
|
89
|
+
onChange={(e) => setName(e.target.value)}
|
|
90
|
+
required
|
|
91
|
+
maxLength={100}
|
|
92
|
+
/>
|
|
93
|
+
</div>
|
|
94
|
+
<div className="space-y-2">
|
|
95
|
+
<Label htmlFor={`${id}-kind`}>{t(keys.analytics.kind)}</Label>
|
|
96
|
+
<select
|
|
97
|
+
id={`${id}-kind`}
|
|
98
|
+
value={kind}
|
|
99
|
+
onChange={(e) => setKind(e.target.value as typeof kind)}
|
|
100
|
+
className="h-10 w-full rounded-md border bg-background px-3 text-sm"
|
|
101
|
+
>
|
|
102
|
+
<option value="public">{t(keys.analytics.public)}</option>
|
|
103
|
+
<option value="application">{t(keys.analytics.application)}</option>
|
|
104
|
+
</select>
|
|
105
|
+
</div>
|
|
106
|
+
</div>
|
|
107
|
+
<div className="grid gap-4 lg:grid-cols-2">
|
|
108
|
+
<div className="space-y-2">
|
|
109
|
+
<Label htmlFor={`${id}-origins`}>{t(keys.analytics.origins)}</Label>
|
|
110
|
+
<Textarea
|
|
111
|
+
id={`${id}-origins`}
|
|
112
|
+
value={origins}
|
|
113
|
+
onChange={(e) => setOrigins(e.target.value)}
|
|
114
|
+
rows={3}
|
|
115
|
+
required
|
|
116
|
+
aria-describedby={`${id}-origins-help`}
|
|
117
|
+
/>
|
|
118
|
+
<p id={`${id}-origins-help`} className="text-sm text-muted-foreground">
|
|
119
|
+
{t(keys.analytics.origins_help)}
|
|
120
|
+
</p>
|
|
121
|
+
</div>
|
|
122
|
+
<div className="space-y-2">
|
|
123
|
+
<Label htmlFor={`${id}-routes`}>{t(keys.analytics.routes)}</Label>
|
|
124
|
+
<Textarea
|
|
125
|
+
id={`${id}-routes`}
|
|
126
|
+
value={routes}
|
|
127
|
+
onChange={(e) => setRoutes(e.target.value)}
|
|
128
|
+
rows={3}
|
|
129
|
+
aria-describedby={`${id}-routes-help`}
|
|
130
|
+
/>
|
|
131
|
+
<p id={`${id}-routes-help`} className="text-sm text-muted-foreground">
|
|
132
|
+
{t(keys.analytics.routes_help)}
|
|
133
|
+
</p>
|
|
134
|
+
</div>
|
|
135
|
+
</div>
|
|
136
|
+
<div className="space-y-2">
|
|
137
|
+
<Label htmlFor={`${id}-events`}>{t(keys.analytics.events_config)}</Label>
|
|
138
|
+
<Textarea
|
|
139
|
+
id={`${id}-events`}
|
|
140
|
+
value={events}
|
|
141
|
+
onChange={(e) => setEvents(e.target.value)}
|
|
142
|
+
rows={3}
|
|
143
|
+
aria-describedby={`${id}-events-help`}
|
|
144
|
+
/>
|
|
145
|
+
<p id={`${id}-events-help`} className="text-sm text-muted-foreground">
|
|
146
|
+
{t(keys.analytics.events_help)}
|
|
147
|
+
</p>
|
|
148
|
+
</div>
|
|
149
|
+
<fieldset className="space-y-2">
|
|
150
|
+
<legend className="mb-2 text-sm font-medium">{t(keys.analytics.utm)}</legend>
|
|
151
|
+
<div className="flex flex-wrap gap-x-5 gap-y-2">
|
|
152
|
+
{UTM.map((param) => (
|
|
153
|
+
<label key={param} className="flex items-center gap-2 text-sm">
|
|
154
|
+
<input
|
|
155
|
+
type="checkbox"
|
|
156
|
+
checked={utm.includes(param)}
|
|
157
|
+
onChange={(e) =>
|
|
158
|
+
setUtm(e.target.checked ? [...utm, param] : utm.filter((v) => v !== param))
|
|
159
|
+
}
|
|
160
|
+
/>
|
|
161
|
+
{param}
|
|
162
|
+
</label>
|
|
163
|
+
))}
|
|
164
|
+
</div>
|
|
165
|
+
<p className="text-sm text-muted-foreground">{t(keys.analytics.utm_help)}</p>
|
|
166
|
+
</fieldset>
|
|
167
|
+
<div className="space-y-2">
|
|
168
|
+
<label className="flex items-center gap-2 text-sm font-medium">
|
|
169
|
+
<input
|
|
170
|
+
type="checkbox"
|
|
171
|
+
checked={enabled}
|
|
172
|
+
onChange={(e) => setEnabled(e.target.checked)}
|
|
173
|
+
/>
|
|
174
|
+
{t(keys.analytics.enabled)}
|
|
175
|
+
</label>
|
|
176
|
+
<p className="text-sm text-muted-foreground">{t(keys.analytics.enabled_help)}</p>
|
|
177
|
+
</div>
|
|
178
|
+
<div className="flex gap-2">
|
|
179
|
+
<Button type="submit" disabled={busy}>
|
|
180
|
+
{t(busy ? keys.analytics.saving : keys.analytics.save)}
|
|
181
|
+
</Button>
|
|
182
|
+
<Button type="button" variant="outline" disabled={busy} onClick={onCancel}>
|
|
183
|
+
{t(keys.analytics.cancel)}
|
|
184
|
+
</Button>
|
|
185
|
+
</div>
|
|
186
|
+
</form>
|
|
187
|
+
</section>
|
|
188
|
+
);
|
|
189
|
+
}
|