🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feat: saved segments (named, reusable filter sets) (#1165)
Goldflag778344af5051
diff --git a/client/messages/cs.json b/client/messages/cs.jsonindex 018b7a40c..7f1057189 100644--- a/client/messages/cs.json+++ b/client/messages/cs.json@@ -113,6 +113,19 @@"FIKvUB": "Přidat web","Dg2v6W": "vyberte hodnotu","oCBPQ4": "Odebrat filtr",+ "fB09El": "Cesty začínající /blog/",+ "nnuMWB": "Cesty obsahující /blog/ následované čímkoli",+ "GBIt8l": "Cesty končící na .pdf, .doc nebo .docx",+ "o7g8s9": "např. ^/blog/.*",+ "uxcVP6": "Zadej hodnotu...",+ "dhMkG9": "Příklady regex:",+ "kYpf9a": "Hledat nebo přidat hodnotu",+ "gjBiyj": "Načítám...",+ "jHJmjf": "Žádné výsledky",+ "2/2yg+": "Přidat",+ "SElbF+": "Uložit filtr",+ "oZhbMq": "Filtrovat statistiky podle",+ "xmcVZ0": "Hledat","LeFOAk": "Filtr není aktivní pro tuto stránku","vONi+O": "Země","2eRO6y": "Typ zařízení",@@ -170,20 +183,50 @@"hJL4XZ": "Menší než","m0lxVQ": "Větší nebo rovno","qib0lb": "Menší nebo rovno",- "fB09El": "Cesty začínající /blog/",- "nnuMWB": "Cesty obsahující /blog/ následované čímkoli",- "GBIt8l": "Cesty končící na .pdf, .doc nebo .docx",- "o7g8s9": "např. ^/blog/.*",- "uxcVP6": "Zadej hodnotu...",- "dhMkG9": "Příklady regex:",- "kYpf9a": "Hledat nebo přidat hodnotu",- "gjBiyj": "Načítám...",- "jHJmjf": "Žádné výsledky",- "2/2yg+": "Přidat",- "SElbF+": "Uložit filtr","9Obw6C": "Filtr",- "oZhbMq": "Filtrovat statistiky podle",- "xmcVZ0": "Hledat",+ "VF3DcR": "Segmenty",+ "gy/Kkr": "(upraveno)",+ "/AMnMU": "Sdíleno se všemi weby v organizaci",+ "wqoG/5": "Definováno jako",+ "1d0t7e": "Některé z těchto filtrů byly na dashboardu změněny. Samotný segment zůstal beze změny.",+ "PO3ZXG": "Upravit segment",+ "djNL6D": "Pouze pro čtení",+ "G/yZLu": "Odebrat",+ "j6Cfhx": "Odebrat segment",+ "uHnMYi": "Nový segment",+ "+NhXOR": "Změny se projeví všude, kde se tento segment používá.",+ "1rREuf": "Segment je pojmenovaná sada filtrů, kterou můžete jedním kliknutím použít v libovolném reportu.",+ "FIs3zs": "Segment „{name}“ byl uložen",+ "SubaMm": "Segment se nepodařilo uložit",+ "wFGilL": "Segment „{name}“ byl smazán",+ "gXXeAo": "Segment se nepodařilo smazat",+ "HAlOn1": "Jméno",+ "C1QAaZ": "např. Mobilní organická návštěvnost z Německa",+ "M/zZVx": "Přidat filtr",+ "VkGJJD": "Všechny filtry musí platit současně. Hodnoty v rámci jednoho filtru jsou alternativy.",+ "kWMpjI": "Dostupné pro",+ "JtbpIP": "Tento web",+ "sW/jiZ": "Všechny weby v {organization}",+ "NwIme6": "Všechny weby v organizaci",+ "36pzMD": "Hodnoty specifické pro web, například cesty, nemusí na každém webu znamenat totéž.",+ "Q8Qw5B": "Popis",+ "V4KNjk": "volitelné",+ "Q+OCEy": "Proč je tato skupina důležitá",+ "/G0KkW": "Zobrazit na veřejném dashboardu a v soukromých odkazech",+ "K3r6DQ": "Smazat",+ "VREmFv": "Smazat segment?",+ "SLHC6B": "„{name}“ bude odstraněn všem, kdo jej používají. Odkazy, které už jeho filtry rozbalily, budou dál fungovat.",+ "47FYwb": "Zrušit",+ "TiR/Hq": "Ukládám...",+ "X0ha1a": "Uložit změny",+ "IAEaaA": "Uložit segment",+ "WhVNRN": "Uložit aktuální filtry jako segment",+ "uncWxg": "Zatím žádné segmenty",+ "wWQxTq": "Uložte sadu filtrů a použijte ji jedním kliknutím v libovolném reportu.",+ "Dxi6lc": "Vlastník webu na tomto dashboardu nesdílí žádné segmenty.",+ "RQTMq0": "Hledat segmenty",+ "YbW6Km": "Zobrazeno na veřejném dashboardu",+ "ECRv+D": "Akce segmentu","kJfNiC": "Produktové stránky s číselnými ID","gvs2SV": "Porovnání bez ohledu na velikost písmen pro 'newsletter'","XZLB7j": "Cesty NEobsahující 'test'",@@ -301,7 +344,6 @@"ANmBWb": "Test CTA na stránce pokladny","iBImEo": "Hypotéza","JfUnvy": "Změna textu CTA zvýší konverze registrací.",- "Q8Qw5B": "Popis","Yx6aRS": "Volitelné poznámky k tomuto experimentu","F4tWun": "Vytvořit nový příznak","rv+WdZ": "Nejlepší pro nový experiment, který potřebuje vlastní rozdělení přiřazení.",@@ -354,11 +396,8 @@"LHF3Za": "Existující","W6nwjo": "Koncept","rbrahO": "Zavřít",- "47FYwb": "Zrušit","cyR7Kh": "Zpět",- "TiR/Hq": "Ukládám...","mRL9Vh": "Vytvářím...",- "X0ha1a": "Uložit změny","JXdbo8": "Hotovo","acrOoz": "Pokračovat","H+vBOj": "Vítěz",@@ -391,7 +430,6 @@"U78NhE": "Dokončeno","wL7VAE": "Akce","wEQDC6": "Upravit",- "K3r6DQ": "Smazat","poMLbD": "Filtrovat experimenty","qzqYO3": "Nebyly nalezeny žádné experimenty","4YGHzj": "Žádné experimenty neodpovídají „{search}“",@@ -406,7 +444,6 @@"lKv8ex": "Výchozí","wmFdws": "Přesunout nahoru","H/r5m6": "Přesunout dolů",- "G/yZLu": "Odebrat","7/7DdD": "Konfigurační payload","Cn4/rZ": "Payload","Vwukkb": "Přidat JSON payload",@@ -803,7 +840,6 @@"g4dAtI": "Přiřaďte tomuto návštěvníkovi ID uživatele. Jeho dosavadní aktivita z tohoto zařízení k němu bude propojena.","KE2jY+": "","J6C2uX": "ID, které má tato osoba ve vašem vlastním systému, například e-mail nebo ID účtu.",- "HAlOn1": "Jméno","hDGMjf": "","sy+pv5": "E-mail","MQYmtr": "",diff --git a/client/messages/de.json b/client/messages/de.jsonindex d66f0a419..36b7258b1 100644--- a/client/messages/de.json+++ b/client/messages/de.json@@ -113,6 +113,19 @@"FIKvUB": "Website hinzufügen","Dg2v6W": "Wert auswählen","oCBPQ4": "Filter entfernen",+ "fB09El": "Pfade, die mit /blog/ beginnen",+ "nnuMWB": "Pfade, die /blog/ gefolgt von beliebigem Inhalt enthalten",+ "GBIt8l": "Pfade, die auf .pdf, .doc oder .docx enden",+ "o7g8s9": "z.B. ^/blog/.*",+ "uxcVP6": "Wert eingeben...",+ "dhMkG9": "Regex-Beispiele:",+ "kYpf9a": "Wert suchen oder hinzufügen",+ "gjBiyj": "Wird geladen...",+ "jHJmjf": "Keine Ergebnisse",+ "2/2yg+": "Hinzufügen",+ "SElbF+": "Filter speichern",+ "oZhbMq": "Statistiken filtern nach",+ "xmcVZ0": "Suchen","LeFOAk": "Filter für diese Seite nicht aktiv","vONi+O": "Land","2eRO6y": "Gerätetyp",@@ -170,20 +183,50 @@"hJL4XZ": "Kleiner als","m0lxVQ": "Größer oder gleich","qib0lb": "Kleiner oder gleich",- "fB09El": "Pfade, die mit /blog/ beginnen",- "nnuMWB": "Pfade, die /blog/ gefolgt von beliebigem Inhalt enthalten",- "GBIt8l": "Pfade, die auf .pdf, .doc oder .docx enden",- "o7g8s9": "z.B. ^/blog/.*",- "uxcVP6": "Wert eingeben...",- "dhMkG9": "Regex-Beispiele:",- "kYpf9a": "Wert suchen oder hinzufügen",- "gjBiyj": "Wird geladen...",- "jHJmjf": "Keine Ergebnisse",- "2/2yg+": "Hinzufügen",- "SElbF+": "Filter speichern","9Obw6C": "Filter",- "oZhbMq": "Statistiken filtern nach",- "xmcVZ0": "Suchen",+ "VF3DcR": "Segmente",+ "gy/Kkr": "(bearbeitet)",+ "/AMnMU": "Für alle Websites der Organisation freigegeben",+ "wqoG/5": "Definiert als",+ "1d0t7e": "Einige dieser Filter wurden im Dashboard geändert. Das Segment selbst ist unverändert.",+ "PO3ZXG": "Segment bearbeiten",+ "djNL6D": "Schreibgeschützt",+ "G/yZLu": "Entfernen",+ "j6Cfhx": "Segment entfernen",+ "uHnMYi": "Neues Segment",+ "+NhXOR": "Änderungen gelten überall, wo dieses Segment verwendet wird.",+ "1rREuf": "Ein Segment ist eine benannte Filterkombination, die du mit einem Klick auf jeden Bericht anwenden kannst.",+ "FIs3zs": "Segment „{name}“ gespeichert",+ "SubaMm": "Segment konnte nicht gespeichert werden",+ "wFGilL": "Segment „{name}“ gelöscht",+ "gXXeAo": "Segment konnte nicht gelöscht werden",+ "HAlOn1": "Name",+ "C1QAaZ": "z. B. Mobil, organisch, aus Deutschland",+ "M/zZVx": "Filter hinzufügen",+ "VkGJJD": "Alle Filter müssen zutreffen. Werte innerhalb eines Filters sind Alternativen.",+ "kWMpjI": "Verfügbar für",+ "JtbpIP": "Diese Website",+ "sW/jiZ": "Alle Websites in {organization}",+ "NwIme6": "Alle Websites der Organisation",+ "36pzMD": "Website-spezifische Werte wie Pfade bedeuten nicht auf jeder Website dasselbe.",+ "Q8Qw5B": "Beschreibung",+ "V4KNjk": "optional",+ "Q+OCEy": "Warum diese Gruppe wichtig ist",+ "/G0KkW": "Im öffentlichen Dashboard und in privaten Links anzeigen",+ "K3r6DQ": "Löschen",+ "VREmFv": "Segment löschen?",+ "SLHC6B": "„{name}“ wird für alle entfernt, die es verwenden. Links, die seine Filter bereits enthalten, funktionieren weiterhin.",+ "47FYwb": "Abbrechen",+ "TiR/Hq": "Wird gespeichert...",+ "X0ha1a": "Änderungen speichern",+ "IAEaaA": "Segment speichern",+ "WhVNRN": "Aktuelle Filter als Segment speichern",+ "uncWxg": "Noch keine Segmente",+ "wWQxTq": "Speichere eine Filterkombination, um sie mit einem Klick in jedem Bericht wiederzuverwenden.",+ "Dxi6lc": "Der Website-Inhaber hat in diesem Dashboard keine Segmente freigegeben.",+ "RQTMq0": "Segmente durchsuchen",+ "YbW6Km": "Im öffentlichen Dashboard sichtbar",+ "ECRv+D": "Segmentaktionen","kJfNiC": "Produktseiten mit numerischen IDs","gvs2SV": "Groß-/Kleinschreibung ignorierende Suche nach 'newsletter'","XZLB7j": "Pfade, die NICHT 'test' enthalten",@@ -301,7 +344,6 @@"ANmBWb": "Checkout-CTA-Test","iBImEo": "Hypothese","JfUnvy": "Das Ändern des CTA-Textes wird die Anmelde-Konversionen erhöhen.",- "Q8Qw5B": "Beschreibung","Yx6aRS": "Optionale Notizen für dieses Experiment","F4tWun": "Neues Flag erstellen","rv+WdZ": "Am besten für ein neues Experiment, das eine eigene Zuteilungsaufteilung benötigt.",@@ -354,11 +396,8 @@"LHF3Za": "Vorhanden","W6nwjo": "Entwurf","rbrahO": "Schließen",- "47FYwb": "Abbrechen","cyR7Kh": "Zurück",- "TiR/Hq": "Wird gespeichert...","mRL9Vh": "Wird erstellt...",- "X0ha1a": "Änderungen speichern","JXdbo8": "Fertig","acrOoz": "Weiter","H+vBOj": "Gewinner",@@ -391,7 +430,6 @@"U78NhE": "Abgeschlossen","wL7VAE": "Aktionen","wEQDC6": "Bearbeiten",- "K3r6DQ": "Löschen","poMLbD": "Experimente filtern","qzqYO3": "Keine Experimente gefunden","4YGHzj": "Keine Experimente entsprechen \"{search}\"",@@ -406,7 +444,6 @@"lKv8ex": "Standard","wmFdws": "Nach oben verschieben","H/r5m6": "Nach unten verschieben",- "G/yZLu": "Entfernen","7/7DdD": "Konfigurations-Payload","Cn4/rZ": "Nutzlast","Vwukkb": "JSON-Payload hinzufügen",@@ -803,7 +840,6 @@"g4dAtI": "Weisen Sie diesem Besucher eine Benutzer-ID zu. Seine bisherige Aktivität von diesem Gerät wird damit verknüpft.","KE2jY+": "","J6C2uX": "Die ID, die diese Person in Ihrem eigenen System hat, z. B. eine E-Mail oder Konto-ID.",- "HAlOn1": "Name","hDGMjf": "","sy+pv5": "E-Mail","MQYmtr": "",diff --git a/client/messages/en.json b/client/messages/en.jsonindex 8e3a3ffcf..83781d74e 100644--- a/client/messages/en.json+++ b/client/messages/en.json@@ -113,6 +113,19 @@"FIKvUB": "Add Site","Dg2v6W": "pick value","oCBPQ4": "Remove filter",+ "fB09El": "Paths starting with /blog/",+ "nnuMWB": "Paths containing /blog/ followed by anything",+ "GBIt8l": "Paths ending in .pdf, .doc, or .docx",+ "o7g8s9": "e.g. ^/blog/.*",+ "uxcVP6": "Enter value...",+ "dhMkG9": "Regex Examples:",+ "kYpf9a": "Search or add value",+ "gjBiyj": "Loading...",+ "jHJmjf": "No results",+ "2/2yg+": "Add",+ "SElbF+": "Save filter",+ "oZhbMq": "Filter stats by",+ "xmcVZ0": "Search","LeFOAk": "Filter not active for this page","vONi+O": "Country","2eRO6y": "Device Type",@@ -170,20 +183,50 @@"hJL4XZ": "Less than","m0lxVQ": "Greater than or equal to","qib0lb": "Less than or equal to",- "fB09El": "Paths starting with /blog/",- "nnuMWB": "Paths containing /blog/ followed by anything",- "GBIt8l": "Paths ending in .pdf, .doc, or .docx",- "o7g8s9": "e.g. ^/blog/.*",- "uxcVP6": "Enter value...",- "dhMkG9": "Regex Examples:",- "kYpf9a": "Search or add value",- "gjBiyj": "Loading...",- "jHJmjf": "No results",- "2/2yg+": "Add",- "SElbF+": "Save filter","9Obw6C": "Filter",- "oZhbMq": "Filter stats by",- "xmcVZ0": "Search",+ "VF3DcR": "Segments",+ "gy/Kkr": "(edited)",+ "/AMnMU": "Shared with every site in the organization",+ "wqoG/5": "Defined as",+ "1d0t7e": "Some of these filters were changed on the dashboard. The segment itself is unchanged.",+ "PO3ZXG": "Edit segment",+ "djNL6D": "Read-only",+ "G/yZLu": "Remove",+ "j6Cfhx": "Remove segment",+ "uHnMYi": "New segment",+ "+NhXOR": "Changes apply everywhere this segment is used.",+ "1rREuf": "A segment is a named set of filters you can apply to any report with one click.",+ "FIs3zs": "Saved segment “{name}”",+ "SubaMm": "Failed to save segment",+ "wFGilL": "Deleted segment “{name}”",+ "gXXeAo": "Failed to delete segment",+ "HAlOn1": "Name",+ "C1QAaZ": "e.g. Mobile organic from Germany",+ "M/zZVx": "Add filter",+ "VkGJJD": "Every filter must match. Values within one filter are alternatives.",+ "kWMpjI": "Available on",+ "JtbpIP": "This site",+ "sW/jiZ": "All sites in {organization}",+ "NwIme6": "All sites in the organization",+ "36pzMD": "Site-specific values such as paths may not mean the same thing on every site.",+ "Q8Qw5B": "Description",+ "V4KNjk": "optional",+ "Q+OCEy": "Why this group matters",+ "/G0KkW": "Show on the public dashboard and private links",+ "K3r6DQ": "Delete",+ "VREmFv": "Delete segment?",+ "SLHC6B": "“{name}” will be removed for everyone who uses it. Links that already expanded its filters keep working.",+ "47FYwb": "Cancel",+ "TiR/Hq": "Saving...",+ "X0ha1a": "Save changes",+ "IAEaaA": "Save segment",+ "WhVNRN": "Save current filters as segment",+ "uncWxg": "No segments yet",+ "wWQxTq": "Save a set of filters to reuse it on any report with one click.",+ "Dxi6lc": "The site owner has not shared any segments on this dashboard.",+ "RQTMq0": "Search segments",+ "YbW6Km": "Shown on the public dashboard",+ "ECRv+D": "Segment actions","kJfNiC": "Product pages with numeric IDs","gvs2SV": "Case-insensitive match for 'newsletter'","XZLB7j": "Paths NOT containing 'test'",@@ -301,7 +344,6 @@"ANmBWb": "Checkout CTA test","iBImEo": "Hypothesis","JfUnvy": "Changing the CTA copy will increase signup conversions.",- "Q8Qw5B": "Description","Yx6aRS": "Optional notes for this experiment","F4tWun": "Create a new flag","rv+WdZ": "Best for a new experiment that needs its own assignment split.",@@ -354,11 +396,8 @@"LHF3Za": "Existing","W6nwjo": "Draft","rbrahO": "Close",- "47FYwb": "Cancel","cyR7Kh": "Back",- "TiR/Hq": "Saving...","mRL9Vh": "Creating...",- "X0ha1a": "Save changes","JXdbo8": "Done","acrOoz": "Continue","H+vBOj": "Winner",@@ -391,7 +430,6 @@"U78NhE": "Complete","wL7VAE": "Actions","wEQDC6": "Edit",- "K3r6DQ": "Delete","poMLbD": "Filter experiments","qzqYO3": "No experiments found","4YGHzj": "No experiments match \"{search}\"",@@ -406,7 +444,6 @@"lKv8ex": "Default","wmFdws": "Move up","H/r5m6": "Move down",- "G/yZLu": "Remove","7/7DdD": "Config payload","Cn4/rZ": "Payload","Vwukkb": "Add JSON payload",@@ -803,7 +840,6 @@"g4dAtI": "Assign a user ID to this visitor. Their past activity from this device will be linked to it.","KE2jY+": "e.g. user_123","J6C2uX": "The ID this person has in your own system, like an email or account ID.",- "HAlOn1": "Name","hDGMjf": "e.g. Ada Lovelace","sy+pv5": "Email","MQYmtr": "e.g. [email protected]",diff --git a/client/messages/es.json b/client/messages/es.jsonindex f2a40b0f7..77d024577 100644--- a/client/messages/es.json+++ b/client/messages/es.json@@ -113,6 +113,19 @@"FIKvUB": "Añadir sitio","Dg2v6W": "elegir valor","oCBPQ4": "Eliminar filtro",+ "fB09El": "Rutas que comienzan con /blog/",+ "nnuMWB": "Rutas que contienen /blog/ seguido de cualquier cosa",+ "GBIt8l": "Rutas que terminan en .pdf, .doc, o .docx",+ "o7g8s9": "ej. ^/blog/.*",+ "uxcVP6": "Introducir valor...",+ "dhMkG9": "Ejemplos de Regex:",+ "kYpf9a": "Buscar o añadir valor",+ "gjBiyj": "Cargando...",+ "jHJmjf": "Sin resultados",+ "2/2yg+": "Añadir",+ "SElbF+": "Guardar filtro",+ "oZhbMq": "Filtrar estadísticas por",+ "xmcVZ0": "Buscar","LeFOAk": "Filtro no activo para esta página","vONi+O": "País","2eRO6y": "Tipo de dispositivo",@@ -170,20 +183,50 @@"hJL4XZ": "Menor que","m0lxVQ": "Mayor o igual a","qib0lb": "Menor o igual a",- "fB09El": "Rutas que comienzan con /blog/",- "nnuMWB": "Rutas que contienen /blog/ seguido de cualquier cosa",- "GBIt8l": "Rutas que terminan en .pdf, .doc, o .docx",- "o7g8s9": "ej. ^/blog/.*",- "uxcVP6": "Introducir valor...",- "dhMkG9": "Ejemplos de Regex:",- "kYpf9a": "Buscar o añadir valor",- "gjBiyj": "Cargando...",- "jHJmjf": "Sin resultados",- "2/2yg+": "Añadir",- "SElbF+": "Guardar filtro","9Obw6C": "Filtro",- "oZhbMq": "Filtrar estadísticas por",- "xmcVZ0": "Buscar",+ "VF3DcR": "Segmentos",+ "gy/Kkr": "(editado)",+ "/AMnMU": "Compartido con todos los sitios de la organización",+ "wqoG/5": "Definido como",+ "1d0t7e": "Algunos de estos filtros se cambiaron en el panel. El segmento en sí no ha cambiado.",+ "PO3ZXG": "Editar segmento",+ "djNL6D": "Solo lectura",+ "G/yZLu": "Eliminar",+ "j6Cfhx": "Quitar segmento",+ "uHnMYi": "Nuevo segmento",+ "+NhXOR": "Los cambios se aplican en todos los lugares donde se usa este segmento.",+ "1rREuf": "Un segmento es un conjunto de filtros con nombre que puedes aplicar a cualquier informe con un clic.",+ "FIs3zs": "Segmento «{name}» guardado",+ "SubaMm": "No se pudo guardar el segmento",+ "wFGilL": "Segmento «{name}» eliminado",+ "gXXeAo": "No se pudo eliminar el segmento",+ "HAlOn1": "Nombre",+ "C1QAaZ": "p. ej. Móvil orgánico desde Alemania",+ "M/zZVx": "Añadir filtro",+ "VkGJJD": "Todos los filtros deben cumplirse. Los valores dentro de un mismo filtro son alternativas.",+ "kWMpjI": "Disponible en",+ "JtbpIP": "Este sitio",+ "sW/jiZ": "Todos los sitios de {organization}",+ "NwIme6": "Todos los sitios de la organización",+ "36pzMD": "Los valores específicos del sitio, como las rutas, pueden no significar lo mismo en todos los sitios.",+ "Q8Qw5B": "Descripción",+ "V4KNjk": "opcional",+ "Q+OCEy": "Por qué importa este grupo",+ "/G0KkW": "Mostrar en el panel público y en los enlaces privados",+ "K3r6DQ": "Eliminar",+ "VREmFv": "¿Eliminar segmento?",+ "SLHC6B": "«{name}» se eliminará para todos los que lo usan. Los enlaces que ya expandieron sus filtros seguirán funcionando.",+ "47FYwb": "Cancelar",+ "TiR/Hq": "Guardando...",+ "X0ha1a": "Guardar cambios",+ "IAEaaA": "Guardar segmento",+ "WhVNRN": "Guardar filtros actuales como segmento",+ "uncWxg": "Aún no hay segmentos",+ "wWQxTq": "Guarda un conjunto de filtros para reutilizarlo en cualquier informe con un clic.",+ "Dxi6lc": "El propietario del sitio no ha compartido segmentos en este panel.",+ "RQTMq0": "Buscar segmentos",+ "YbW6Km": "Visible en el panel público",+ "ECRv+D": "Acciones del segmento","kJfNiC": "Páginas de producto con IDs numéricos","gvs2SV": "Coincidencia sin distinguir mayúsculas de 'newsletter'","XZLB7j": "Rutas que NO contienen 'test'",@@ -301,7 +344,6 @@"ANmBWb": "Prueba de CTA de pago","iBImEo": "Hipótesis","JfUnvy": "Cambiar el texto del CTA aumentará las conversiones de registro.",- "Q8Qw5B": "Descripción","Yx6aRS": "Notas opcionales para este experimento","F4tWun": "Crear una nueva bandera","rv+WdZ": "Lo mejor para un nuevo experimento que necesita su propia distribución de asignación.",@@ -354,11 +396,8 @@"LHF3Za": "Existente","W6nwjo": "Borrador","rbrahO": "Cerrar",- "47FYwb": "Cancelar","cyR7Kh": "Atrás",- "TiR/Hq": "Guardando...","mRL9Vh": "Creando...",- "X0ha1a": "Guardar cambios","JXdbo8": "Hecho","acrOoz": "Continuar","H+vBOj": "Ganador",@@ -391,7 +430,6 @@"U78NhE": "Completado","wL7VAE": "Acciones","wEQDC6": "Editar",- "K3r6DQ": "Eliminar","poMLbD": "Filtrar experimentos","qzqYO3": "No se encontraron experimentos","4YGHzj": "Ningún experimento coincide con \"{search}\"",@@ -406,7 +444,6 @@"lKv8ex": "Por defecto","wmFdws": "Mover hacia arriba","H/r5m6": "Mover hacia abajo",- "G/yZLu": "Eliminar","7/7DdD": "Carga útil de configuración","Cn4/rZ": "Carga útil","Vwukkb": "Añadir carga útil JSON",@@ -803,7 +840,6 @@"g4dAtI": "Asigna un ID de usuario a este visitante. Su actividad anterior desde este dispositivo quedará vinculada a él.","KE2jY+": "","J6C2uX": "El ID de esta persona en tu propio sistema, como un correo electrónico o un ID de cuenta.",- "HAlOn1": "Nombre","hDGMjf": "","sy+pv5": "Correo electrónico","MQYmtr": "",diff --git a/client/messages/fr.json b/client/messages/fr.jsonindex 0ad2649c1..f9bde1a07 100644--- a/client/messages/fr.json+++ b/client/messages/fr.json@@ -113,6 +113,19 @@"FIKvUB": "Ajouter un site","Dg2v6W": "choisir une valeur","oCBPQ4": "Supprimer le filtre",+ "fB09El": "Chemins commençant par /blog/",+ "nnuMWB": "Chemins contenant /blog/ suivi de n'importe quoi",+ "GBIt8l": "Chemins se terminant par .pdf, .doc ou .docx",+ "o7g8s9": "ex. ^/blog/.*",+ "uxcVP6": "Saisir une valeur...",+ "dhMkG9": "Exemples de regex :",+ "kYpf9a": "Rechercher ou ajouter une valeur",+ "gjBiyj": "Chargement...",+ "jHJmjf": "Aucun résultat",+ "2/2yg+": "Ajouter",+ "SElbF+": "Sauvegarder le filtre",+ "oZhbMq": "Filtrer les statistiques par",+ "xmcVZ0": "Rechercher","LeFOAk": "Filtre non actif pour cette page","vONi+O": "Pays","2eRO6y": "Type d'appareil",@@ -170,20 +183,50 @@"hJL4XZ": "Inférieur à","m0lxVQ": "Supérieur ou égal à","qib0lb": "Inférieur ou égal à",- "fB09El": "Chemins commençant par /blog/",- "nnuMWB": "Chemins contenant /blog/ suivi de n'importe quoi",- "GBIt8l": "Chemins se terminant par .pdf, .doc ou .docx",- "o7g8s9": "ex. ^/blog/.*",- "uxcVP6": "Saisir une valeur...",- "dhMkG9": "Exemples de regex :",- "kYpf9a": "Rechercher ou ajouter une valeur",- "gjBiyj": "Chargement...",- "jHJmjf": "Aucun résultat",- "2/2yg+": "Ajouter",- "SElbF+": "Sauvegarder le filtre","9Obw6C": "Filtre",- "oZhbMq": "Filtrer les statistiques par",- "xmcVZ0": "Rechercher",+ "VF3DcR": "Segments",+ "gy/Kkr": "(modifié)",+ "/AMnMU": "Partagé avec tous les sites de l'organisation",+ "wqoG/5": "Défini comme",+ "1d0t7e": "Certains de ces filtres ont été modifiés sur le tableau de bord. Le segment lui-même est inchangé.",+ "PO3ZXG": "Modifier le segment",+ "djNL6D": "Lecture seule",+ "G/yZLu": "Supprimer",+ "j6Cfhx": "Retirer le segment",+ "uHnMYi": "Nouveau segment",+ "+NhXOR": "Les modifications s'appliquent partout où ce segment est utilisé.",+ "1rREuf": "Un segment est un ensemble nommé de filtres que vous pouvez appliquer à n'importe quel rapport en un clic.",+ "FIs3zs": "Segment « {name} » enregistré",+ "SubaMm": "Impossible d'enregistrer le segment",+ "wFGilL": "Segment « {name} » supprimé",+ "gXXeAo": "Impossible de supprimer le segment",+ "HAlOn1": "Nom",+ "C1QAaZ": "ex. Mobile organique depuis l'Allemagne",+ "M/zZVx": "Ajouter un filtre",+ "VkGJJD": "Tous les filtres doivent correspondre. Les valeurs d'un même filtre sont des alternatives.",+ "kWMpjI": "Disponible sur",+ "JtbpIP": "Ce site",+ "sW/jiZ": "Tous les sites de {organization}",+ "NwIme6": "Tous les sites de l'organisation",+ "36pzMD": "Les valeurs propres à un site, comme les chemins, n'ont pas forcément le même sens sur chaque site.",+ "Q8Qw5B": "Description",+ "V4KNjk": "facultatif",+ "Q+OCEy": "Pourquoi ce groupe est important",+ "/G0KkW": "Afficher sur le tableau de bord public et les liens privés",+ "K3r6DQ": "Supprimer",+ "VREmFv": "Supprimer le segment ?",+ "SLHC6B": "« {name} » sera supprimé pour tous ceux qui l'utilisent. Les liens qui ont déjà développé ses filtres continueront de fonctionner.",+ "47FYwb": "Annuler",+ "TiR/Hq": "Enregistrement en cours...",+ "X0ha1a": "Enregistrer les modifications",+ "IAEaaA": "Enregistrer le segment",+ "WhVNRN": "Enregistrer les filtres actuels comme segment",+ "uncWxg": "Aucun segment pour le moment",+ "wWQxTq": "Enregistrez un ensemble de filtres pour le réutiliser dans n'importe quel rapport en un clic.",+ "Dxi6lc": "Le propriétaire du site n'a partagé aucun segment sur ce tableau de bord.",+ "RQTMq0": "Rechercher des segments",+ "YbW6Km": "Affiché sur le tableau de bord public",+ "ECRv+D": "Actions du segment","kJfNiC": "Pages de produits avec des ID numériques","gvs2SV": "Correspondance insensible à la casse pour 'newsletter'","XZLB7j": "Chemins NE contenant PAS 'test'",@@ -301,7 +344,6 @@"ANmBWb": "Test CTA checkout","iBImEo": "Hypothèse","JfUnvy": "Modifier le texte du CTA augmentera les conversions d'inscription.",- "Q8Qw5B": "Description","Yx6aRS": "Notes facultatives pour cette expérience","F4tWun": "Créer un nouveau drapeau","rv+WdZ": "Idéal pour une nouvelle expérience nécessitant sa propre répartition d'assignation.",@@ -354,11 +396,8 @@"LHF3Za": "Existant","W6nwjo": "Brouillon","rbrahO": "Fermer",- "47FYwb": "Annuler","cyR7Kh": "Retour",- "TiR/Hq": "Enregistrement en cours...","mRL9Vh": "Création en cours...",- "X0ha1a": "Enregistrer les modifications","JXdbo8": "Terminé","acrOoz": "Continuer","H+vBOj": "Gagnant",@@ -391,7 +430,6 @@"U78NhE": "Terminé","wL7VAE": "Actions","wEQDC6": "Modifier",- "K3r6DQ": "Supprimer","poMLbD": "Filtrer les expériences","qzqYO3": "Aucune expérience trouvée","4YGHzj": "Aucune expérience ne correspond à \"{search}\"",@@ -406,7 +444,6 @@"lKv8ex": "Par défaut","wmFdws": "Déplacer vers le haut","H/r5m6": "Déplacer vers le bas",- "G/yZLu": "Supprimer","7/7DdD": "Charge utile de config","Cn4/rZ": "Charge utile","Vwukkb": "Ajouter une charge utile JSON",@@ -803,7 +840,6 @@"g4dAtI": "Attribuez un identifiant utilisateur à ce visiteur. Son activité passée depuis cet appareil y sera associée.","KE2jY+": "","J6C2uX": "L'identifiant de cette personne dans votre propre système, comme un e-mail ou un ID de compte.",- "HAlOn1": "Nom","hDGMjf": "","sy+pv5": "E-mail","MQYmtr": "",diff --git a/client/messages/it.json b/client/messages/it.jsonindex b130ed4a0..7246b6239 100644--- a/client/messages/it.json+++ b/client/messages/it.json@@ -113,6 +113,19 @@"FIKvUB": "Aggiungi Sito","Dg2v6W": "scegli valore","oCBPQ4": "Rimuovi filtro",+ "fB09El": "Percorsi che iniziano con /blog/",+ "nnuMWB": "Percorsi che contengono /blog/ seguito da qualsiasi cosa",+ "GBIt8l": "Percorsi che finiscono in .pdf, .doc, o .docx",+ "o7g8s9": "es. ^/blog/.*",+ "uxcVP6": "Inserisci valore...",+ "dhMkG9": "Esempi Regex:",+ "kYpf9a": "Cerca o aggiungi valore",+ "gjBiyj": "Caricamento in corso...",+ "jHJmjf": "Nessun risultato",+ "2/2yg+": "Aggiungi",+ "SElbF+": "Salva filtro",+ "oZhbMq": "Filtra statistiche per",+ "xmcVZ0": "Cerca","LeFOAk": "Filtro non attivo per questa pagina","vONi+O": "Paese","2eRO6y": "Tipo di Dispositivo",@@ -170,20 +183,50 @@"hJL4XZ": "Minore di","m0lxVQ": "Maggiore o uguale a","qib0lb": "Minore o uguale a",- "fB09El": "Percorsi che iniziano con /blog/",- "nnuMWB": "Percorsi che contengono /blog/ seguito da qualsiasi cosa",- "GBIt8l": "Percorsi che finiscono in .pdf, .doc, o .docx",- "o7g8s9": "es. ^/blog/.*",- "uxcVP6": "Inserisci valore...",- "dhMkG9": "Esempi Regex:",- "kYpf9a": "Cerca o aggiungi valore",- "gjBiyj": "Caricamento in corso...",- "jHJmjf": "Nessun risultato",- "2/2yg+": "Aggiungi",- "SElbF+": "Salva filtro","9Obw6C": "Filtro",- "oZhbMq": "Filtra statistiche per",- "xmcVZ0": "Cerca",+ "VF3DcR": "Segmenti",+ "gy/Kkr": "(modificato)",+ "/AMnMU": "Condiviso con tutti i siti dell'organizzazione",+ "wqoG/5": "Definito come",+ "1d0t7e": "Alcuni di questi filtri sono stati modificati nella dashboard. Il segmento in sé non è cambiato.",+ "PO3ZXG": "Modifica segmento",+ "djNL6D": "Sola lettura",+ "G/yZLu": "Rimuovi",+ "j6Cfhx": "Rimuovi segmento",+ "uHnMYi": "Nuovo segmento",+ "+NhXOR": "Le modifiche si applicano ovunque questo segmento venga usato.",+ "1rREuf": "Un segmento è un insieme di filtri con un nome che puoi applicare a qualsiasi report con un clic.",+ "FIs3zs": "Segmento “{name}” salvato",+ "SubaMm": "Impossibile salvare il segmento",+ "wFGilL": "Segmento “{name}” eliminato",+ "gXXeAo": "Impossibile eliminare il segmento",+ "HAlOn1": "Nome",+ "C1QAaZ": "es. Mobile organico dalla Germania",+ "M/zZVx": "Aggiungi filtro",+ "VkGJJD": "Tutti i filtri devono corrispondere. I valori all'interno di un filtro sono alternative.",+ "kWMpjI": "Disponibile su",+ "JtbpIP": "Questo sito",+ "sW/jiZ": "Tutti i siti di {organization}",+ "NwIme6": "Tutti i siti dell'organizzazione",+ "36pzMD": "I valori specifici del sito, come i percorsi, potrebbero non avere lo stesso significato su ogni sito.",+ "Q8Qw5B": "Descrizione",+ "V4KNjk": "facoltativo",+ "Q+OCEy": "Perché questo gruppo è importante",+ "/G0KkW": "Mostra nella dashboard pubblica e nei link privati",+ "K3r6DQ": "Elimina",+ "VREmFv": "Eliminare il segmento?",+ "SLHC6B": "“{name}” verrà rimosso per tutti coloro che lo usano. I link che hanno già espanso i suoi filtri continueranno a funzionare.",+ "47FYwb": "Annulla",+ "TiR/Hq": "Salvataggio in corso...",+ "X0ha1a": "Salva modifiche",+ "IAEaaA": "Salva segmento",+ "WhVNRN": "Salva i filtri attuali come segmento",+ "uncWxg": "Ancora nessun segmento",+ "wWQxTq": "Salva un insieme di filtri per riutilizzarlo in qualsiasi report con un clic.",+ "Dxi6lc": "Il proprietario del sito non ha condiviso segmenti in questa dashboard.",+ "RQTMq0": "Cerca segmenti",+ "YbW6Km": "Mostrato nella dashboard pubblica",+ "ECRv+D": "Azioni del segmento","kJfNiC": "Pagine prodotto con ID numerici","gvs2SV": "Corrispondenza case-insensitive per 'newsletter'","XZLB7j": "Percorsi che NON contengono 'test'",@@ -301,7 +344,6 @@"ANmBWb": "Test CTA checkout","iBImEo": "Ipotesi","JfUnvy": "Cambiare il testo della CTA aumenterà le conversioni di registrazione.",- "Q8Qw5B": "Descrizione","Yx6aRS": "Note facoltative per questo esperimento","F4tWun": "Crea un nuovo flag","rv+WdZ": "Ideale per un nuovo esperimento che necessita di una propria suddivisione di assegnazione.",@@ -354,11 +396,8 @@"LHF3Za": "Esistente","W6nwjo": "Bozza","rbrahO": "Chiudi",- "47FYwb": "Annulla","cyR7Kh": "Indietro",- "TiR/Hq": "Salvataggio in corso...","mRL9Vh": "Creazione in corso...",- "X0ha1a": "Salva modifiche","JXdbo8": "Fatto","acrOoz": "Continua","H+vBOj": "Vincitore",@@ -391,7 +430,6 @@"U78NhE": "Completo","wL7VAE": "Azioni","wEQDC6": "Modifica",- "K3r6DQ": "Elimina","poMLbD": "Filtra esperimenti","qzqYO3": "Nessun esperimento trovato","4YGHzj": "Nessun esperimento corrisponde a \"{search}\"",@@ -406,7 +444,6 @@"lKv8ex": "Predefinito","wmFdws": "Sposta in alto","H/r5m6": "Sposta in basso",- "G/yZLu": "Rimuovi","7/7DdD": "Payload di configurazione","Cn4/rZ": "Payload","Vwukkb": "Aggiungi payload JSON",@@ -803,7 +840,6 @@"g4dAtI": "Assegna un ID utente a questo visitatore. La sua attività passata da questo dispositivo verrà collegata ad esso.","KE2jY+": "","J6C2uX": "L'ID di questa persona nel tuo sistema, come un'e-mail o un ID account.",- "HAlOn1": "Nome","hDGMjf": "","sy+pv5": "E-mail","MQYmtr": "",diff --git a/client/messages/ja.json b/client/messages/ja.jsonindex 737946340..ff7c713be 100644--- a/client/messages/ja.json+++ b/client/messages/ja.json@@ -113,6 +113,19 @@"FIKvUB": "サイトを追加","Dg2v6W": "値を選択","oCBPQ4": "フィルターを削除",+ "fB09El": "/blog/で始まるパス",+ "nnuMWB": "/blog/を含むパスとその後に続く任意の文字列",+ "GBIt8l": ".pdf、.doc、.docxで終わるパス",+ "o7g8s9": "例: ^/blog/.*",+ "uxcVP6": "値を入力...",+ "dhMkG9": "正規表現の例:",+ "kYpf9a": "値を検索または追加",+ "gjBiyj": "読み込み中...",+ "jHJmjf": "結果なし",+ "2/2yg+": "追加",+ "SElbF+": "フィルターを保存",+ "oZhbMq": "統計のフィルター",+ "xmcVZ0": "検索","LeFOAk": "このページではフィルターが無効です","vONi+O": "国","2eRO6y": "デバイスタイプ",@@ -170,20 +183,50 @@"hJL4XZ": "より小さい","m0lxVQ": "以上","qib0lb": "以下",- "fB09El": "/blog/で始まるパス",- "nnuMWB": "/blog/を含むパスとその後に続く任意の文字列",- "GBIt8l": ".pdf、.doc、.docxで終わるパス",- "o7g8s9": "例: ^/blog/.*",- "uxcVP6": "値を入力...",- "dhMkG9": "正規表現の例:",- "kYpf9a": "値を検索または追加",- "gjBiyj": "読み込み中...",- "jHJmjf": "結果なし",- "2/2yg+": "追加",- "SElbF+": "フィルターを保存","9Obw6C": "フィルター",- "oZhbMq": "統計のフィルター",- "xmcVZ0": "検索",+ "VF3DcR": "セグメント",+ "gy/Kkr": "(編集済み)",+ "/AMnMU": "組織内のすべてのサイトで共有",+ "wqoG/5": "定義",+ "1d0t7e": "これらのフィルターの一部はダッシュボード上で変更されています。セグメント自体は変更されていません。",+ "PO3ZXG": "セグメントを編集",+ "djNL6D": "読み取り専用",+ "G/yZLu": "削除",+ "j6Cfhx": "セグメントを解除",+ "uHnMYi": "新しいセグメント",+ "+NhXOR": "変更はこのセグメントが使われているすべての場所に反映されます。",+ "1rREuf": "セグメントとは、名前を付けたフィルターの組み合わせで、どのレポートにもワンクリックで適用できます。",+ "FIs3zs": "セグメント「{name}」を保存しました",+ "SubaMm": "セグメントを保存できませんでした",+ "wFGilL": "セグメント「{name}」を削除しました",+ "gXXeAo": "セグメントを削除できませんでした",+ "HAlOn1": "名前",+ "C1QAaZ": "例:ドイツからのモバイル自然検索",+ "M/zZVx": "フィルターを追加",+ "VkGJJD": "すべてのフィルターに一致する必要があります。1つのフィルター内の値はいずれかに一致すれば適用されます。",+ "kWMpjI": "利用可能な範囲",+ "JtbpIP": "このサイト",+ "sW/jiZ": "{organization} のすべてのサイト",+ "NwIme6": "組織内のすべてのサイト",+ "36pzMD": "パスなどサイト固有の値は、サイトによって意味が異なる場合があります。",+ "Q8Qw5B": "説明",+ "V4KNjk": "任意",+ "Q+OCEy": "このグループが重要な理由",+ "/G0KkW": "公開ダッシュボードとプライベートリンクに表示",+ "K3r6DQ": "削除",+ "VREmFv": "セグメントを削除しますか?",+ "SLHC6B": "「{name}」は使用しているすべてのユーザーから削除されます。すでにフィルターを展開したリンクはそのまま動作します。",+ "47FYwb": "キャンセル",+ "TiR/Hq": "保存中...",+ "X0ha1a": "変更を保存",+ "IAEaaA": "セグメントを保存",+ "WhVNRN": "現在のフィルターをセグメントとして保存",+ "uncWxg": "セグメントはまだありません",+ "wWQxTq": "フィルターの組み合わせを保存すると、どのレポートでもワンクリックで再利用できます。",+ "Dxi6lc": "サイトの所有者はこのダッシュボードでセグメントを共有していません。",+ "RQTMq0": "セグメントを検索",+ "YbW6Km": "公開ダッシュボードに表示",+ "ECRv+D": "セグメントの操作","kJfNiC": "数値IDの商品ページ","gvs2SV": "'newsletter'の大文字小文字を区別しない一致","XZLB7j": "'test'を含まないパス",@@ -301,7 +344,6 @@"ANmBWb": "チェックアウトCTAテスト","iBImEo": "仮説","JfUnvy": "CTAのコピーを変更するとサインアップのコンバージョン率が向上する。",- "Q8Qw5B": "説明","Yx6aRS": "この実験の任意のメモ","F4tWun": "新しいフラグを作成","rv+WdZ": "独自の割り当て分割が必要な新しい実験に最適です。",@@ -354,11 +396,8 @@"LHF3Za": "既存","W6nwjo": "下書き","rbrahO": "閉じる",- "47FYwb": "キャンセル","cyR7Kh": "戻る",- "TiR/Hq": "保存中...","mRL9Vh": "作成中...",- "X0ha1a": "変更を保存","JXdbo8": "完了","acrOoz": "続行","H+vBOj": "勝者",@@ -391,7 +430,6 @@"U78NhE": "完了","wL7VAE": "操作","wEQDC6": "編集",- "K3r6DQ": "削除","poMLbD": "実験を絞り込む","qzqYO3": "実験が見つかりません","4YGHzj": "\"{search}\"に一致する実験はありません",@@ -406,7 +444,6 @@"lKv8ex": "デフォルト","wmFdws": "上へ移動","H/r5m6": "下へ移動",- "G/yZLu": "削除","7/7DdD": "設定のペイロード","Cn4/rZ": "ペイロード","Vwukkb": "JSONペイロードを追加",@@ -803,7 +840,6 @@"g4dAtI": "この訪問者にユーザー ID を割り当てます。このデバイスからの過去のアクティビティがその ID に関連付けられます。","KE2jY+": "","J6C2uX": "自社システムでのこの人物の ID(メールアドレスやアカウント ID など)。",- "HAlOn1": "名前","hDGMjf": "","sy+pv5": "メール","MQYmtr": "",diff --git a/client/messages/ko.json b/client/messages/ko.jsonindex aba030522..6abb21bca 100644--- a/client/messages/ko.json+++ b/client/messages/ko.json@@ -113,6 +113,19 @@"FIKvUB": "사이트 추가","Dg2v6W": "값 선택","oCBPQ4": "필터 제거",+ "fB09El": "/blog/로 시작하는 경로",+ "nnuMWB": "/blog/ 다음에 무엇이든 포함하는 경로",+ "GBIt8l": ".pdf, .doc 또는 .docx로 끝나는 경로",+ "o7g8s9": "예: ^/blog/.*",+ "uxcVP6": "값 입력...",+ "dhMkG9": "정규식 예시:",+ "kYpf9a": "값 검색 또는 추가",+ "gjBiyj": "로딩 중...",+ "jHJmjf": "결과 없음",+ "2/2yg+": "추가",+ "SElbF+": "필터 저장",+ "oZhbMq": "통계 필터",+ "xmcVZ0": "검색","LeFOAk": "이 페이지에서 필터가 활성화되지 않음","vONi+O": "국가","2eRO6y": "기기 유형",@@ -170,20 +183,50 @@"hJL4XZ": "보다 작음","m0lxVQ": "이상","qib0lb": "이하",- "fB09El": "/blog/로 시작하는 경로",- "nnuMWB": "/blog/ 다음에 무엇이든 포함하는 경로",- "GBIt8l": ".pdf, .doc 또는 .docx로 끝나는 경로",- "o7g8s9": "예: ^/blog/.*",- "uxcVP6": "값 입력...",- "dhMkG9": "정규식 예시:",- "kYpf9a": "값 검색 또는 추가",- "gjBiyj": "로딩 중...",- "jHJmjf": "결과 없음",- "2/2yg+": "추가",- "SElbF+": "필터 저장","9Obw6C": "필터",- "oZhbMq": "통계 필터",- "xmcVZ0": "검색",+ "VF3DcR": "세그먼트",+ "gy/Kkr": "(수정됨)",+ "/AMnMU": "조직의 모든 사이트와 공유됨",+ "wqoG/5": "정의",+ "1d0t7e": "이 필터 중 일부가 대시보드에서 변경되었습니다. 세그먼트 자체는 변경되지 않았습니다.",+ "PO3ZXG": "세그먼트 편집",+ "djNL6D": "읽기 전용",+ "G/yZLu": "제거",+ "j6Cfhx": "세그먼트 제거",+ "uHnMYi": "새 세그먼트",+ "+NhXOR": "변경 사항은 이 세그먼트가 사용되는 모든 곳에 적용됩니다.",+ "1rREuf": "세그먼트는 이름이 있는 필터 조합으로, 어떤 보고서에든 클릭 한 번으로 적용할 수 있습니다.",+ "FIs3zs": "세그먼트 “{name}”을(를) 저장했습니다",+ "SubaMm": "세그먼트를 저장하지 못했습니다",+ "wFGilL": "세그먼트 “{name}”을(를) 삭제했습니다",+ "gXXeAo": "세그먼트를 삭제하지 못했습니다",+ "HAlOn1": "이름",+ "C1QAaZ": "예: 독일에서 온 모바일 자연 검색",+ "M/zZVx": "필터 추가",+ "VkGJJD": "모든 필터가 일치해야 합니다. 하나의 필터 안의 값들은 그중 하나만 일치하면 됩니다.",+ "kWMpjI": "적용 범위",+ "JtbpIP": "이 사이트",+ "sW/jiZ": "{organization}의 모든 사이트",+ "NwIme6": "조직의 모든 사이트",+ "36pzMD": "경로처럼 사이트마다 다른 값은 모든 사이트에서 같은 의미가 아닐 수 있습니다.",+ "Q8Qw5B": "설명",+ "V4KNjk": "선택 사항",+ "Q+OCEy": "이 그룹이 중요한 이유",+ "/G0KkW": "공개 대시보드와 비공개 링크에 표시",+ "K3r6DQ": "삭제",+ "VREmFv": "세그먼트를 삭제할까요?",+ "SLHC6B": "“{name}”이(가) 이를 사용하는 모든 사용자에게서 제거됩니다. 이미 필터가 펼쳐진 링크는 계속 작동합니다.",+ "47FYwb": "취소",+ "TiR/Hq": "저장 중...",+ "X0ha1a": "변경사항 저장",+ "IAEaaA": "세그먼트 저장",+ "WhVNRN": "현재 필터를 세그먼트로 저장",+ "uncWxg": "아직 세그먼트가 없습니다",+ "wWQxTq": "필터 조합을 저장하면 어떤 보고서에서든 클릭 한 번으로 다시 사용할 수 있습니다.",+ "Dxi6lc": "사이트 소유자가 이 대시보드에 공유한 세그먼트가 없습니다.",+ "RQTMq0": "세그먼트 검색",+ "YbW6Km": "공개 대시보드에 표시됨",+ "ECRv+D": "세그먼트 작업","kJfNiC": "숫자 ID가 있는 상품 페이지","gvs2SV": "'newsletter' 대소문자 무시 일치","XZLB7j": "'test'를 포함하지 않는 경로",@@ -301,7 +344,6 @@"ANmBWb": "결제 CTA 테스트","iBImEo": "가설","JfUnvy": "CTA 문구를 변경하면 가입 전환율이 높아질 것입니다.",- "Q8Qw5B": "설명","Yx6aRS": "이 실험에 대한 선택적 메모","F4tWun": "새 플래그 만들기","rv+WdZ": "자체 할당 분할이 필요한 새 실험에 적합합니다.",@@ -354,11 +396,8 @@"LHF3Za": "기존","W6nwjo": "초안","rbrahO": "닫기",- "47FYwb": "취소","cyR7Kh": "뒤로",- "TiR/Hq": "저장 중...","mRL9Vh": "생성 중...",- "X0ha1a": "변경사항 저장","JXdbo8": "완료","acrOoz": "계속","H+vBOj": "우승자",@@ -391,7 +430,6 @@"U78NhE": "완료","wL7VAE": "작업","wEQDC6": "편집",- "K3r6DQ": "삭제","poMLbD": "실험 필터","qzqYO3": "실험을 찾을 수 없습니다","4YGHzj": "\"{search}\"와 일치하는 실험이 없습니다",@@ -406,7 +444,6 @@"lKv8ex": "기본값","wmFdws": "위로 이동","H/r5m6": "아래로 이동",- "G/yZLu": "제거","7/7DdD": "설정 페이로드","Cn4/rZ": "페이로드","Vwukkb": "JSON 페이로드 추가",@@ -803,7 +840,6 @@"g4dAtI": "이 방문자에게 사용자 ID를 지정합니다. 이 기기에서의 과거 활동이 해당 ID에 연결됩니다.","KE2jY+": "","J6C2uX": "이 사람이 내 시스템에서 갖는 ID입니다. 예: 이메일 또는 계정 ID.",- "HAlOn1": "이름","hDGMjf": "","sy+pv5": "이메일","MQYmtr": "",diff --git a/client/messages/pl.json b/client/messages/pl.jsonindex ee5e000d8..1849ec921 100644--- a/client/messages/pl.json+++ b/client/messages/pl.json@@ -113,6 +113,19 @@"FIKvUB": "Dodaj witrynę","Dg2v6W": "wybierz wartość","oCBPQ4": "Usuń filtr",+ "fB09El": "Ścieżki zaczynające się od /blog/",+ "nnuMWB": "Ścieżki zawierające /blog/ i cokolwiek dalej",+ "GBIt8l": "Ścieżki kończące się na .pdf, .doc lub .docx",+ "o7g8s9": "np. ^/blog/.*",+ "uxcVP6": "Wprowadź wartość...",+ "dhMkG9": "Przykłady regex:",+ "kYpf9a": "Wyszukaj lub dodaj wartość",+ "gjBiyj": "Ładowanie...",+ "jHJmjf": "Brak wyników",+ "2/2yg+": "Dodaj",+ "SElbF+": "Zapisz filtr",+ "oZhbMq": "Filtruj statystyki według",+ "xmcVZ0": "Szukaj","LeFOAk": "Filtr nieaktywny dla tej strony","vONi+O": "Kraj","2eRO6y": "Typ urządzenia",@@ -170,20 +183,50 @@"hJL4XZ": "Mniejsze niż","m0lxVQ": "Większe lub równe","qib0lb": "Mniejsze lub równe",- "fB09El": "Ścieżki zaczynające się od /blog/",- "nnuMWB": "Ścieżki zawierające /blog/ i cokolwiek dalej",- "GBIt8l": "Ścieżki kończące się na .pdf, .doc lub .docx",- "o7g8s9": "np. ^/blog/.*",- "uxcVP6": "Wprowadź wartość...",- "dhMkG9": "Przykłady regex:",- "kYpf9a": "Wyszukaj lub dodaj wartość",- "gjBiyj": "Ładowanie...",- "jHJmjf": "Brak wyników",- "2/2yg+": "Dodaj",- "SElbF+": "Zapisz filtr","9Obw6C": "Filtr",- "oZhbMq": "Filtruj statystyki według",- "xmcVZ0": "Szukaj",+ "VF3DcR": "Segmenty",+ "gy/Kkr": "(zmieniony)",+ "/AMnMU": "Udostępniony wszystkim witrynom w organizacji",+ "wqoG/5": "Definicja",+ "1d0t7e": "Niektóre z tych filtrów zostały zmienione na pulpicie. Sam segment pozostaje bez zmian.",+ "PO3ZXG": "Edytuj segment",+ "djNL6D": "Tylko do odczytu",+ "G/yZLu": "Usuń",+ "j6Cfhx": "Usuń segment",+ "uHnMYi": "Nowy segment",+ "+NhXOR": "Zmiany obowiązują wszędzie tam, gdzie używany jest ten segment.",+ "1rREuf": "Segment to nazwany zestaw filtrów, który możesz jednym kliknięciem zastosować w dowolnym raporcie.",+ "FIs3zs": "Zapisano segment „{name}”",+ "SubaMm": "Nie udało się zapisać segmentu",+ "wFGilL": "Usunięto segment „{name}”",+ "gXXeAo": "Nie udało się usunąć segmentu",+ "HAlOn1": "Imię",+ "C1QAaZ": "np. Ruch organiczny z urządzeń mobilnych z Niemiec",+ "M/zZVx": "Dodaj filtr",+ "VkGJJD": "Wszystkie filtry muszą być spełnione. Wartości w obrębie jednego filtra są alternatywami.",+ "kWMpjI": "Dostępny w",+ "JtbpIP": "Ta witryna",+ "sW/jiZ": "Wszystkie witryny w {organization}",+ "NwIme6": "Wszystkie witryny w organizacji",+ "36pzMD": "Wartości specyficzne dla witryny, takie jak ścieżki, mogą nie znaczyć tego samego w każdej witrynie.",+ "Q8Qw5B": "Opis",+ "V4KNjk": "opcjonalnie",+ "Q+OCEy": "Dlaczego ta grupa jest ważna",+ "/G0KkW": "Pokaż na publicznym pulpicie i w linkach prywatnych",+ "K3r6DQ": "Usuń",+ "VREmFv": "Usunąć segment?",+ "SLHC6B": "„{name}” zostanie usunięty dla wszystkich, którzy go używają. Linki, które już rozwinęły jego filtry, będą nadal działać.",+ "47FYwb": "Anuluj",+ "TiR/Hq": "Zapisywanie...",+ "X0ha1a": "Zapisz zmiany",+ "IAEaaA": "Zapisz segment",+ "WhVNRN": "Zapisz bieżące filtry jako segment",+ "uncWxg": "Brak segmentów",+ "wWQxTq": "Zapisz zestaw filtrów, aby jednym kliknięciem użyć go w dowolnym raporcie.",+ "Dxi6lc": "Właściciel witryny nie udostępnił żadnych segmentów na tym pulpicie.",+ "RQTMq0": "Szukaj segmentów",+ "YbW6Km": "Widoczny na publicznym pulpicie",+ "ECRv+D": "Akcje segmentu","kJfNiC": "Strony produktów z numerycznymi identyfikatorami","gvs2SV": "Dopasowanie bez rozróżniania wielkości liter dla 'newsletter'","XZLB7j": "Ścieżki NIE zawierające 'test'",@@ -301,7 +344,6 @@"ANmBWb": "Test CTA przy kasie","iBImEo": "Hipoteza","JfUnvy": "Zmiana tekstu CTA zwiększy współczynnik konwersji rejestracji.",- "Q8Qw5B": "Opis","Yx6aRS": "Opcjonalne notatki dotyczące tego eksperymentu","F4tWun": "Utwórz nową flagę","rv+WdZ": "Najlepsze dla nowego eksperymentu, który potrzebuje własnego podziału przypisania.",@@ -354,11 +396,8 @@"LHF3Za": "Istniejąca","W6nwjo": "Szkic","rbrahO": "Zamknij",- "47FYwb": "Anuluj","cyR7Kh": "Wstecz",- "TiR/Hq": "Zapisywanie...","mRL9Vh": "Tworzenie...",- "X0ha1a": "Zapisz zmiany","JXdbo8": "Gotowe","acrOoz": "Kontynuuj","H+vBOj": "Zwycięzca",@@ -391,7 +430,6 @@"U78NhE": "Zakończony","wL7VAE": "Akcje","wEQDC6": "Edytuj",- "K3r6DQ": "Usuń","poMLbD": "Filtruj eksperymenty","qzqYO3": "Nie znaleziono eksperymentów","4YGHzj": "Brak eksperymentów pasujących do \"{search}\"",@@ -406,7 +444,6 @@"lKv8ex": "Domyślna","wmFdws": "Przesuń w górę","H/r5m6": "Przesuń w dół",- "G/yZLu": "Usuń","7/7DdD": "Ładunek konfiguracji","Cn4/rZ": "Ładunek","Vwukkb": "Dodaj ładunek JSON",@@ -803,7 +840,6 @@"g4dAtI": "Przypisz identyfikator użytkownika temu odwiedzającemu. Jego dotychczasowa aktywność z tego urządzenia zostanie z nim powiązana.","KE2jY+": "","J6C2uX": "Identyfikator tej osoby w Twoim systemie, np. e-mail lub ID konta.",- "HAlOn1": "Imię","hDGMjf": "","sy+pv5": "E-mail","MQYmtr": "",diff --git a/client/messages/pt.json b/client/messages/pt.jsonindex 52172a7bf..7ad0c6210 100644--- a/client/messages/pt.json+++ b/client/messages/pt.json@@ -113,6 +113,19 @@"FIKvUB": "Adicionar Site","Dg2v6W": "escolher valor","oCBPQ4": "Remover filtro",+ "fB09El": "Caminhos começando com /blog/",+ "nnuMWB": "Caminhos contendo /blog/ seguido de qualquer coisa",+ "GBIt8l": "Caminhos terminando em .pdf, .doc ou .docx",+ "o7g8s9": "ex. ^/blog/.*",+ "uxcVP6": "Digite o valor...",+ "dhMkG9": "Exemplos de Regex:",+ "kYpf9a": "Pesquisar ou adicionar valor",+ "gjBiyj": "Carregando...",+ "jHJmjf": "Sem resultados",+ "2/2yg+": "Adicionar",+ "SElbF+": "Salvar filtro",+ "oZhbMq": "Filtrar estatísticas por",+ "xmcVZ0": "Pesquisar","LeFOAk": "Filtro não ativo para esta página","vONi+O": "País","2eRO6y": "Tipo de Dispositivo",@@ -170,20 +183,50 @@"hJL4XZ": "Menor que","m0lxVQ": "Maior ou igual a","qib0lb": "Menor ou igual a",- "fB09El": "Caminhos começando com /blog/",- "nnuMWB": "Caminhos contendo /blog/ seguido de qualquer coisa",- "GBIt8l": "Caminhos terminando em .pdf, .doc ou .docx",- "o7g8s9": "ex. ^/blog/.*",- "uxcVP6": "Digite o valor...",- "dhMkG9": "Exemplos de Regex:",- "kYpf9a": "Pesquisar ou adicionar valor",- "gjBiyj": "Carregando...",- "jHJmjf": "Sem resultados",- "2/2yg+": "Adicionar",- "SElbF+": "Salvar filtro","9Obw6C": "Filtro",- "oZhbMq": "Filtrar estatísticas por",- "xmcVZ0": "Pesquisar",+ "VF3DcR": "Segmentos",+ "gy/Kkr": "(editado)",+ "/AMnMU": "Compartilhado com todos os sites da organização",+ "wqoG/5": "Definido como",+ "1d0t7e": "Alguns desses filtros foram alterados no painel. O segmento em si não mudou.",+ "PO3ZXG": "Editar segmento",+ "djNL6D": "Somente leitura",+ "G/yZLu": "Remover",+ "j6Cfhx": "Remover segmento",+ "uHnMYi": "Novo segmento",+ "+NhXOR": "As alterações se aplicam em todos os lugares onde este segmento é usado.",+ "1rREuf": "Um segmento é um conjunto nomeado de filtros que você pode aplicar a qualquer relatório com um clique.",+ "FIs3zs": "Segmento “{name}” salvo",+ "SubaMm": "Não foi possível salvar o segmento",+ "wFGilL": "Segmento “{name}” excluído",+ "gXXeAo": "Não foi possível excluir o segmento",+ "HAlOn1": "Nome",+ "C1QAaZ": "ex.: Mobile orgânico da Alemanha",+ "M/zZVx": "Adicionar filtro",+ "VkGJJD": "Todos os filtros precisam corresponder. Os valores dentro de um mesmo filtro são alternativas.",+ "kWMpjI": "Disponível em",+ "JtbpIP": "Este site",+ "sW/jiZ": "Todos os sites de {organization}",+ "NwIme6": "Todos os sites da organização",+ "36pzMD": "Valores específicos do site, como caminhos, podem não significar o mesmo em todos os sites.",+ "Q8Qw5B": "Descrição",+ "V4KNjk": "opcional",+ "Q+OCEy": "Por que este grupo importa",+ "/G0KkW": "Mostrar no painel público e em links privados",+ "K3r6DQ": "Excluir",+ "VREmFv": "Excluir segmento?",+ "SLHC6B": "“{name}” será removido para todos que o usam. Links que já expandiram seus filtros continuam funcionando.",+ "47FYwb": "Cancelar",+ "TiR/Hq": "Salvando...",+ "X0ha1a": "Salvar alterações",+ "IAEaaA": "Salvar segmento",+ "WhVNRN": "Salvar filtros atuais como segmento",+ "uncWxg": "Ainda não há segmentos",+ "wWQxTq": "Salve um conjunto de filtros para reutilizá-lo em qualquer relatório com um clique.",+ "Dxi6lc": "O proprietário do site não compartilhou segmentos neste painel.",+ "RQTMq0": "Buscar segmentos",+ "YbW6Km": "Exibido no painel público",+ "ECRv+D": "Ações do segmento","kJfNiC": "Páginas de produto com IDs numéricos","gvs2SV": "Correspondência sem distinção de maiúsculas para 'newsletter'","XZLB7j": "Caminhos que NÃO contêm 'test'",@@ -301,7 +344,6 @@"ANmBWb": "Teste de CTA do checkout","iBImEo": "Hipótese","JfUnvy": "Alterar o texto do CTA aumentará as conversões de cadastro.",- "Q8Qw5B": "Descrição","Yx6aRS": "Notas opcionais para este experimento","F4tWun": "Criar uma nova flag","rv+WdZ": "Ideal para um novo experimento que precisa de sua própria divisão de atribuição.",@@ -354,11 +396,8 @@"LHF3Za": "Existente","W6nwjo": "Rascunho","rbrahO": "Fechar",- "47FYwb": "Cancelar","cyR7Kh": "Voltar",- "TiR/Hq": "Salvando...","mRL9Vh": "Criando...",- "X0ha1a": "Salvar alterações","JXdbo8": "Concluído","acrOoz": "Continuar","H+vBOj": "Vencedor",@@ -391,7 +430,6 @@"U78NhE": "Concluído","wL7VAE": "Ações","wEQDC6": "Editar",- "K3r6DQ": "Excluir","poMLbD": "Filtrar experimentos","qzqYO3": "Nenhum experimento encontrado","4YGHzj": "Nenhum experimento corresponde a \"{search}\"",@@ -406,7 +444,6 @@"lKv8ex": "Padrão","wmFdws": "Mover para cima","H/r5m6": "Mover para baixo",- "G/yZLu": "Remover","7/7DdD": "Payload de config","Cn4/rZ": "Payload","Vwukkb": "Adicionar payload JSON",@@ -803,7 +840,6 @@"g4dAtI": "Atribua um ID de usuário a este visitante. A atividade anterior deste dispositivo será vinculada a ele.","KE2jY+": "","J6C2uX": "O ID desta pessoa no seu próprio sistema, como um e-mail ou ID de conta.",- "HAlOn1": "Nome","hDGMjf": "","sy+pv5": "E-mail","MQYmtr": "",diff --git a/client/messages/uk.json b/client/messages/uk.jsonindex e2aa039a9..aef565d41 100644--- a/client/messages/uk.json+++ b/client/messages/uk.json@@ -113,6 +113,19 @@"FIKvUB": "Додати сайт","Dg2v6W": "виберіть значення","oCBPQ4": "Видалити фільтр",+ "fB09El": "Шляхи, що починаються з /blog/",+ "nnuMWB": "Шляхи, що містять /blog/, після якого йде будь-що",+ "GBIt8l": "Шляхи, що закінчуються на .pdf, .doc або .docx",+ "o7g8s9": "напр. ^/blog/.*",+ "uxcVP6": "Введіть значення...",+ "dhMkG9": "Приклади регулярних виразів:",+ "kYpf9a": "Пошук або додавання значення",+ "gjBiyj": "Завантаження...",+ "jHJmjf": "Немає результатів",+ "2/2yg+": "Додати",+ "SElbF+": "Зберегти фільтр",+ "oZhbMq": "Фільтрувати статистику за",+ "xmcVZ0": "Пошук","LeFOAk": "Фільтр неактивний для цієї сторінки","vONi+O": "Країна","2eRO6y": "Тип пристрою",@@ -170,20 +183,50 @@"hJL4XZ": "Менше ніж","m0lxVQ": "Більше або дорівнює","qib0lb": "Менше або дорівнює",- "fB09El": "Шляхи, що починаються з /blog/",- "nnuMWB": "Шляхи, що містять /blog/, після якого йде будь-що",- "GBIt8l": "Шляхи, що закінчуються на .pdf, .doc або .docx",- "o7g8s9": "напр. ^/blog/.*",- "uxcVP6": "Введіть значення...",- "dhMkG9": "Приклади регулярних виразів:",- "kYpf9a": "Пошук або додавання значення",- "gjBiyj": "Завантаження...",- "jHJmjf": "Немає результатів",- "2/2yg+": "Додати",- "SElbF+": "Зберегти фільтр","9Obw6C": "Фільтр",- "oZhbMq": "Фільтрувати статистику за",- "xmcVZ0": "Пошук",+ "VF3DcR": "Сегменти",+ "gy/Kkr": "(змінено)",+ "/AMnMU": "Доступно всім сайтам організації",+ "wqoG/5": "Визначення",+ "1d0t7e": "Деякі з цих фільтрів було змінено на панелі. Сам сегмент не змінився.",+ "PO3ZXG": "Редагувати сегмент",+ "djNL6D": "Лише для читання",+ "G/yZLu": "Видалити",+ "j6Cfhx": "Прибрати сегмент",+ "uHnMYi": "Новий сегмент",+ "+NhXOR": "Зміни застосовуються всюди, де використовується цей сегмент.",+ "1rREuf": "Сегмент — це іменований набір фільтрів, який можна одним кліком застосувати до будь-якого звіту.",+ "FIs3zs": "Сегмент «{name}» збережено",+ "SubaMm": "Не вдалося зберегти сегмент",+ "wFGilL": "Сегмент «{name}» видалено",+ "gXXeAo": "Не вдалося видалити сегмент",+ "HAlOn1": "Ім'я",+ "C1QAaZ": "напр. Мобільний органічний трафік із Німеччини",+ "M/zZVx": "Додати фільтр",+ "VkGJJD": "Мають збігатися всі фільтри. Значення в межах одного фільтра — це альтернативи.",+ "kWMpjI": "Доступно для",+ "JtbpIP": "Цей сайт",+ "sW/jiZ": "Усі сайти в {organization}",+ "NwIme6": "Усі сайти організації",+ "36pzMD": "Значення, специфічні для сайту, як-от шляхи, можуть означати різне на різних сайтах.",+ "Q8Qw5B": "Опис",+ "V4KNjk": "необов'язково",+ "Q+OCEy": "Чому ця група важлива",+ "/G0KkW": "Показувати на публічній панелі та в приватних посиланнях",+ "K3r6DQ": "Видалити",+ "VREmFv": "Видалити сегмент?",+ "SLHC6B": "«{name}» буде видалено для всіх, хто його використовує. Посилання, у яких його фільтри вже розгорнуто, працюватимуть далі.",+ "47FYwb": "Скасувати",+ "TiR/Hq": "Збереження...",+ "X0ha1a": "Зберегти зміни",+ "IAEaaA": "Зберегти сегмент",+ "WhVNRN": "Зберегти поточні фільтри як сегмент",+ "uncWxg": "Сегментів поки немає",+ "wWQxTq": "Збережіть набір фільтрів, щоб одним кліком використовувати його в будь-якому звіті.",+ "Dxi6lc": "Власник сайту не поділився жодним сегментом на цій панелі.",+ "RQTMq0": "Пошук сегментів",+ "YbW6Km": "Показано на публічній панелі",+ "ECRv+D": "Дії з сегментом","kJfNiC": "Сторінки товарів із числовими ідентифікаторами","gvs2SV": "Пошук без урахування регістру для 'newsletter'","XZLB7j": "Шляхи, що НЕ містять 'test'",@@ -301,7 +344,6 @@"ANmBWb": "Тест CTA на сторінці оформлення замовлення","iBImEo": "Гіпотеза","JfUnvy": "Зміна тексту CTA збільшить конверсію реєстрацій.",- "Q8Qw5B": "Опис","Yx6aRS": "Необов'язкові нотатки для цього експерименту","F4tWun": "Створити новий прапорець","rv+WdZ": "Найкраще підходить для нового експерименту, якому потрібен власний розподіл призначень.",@@ -354,11 +396,8 @@"LHF3Za": "Наявний","W6nwjo": "Чернетка","rbrahO": "Закрити",- "47FYwb": "Скасувати","cyR7Kh": "Назад",- "TiR/Hq": "Збереження...","mRL9Vh": "Створення...",- "X0ha1a": "Зберегти зміни","JXdbo8": "Готово","acrOoz": "Продовжити","H+vBOj": "Переможець",@@ -391,7 +430,6 @@"U78NhE": "Завершено","wL7VAE": "Дії","wEQDC6": "Редагувати",- "K3r6DQ": "Видалити","poMLbD": "Фільтрувати експерименти","qzqYO3": "Експерименти не знайдено","4YGHzj": "Немає експериментів, що відповідають \"{search}\"",@@ -406,7 +444,6 @@"lKv8ex": "За замовчуванням","wmFdws": "Перемістити вгору","H/r5m6": "Перемістити вниз",- "G/yZLu": "Видалити","7/7DdD": "Payload конфігурації","Cn4/rZ": "Payload","Vwukkb": "Додати JSON payload",@@ -803,7 +840,6 @@"g4dAtI": "Призначте ID користувача цьому відвідувачу. Його минула активність з цього пристрою буде пов'язана з ним.","KE2jY+": "","J6C2uX": "ID цієї особи у вашій власній системі, наприклад email або ID облікового запису.",- "HAlOn1": "Ім'я","hDGMjf": "","sy+pv5": "Email","MQYmtr": "",diff --git a/client/messages/zh.json b/client/messages/zh.jsonindex 178f7f24b..7cfff4814 100644--- a/client/messages/zh.json+++ b/client/messages/zh.json@@ -113,6 +113,19 @@"FIKvUB": "添加站点","Dg2v6W": "选择值","oCBPQ4": "移除筛选器",+ "fB09El": "以 /blog/ 开头的路径",+ "nnuMWB": "包含 /blog/ 后接任意内容的路径",+ "GBIt8l": "以 .pdf、.doc 或 .docx 结尾的路径",+ "o7g8s9": "例如:^/blog/.*",+ "uxcVP6": "输入值...",+ "dhMkG9": "正则表达式示例:",+ "kYpf9a": "搜索或添加值",+ "gjBiyj": "正在加载...",+ "jHJmjf": "无结果",+ "2/2yg+": "添加",+ "SElbF+": "保存筛选器",+ "oZhbMq": "按以下条件筛选统计数据",+ "xmcVZ0": "搜索","LeFOAk": "此页面未激活过滤器","vONi+O": "国家/地区","2eRO6y": "设备类型",@@ -170,20 +183,50 @@"hJL4XZ": "小于","m0lxVQ": "大于等于","qib0lb": "小于等于",- "fB09El": "以 /blog/ 开头的路径",- "nnuMWB": "包含 /blog/ 后接任意内容的路径",- "GBIt8l": "以 .pdf、.doc 或 .docx 结尾的路径",- "o7g8s9": "例如:^/blog/.*",- "uxcVP6": "输入值...",- "dhMkG9": "正则表达式示例:",- "kYpf9a": "搜索或添加值",- "gjBiyj": "正在加载...",- "jHJmjf": "无结果",- "2/2yg+": "添加",- "SElbF+": "保存筛选器","9Obw6C": "过滤",- "oZhbMq": "按以下条件筛选统计数据",- "xmcVZ0": "搜索",+ "VF3DcR": "分群",+ "gy/Kkr": "(已修改)",+ "/AMnMU": "已与组织内的所有站点共享",+ "wqoG/5": "定义为",+ "1d0t7e": "其中一些筛选条件已在仪表盘上被修改。分群本身未改变。",+ "PO3ZXG": "编辑分群",+ "djNL6D": "只读",+ "G/yZLu": "删除",+ "j6Cfhx": "移除分群",+ "uHnMYi": "新建分群",+ "+NhXOR": "更改将应用于使用此分群的所有位置。",+ "1rREuf": "分群是一组命名的筛选条件,可一键应用到任何报表。",+ "FIs3zs": "已保存分群“{name}”",+ "SubaMm": "保存分群失败",+ "wFGilL": "已删除分群“{name}”",+ "gXXeAo": "删除分群失败",+ "HAlOn1": "姓名",+ "C1QAaZ": "例如:来自德国的移动端自然流量",+ "M/zZVx": "添加筛选条件",+ "VkGJJD": "所有筛选条件都必须匹配。同一筛选条件内的多个值为“任一匹配”。",+ "kWMpjI": "适用范围",+ "JtbpIP": "此站点",+ "sW/jiZ": "{organization} 的所有站点",+ "NwIme6": "组织内的所有站点",+ "36pzMD": "路径等站点特定的值在不同站点上的含义可能不同。",+ "Q8Qw5B": "描述",+ "V4KNjk": "可选",+ "Q+OCEy": "为什么这个群体很重要",+ "/G0KkW": "在公开仪表盘和私密链接中显示",+ "K3r6DQ": "删除",+ "VREmFv": "删除分群?",+ "SLHC6B": "“{name}”将对所有使用它的人移除。已展开其筛选条件的链接仍可正常使用。",+ "47FYwb": "取消",+ "TiR/Hq": "正在保存...",+ "X0ha1a": "保存更改",+ "IAEaaA": "保存分群",+ "WhVNRN": "将当前筛选条件保存为分群",+ "uncWxg": "还没有分群",+ "wWQxTq": "保存一组筛选条件,即可在任何报表中一键复用。",+ "Dxi6lc": "站点所有者未在此仪表盘上共享任何分群。",+ "RQTMq0": "搜索分群",+ "YbW6Km": "显示在公开仪表盘上",+ "ECRv+D": "分群操作","kJfNiC": "带有数字 ID 的产品页面","gvs2SV": "不区分大小写匹配 'newsletter'","XZLB7j": "不包含 'test' 的路径",@@ -301,7 +344,6 @@"ANmBWb": "结账 CTA 测试","iBImEo": "假设","JfUnvy": "更改 CTA 文案将提高注册转化率。",- "Q8Qw5B": "描述","Yx6aRS": "此实验的可选备注","F4tWun": "创建新标志","rv+WdZ": "最适合需要独立分配分组的新实验。",@@ -354,11 +396,8 @@"LHF3Za": "现有","W6nwjo": "草稿","rbrahO": "关闭",- "47FYwb": "取消","cyR7Kh": "返回",- "TiR/Hq": "正在保存...","mRL9Vh": "正在创建...",- "X0ha1a": "保存更改","JXdbo8": "完成","acrOoz": "继续","H+vBOj": "获胜者",@@ -391,7 +430,6 @@"U78NhE": "已完成","wL7VAE": "操作","wEQDC6": "编辑",- "K3r6DQ": "删除","poMLbD": "筛选实验","qzqYO3": "未找到实验","4YGHzj": "没有与\"{search}\"匹配的实验",@@ -406,7 +444,6 @@"lKv8ex": "默认","wmFdws": "上移","H/r5m6": "下移",- "G/yZLu": "删除","7/7DdD": "配置载荷","Cn4/rZ": "载荷","Vwukkb": "添加 JSON 载荷",@@ -803,7 +840,6 @@"g4dAtI": "为此访客分配用户 ID。该设备上的历史活动将与其关联。","KE2jY+": "","J6C2uX": "此人在您自己系统中的 ID,例如电子邮件或账户 ID。",- "HAlOn1": "姓名","hDGMjf": "","sy+pv5": "电子邮件","MQYmtr": "",diff --git a/client/src/api/analytics/endpoints/segments.ts b/client/src/api/analytics/endpoints/segments.tsnew file mode 100644index 000000000..bfc0e42e7--- /dev/null+++ b/client/src/api/analytics/endpoints/segments.ts@@ -0,0 +1,30 @@+import type { Filter, Segment, SegmentScope } from "@rybbit/shared";+import { authedFetch } from "../../utils";++export interface SegmentWriteBody {+ name: string;+ description?: string | null;+ filters: Filter[];+ isPublic?: boolean;+ scope?: SegmentScope;+}++export function fetchSegments(site: string | number) {+ return authedFetch<Segment[]>(`/sites/${site}/segments`);+}++export function fetchSegment(site: string | number, segmentId: number) {+ return authedFetch<Segment>(`/sites/${site}/segments/${segmentId}`);+}++export function createSegment(site: string | number, body: SegmentWriteBody) {+ return authedFetch<Segment>(`/sites/${site}/segments`, undefined, { method: "POST", data: body });+}++export function updateSegment(site: string | number, segmentId: number, body: Partial<SegmentWriteBody>) {+ return authedFetch<Segment>(`/sites/${site}/segments/${segmentId}`, undefined, { method: "PUT", data: body });+}++export function deleteSegment(site: string | number, segmentId: number) {+ return authedFetch<{ success: true }>(`/sites/${site}/segments/${segmentId}`, undefined, { method: "DELETE" });+}diff --git a/client/src/api/analytics/hooks/useSegments.ts b/client/src/api/analytics/hooks/useSegments.tsnew file mode 100644index 000000000..b7ff8c42b--- /dev/null+++ b/client/src/api/analytics/hooks/useSegments.ts@@ -0,0 +1,53 @@+import type { Segment } from "@rybbit/shared";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { createSegment, deleteSegment, fetchSegments, SegmentWriteBody, updateSegment } from "../endpoints/segments";++export const SEGMENTS_QUERY_KEY = "get-segments";++export function useGetSegments(siteId?: string | number, options?: { enabled?: boolean }) {+ return useQuery<Segment[]>({+ queryKey: [SEGMENTS_QUERY_KEY, siteId],+ queryFn: () => fetchSegments(siteId!),+ enabled: !!siteId && options?.enabled !== false,+ staleTime: 60_000,+ });+}++export function useCreateSegment() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: ({ siteId, body }: { siteId: string | number; body: SegmentWriteBody }) => createSegment(siteId, body),+ onSuccess: (_, variables) => {+ queryClient.invalidateQueries({ queryKey: [SEGMENTS_QUERY_KEY, variables.siteId] });+ },+ });+}++export function useUpdateSegment() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: ({+ siteId,+ segmentId,+ body,+ }: {+ siteId: string | number;+ segmentId: number;+ body: Partial<SegmentWriteBody>;+ }) => updateSegment(siteId, segmentId, body),+ onSuccess: (_, variables) => {+ queryClient.invalidateQueries({ queryKey: [SEGMENTS_QUERY_KEY, variables.siteId] });+ },+ });+}++export function useDeleteSegment() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: ({ siteId, segmentId }: { siteId: string | number; segmentId: number }) =>+ deleteSegment(siteId, segmentId),+ onSuccess: (_, variables) => {+ queryClient.invalidateQueries({ queryKey: [SEGMENTS_QUERY_KEY, variables.siteId] });+ },+ });+}diff --git a/client/src/app/[site]/components/SubHeader/Filters/FilterChip.tsx b/client/src/app/[site]/components/SubHeader/Filters/FilterChip.tsxnew file mode 100644index 000000000..77c8855c9--- /dev/null+++ b/client/src/app/[site]/components/SubHeader/Filters/FilterChip.tsx@@ -0,0 +1,104 @@+"use client";++import { Filter, FilterParameter } from "@rybbit/shared";+import { X } from "lucide-react";+import { useExtracted } from "next-intl";+import { Button } from "../../../../../components/ui/button";+import { ButtonGroup } from "../../../../../components/ui/button-group";+import { useGetRegionName } from "../../../../../lib/geo";+import { cn } from "../../../../../lib/utils";+import { isNumericParameter } from "./const";+import {+ formatDisplayValue,+ getParameterIcon,+ operatorNeedsValue,+ useOperatorLabel,+ useParameterLabel,+} from "./labels";+import { OperatorPopover } from "./OperatorPopover";+import { ParameterPopover } from "./ParameterPopover";+import { ValuePopover } from "./ValuePopover";++/**+ * One editable filter pill: dimension, operator, value, remove. Used by the+ * dashboard's chip row and by the segment editor, so both edit a filter the+ * same way.+ */+export function FilterChip({+ filter,+ onUpdate,+ onRemove,+ availableFilters,+ disabled,+}: {+ filter: Filter;+ onUpdate: (filter: Filter) => void;+ onRemove: () => void;+ availableFilters?: FilterParameter[];+ disabled?: boolean;+}) {+ const t = useExtracted();+ const { getRegionName } = useGetRegionName();+ const getParameterLabel = useParameterLabel();+ const getOperatorLabel = useOperatorLabel();++ const isNumeric = isNumericParameter(filter.parameter);+ const displayValue = formatDisplayValue(filter, getRegionName);+ const hasValue = filter.value.length > 0;++ return (+ <ButtonGroup>+ <ParameterPopover filter={filter} onUpdate={onUpdate} availableFilters={availableFilters}>+ <Button+ variant="secondary"+ size="sm"+ disabled={disabled}+ className={cn(+ "font-normal py-1.5 px-2 gap-1.5",+ disabled ? "text-neutral-400 dark:text-neutral-500" : "text-neutral-700 dark:text-neutral-100"+ )}+ >+ {getParameterIcon(filter.parameter)}+ {getParameterLabel(filter.parameter)}+ </Button>+ </ParameterPopover>+ <OperatorPopover filter={filter} onUpdate={onUpdate}>+ <Button+ variant="secondary"+ size="sm"+ disabled={disabled}+ className="font-normal p-1.5 text-neutral-500 dark:text-neutral-400"+ >+ {getOperatorLabel(filter.type, isNumeric)}+ </Button>+ </OperatorPopover>+ {operatorNeedsValue(filter.type) && (+ <ValuePopover filter={filter} onUpdate={onUpdate}>+ <Button+ variant="secondary"+ size="sm"+ disabled={disabled}+ className={cn(+ "max-w-[260px] truncate py-1.5 px-2",+ hasValue+ ? "text-neutral-900 dark:text-neutral-100 font-medium"+ : "text-neutral-500 dark:text-neutral-400 italic font-normal",+ disabled && "text-neutral-400 dark:text-neutral-500"+ )}+ >+ <span className="truncate">{hasValue ? displayValue : t("pick value")}</span>+ </Button>+ </ValuePopover>+ )}+ <Button+ variant="secondary"+ size="sm"+ className="text-neutral-500 dark:text-neutral-400 px-1.5"+ onClick={onRemove}+ aria-label={t("Remove filter")}+ >+ <X size={14} strokeWidth={2.5} />+ </Button>+ </ButtonGroup>+ );+}diff --git a/client/src/app/[site]/components/SubHeader/Filters/FilterPicker.tsx b/client/src/app/[site]/components/SubHeader/Filters/FilterPicker.tsxnew file mode 100644index 000000000..114c76a09--- /dev/null+++ b/client/src/app/[site]/components/SubHeader/Filters/FilterPicker.tsx@@ -0,0 +1,397 @@+"use client";++import { Filter, FilterParameter, FilterType } from "@rybbit/shared";+import { Check, ChevronLeft, ChevronRight, ChevronsUpDown, HelpCircle, Plus } from "lucide-react";+import { useExtracted } from "next-intl";+import { useMemo, useState } from "react";+import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";+import { Button } from "../../../../../components/ui/button";+import { Checkbox } from "../../../../../components/ui/checkbox";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "../../../../../components/ui/command";+import { Input } from "../../../../../components/ui/input";+import { Popover, PopoverContent, PopoverTrigger } from "../../../../../components/ui/popover";+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";+import { useGetRegionName } from "../../../../../lib/geo";+import { cn, getCountryName, getLanguageName } from "../../../../../lib/utils";+import {+ FilterOptions,+ isNumericParameter,+ NumericOperatorOptions,+ StringOperatorOptions,+} from "./const";+import { useOperatorLabel, useOperatorMenuLabel, useParameterLabel, validateRegex } from "./labels";++function RegexExamples() {+ const t = useExtracted();+ return (+ <ul className="text-xs space-y-1">+ <li>+ <code className="bg-neutral-100 dark:bg-neutral-800 px-1 rounded">{"^/blog/"}</code>+ <span className="text-neutral-500 ml-1">— {t("Paths starting with /blog/")}</span>+ </li>+ <li>+ <code className="bg-neutral-100 dark:bg-neutral-800 px-1 rounded">{"/blog/.*"}</code>+ <span className="text-neutral-500 ml-1">+ — {t("Paths containing /blog/ followed by anything")}+ </span>+ </li>+ <li>+ <code className="bg-neutral-100 dark:bg-neutral-800 px-1 rounded">{"\\.(pdf|doc|docx)$"}</code>+ <span className="text-neutral-500 ml-1">— {t("Paths ending in .pdf, .doc, or .docx")}</span>+ </li>+ </ul>+ );+}++function ValueStep({+ parameter,+ onCommit,+ onBack,+ onClose,+ pendingRef,+}: {+ parameter: FilterParameter;+ onCommit: (filter: Filter) => void;+ onBack: () => void;+ onClose: () => void;+ pendingRef: React.MutableRefObject<() => Filter | null>;+}) {+ const t = useExtracted();+ const { getRegionName } = useGetRegionName();+ const [type, setType] = useState<FilterType>("equals");+ const [selected, setSelected] = useState<(string | number)[]>([]);+ const [textInput, setTextInput] = useState("");+ const [search, setSearch] = useState("");+ const [operatorOpen, setOperatorOpen] = useState(false);++ const getParameterLabel = useParameterLabel();+ const getOperatorLabel = useOperatorLabel();+ const getOperatorMenuLabel = useOperatorMenuLabel();++ const isNumeric = isNumericParameter(parameter);+ const isRegex = type === "regex" || type === "not_regex";+ const isNumericComparison =+ type === "greater_than" ||+ type === "less_than" ||+ type === "greater_than_or_equal" ||+ type === "less_than_or_equal";+ const needsValue = type !== "is_null" && type !== "is_not_null";+ const needsTextInput = isNumeric || isRegex || isNumericComparison;+ const operatorOptions = isNumeric ? NumericOperatorOptions : StringOperatorOptions;++ const { data, isFetching } = useMetric({+ parameter,+ limit: 1000,+ useFilters: false,+ });++ const getValueLabel = (val: string | number) => {+ if (parameter === "country") return getCountryName(val as string);+ if (parameter === "region") return getRegionName(val as string) ?? String(val);+ if (parameter === "language") return getLanguageName(val as string);+ return String(val);+ };++ const suggestions = useMemo(() => {+ const fromData =+ data?.data?.flatMap(item => {+ const val = item.value;+ return val ? [{ value: String(val), label: String(getValueLabel(val)) }] : [];+ }) ?? [];+ const present = new Set(fromData.map(o => o.value));+ const selectedExtras = selected+ .map(v => String(v))+ .filter(v => !present.has(v))+ .map(v => ({ value: v, label: String(getValueLabel(v)) }));+ return [...selectedExtras, ...fromData];+ }, [data, parameter, selected, getRegionName]);++ const trimmedSearch = search.trim();+ const matchesExisting = suggestions.some(+ o => o.label.toLowerCase() === trimmedSearch.toLowerCase()+ );+ const canCreate = trimmedSearch.length > 0 && !matchesExisting;++ const toggleValue = (val: string) => {+ const exists = selected.some(v => String(v) === val);+ setSelected(exists ? selected.filter(v => String(v) !== val) : [...selected, val]);+ };++ const addCustomValue = () => {+ if (!canCreate) return;+ const exists = selected.some(v => String(v) === trimmedSearch);+ if (!exists) setSelected([...selected, trimmedSearch]);+ setSearch("");+ };++ const regexError = useMemo(() => (isRegex ? validateRegex(textInput) : null), [isRegex, textInput]);++ const buildFilter = (): Filter | null => {+ if (type === "is_null" || type === "is_not_null") {+ return { parameter, type, value: [] };+ }+ if (needsTextInput) {+ if (textInput.trim() === "") return null;+ if (isNumeric || isNumericComparison) {+ const num = Number(textInput);+ if (!Number.isFinite(num)) return null;+ return { parameter, type, value: [num] };+ }+ if (isRegex && validateRegex(textInput)) return null;+ return { parameter, type, value: [textInput.trim()] };+ }+ if (selected.length === 0) return null;+ return { parameter, type, value: selected };+ };++ const canSave = buildFilter() !== null;+ pendingRef.current = buildFilter;++ const commitAndClose = () => {+ const f = buildFilter();+ if (!f) return;+ onCommit(f);+ onClose();+ };++ const selectOperator = (next: FilterType) => {+ setOperatorOpen(false);+ if (next === "is_null" || next === "is_not_null") {+ onCommit({ parameter, type: next, value: [] });+ onClose();+ return;+ }+ setType(next);+ setSelected([]);+ setTextInput("");+ };++ return (+ <div className="flex flex-col">+ <div className="flex items-center justify-between px-2 py-2 border-b border-neutral-200 dark:border-neutral-800">+ <button+ type="button"+ onClick={onBack}+ className="inline-flex items-center gap-1 text-sm font-medium text-neutral-700 dark:text-neutral-200 hover:text-neutral-900 dark:hover:text-neutral-50 px-1"+ >+ <ChevronLeft className="h-4 w-4" />+ {getParameterLabel(parameter)}+ </button>+ <Popover open={operatorOpen} onOpenChange={setOperatorOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="inline-flex items-center gap-1 text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200 px-2 py-1 rounded"+ >+ {getOperatorLabel(type, isNumeric)}+ <ChevronsUpDown className="h-3 w-3" />+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-56 p-0" align="end">+ <div className="px-3 pt-3 pb-1 text-sm font-medium">{t("Operator")}</div>+ <div className="flex flex-col py-1">+ {operatorOptions.map(option => {+ const isSelected = option.value === type;+ return (+ <button+ key={option.value}+ type="button"+ onClick={() => selectOperator(option.value as FilterType)}+ className={cn(+ "text-left px-3 py-2 text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800",+ isSelected && "bg-neutral-100 dark:bg-neutral-800"+ )}+ >+ {getOperatorMenuLabel(option.value as FilterType, isNumeric)}+ </button>+ );+ })}+ </div>+ </PopoverContent>+ </Popover>+ </div>+ {needsValue && (+ needsTextInput ? (+ <div className="p-3 flex flex-col gap-2">+ <div className="flex items-center gap-1">+ <Input+ autoFocus+ value={textInput}+ onChange={e => setTextInput(e.target.value)}+ onKeyDown={e => {+ if (e.key === "Enter") {+ e.preventDefault();+ commitAndClose();+ }+ }}+ placeholder={isRegex ? t("e.g. ^/blog/.*") : t("Enter value...")}+ className={cn("h-9", regexError && "border-red-500 focus-visible:ring-red-500")}+ type={isNumeric || isNumericComparison ? "number" : "text"}+ />+ {isRegex && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ className="h-9 w-9 shrink-0 inline-flex items-center justify-center rounded-md text-neutral-500 hover:text-neutral-300"+ >+ <HelpCircle className="h-4 w-4" />+ </button>+ </TooltipTrigger>+ <TooltipContent side="bottom" className="max-w-xs">+ <div className="space-y-2">+ <p className="font-medium">{t("Regex Examples:")}</p>+ <RegexExamples />+ </div>+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ {regexError && <div className="text-xs text-red-500 truncate">{regexError}</div>}+ </div>+ ) : (+ <Command>+ <CommandInput+ placeholder={t("Search or add value")}+ value={search}+ onValueChange={setSearch}+ />+ <CommandList>+ <CommandEmpty>{isFetching ? t("Loading...") : t("No results")}</CommandEmpty>+ {canCreate && (+ <CommandGroup>+ <CommandItem+ value={`__create__${trimmedSearch}`}+ onSelect={addCustomValue}+ className="cursor-pointer"+ >+ <Plus className="mr-2 h-4 w-4" />+ <span className="truncate">+ {t("Add")} "{trimmedSearch}"+ </span>+ </CommandItem>+ </CommandGroup>+ )}+ <CommandGroup>+ {suggestions.map(option => {+ const isSelected = selected.some(v => String(v) === option.value);+ return (+ <CommandItem+ key={option.value}+ value={option.label}+ onSelect={() => toggleValue(option.value)}+ className="cursor-pointer"+ >+ <Checkbox checked={isSelected} className="mr-2" />+ <span className="truncate">{option.label}</span>+ </CommandItem>+ );+ })}+ </CommandGroup>+ </CommandList>+ </Command>+ )+ )}+ {needsValue && (+ <div className="border-t border-neutral-200 dark:border-neutral-800 p-2">+ <Button+ type="button"+ size="sm"+ variant="success"+ className="w-full"+ disabled={!canSave}+ onClick={commitAndClose}+ >+ <Check className="h-4 w-4" />+ {t("Save filter")}+ </Button>+ </div>+ )}+ </div>+ );+}++/**+ * The two-step filter builder (pick a dimension, then an operator and value)+ * that the Filter popover has always shown. It is a controlled fragment so+ * the same picker can add filters to the dashboard and to a segment being+ * edited in a dialog. `pendingRef` lets the host commit a half-built filter+ * when its popover is dismissed, matching the previous behaviour.+ */+export function FilterPicker({+ availableFilters,+ onCommit,+ onClose,+ pendingRef,+ parameter,+ setParameter,+}: {+ availableFilters?: FilterParameter[];+ onCommit: (filter: Filter) => void;+ onClose: () => void;+ pendingRef: React.MutableRefObject<() => Filter | null>;+ parameter: FilterParameter | null;+ setParameter: (parameter: FilterParameter | null) => void;+}) {+ const t = useExtracted();+ const getParameterLabel = useParameterLabel();++ const parameterOptions = availableFilters+ ? FilterOptions.filter(o => availableFilters.includes(o.value))+ : FilterOptions;++ const goBackToParameter = () => {+ pendingRef.current = () => null;+ setParameter(null);+ };++ if (parameter) {+ return (+ <ValueStep+ key={parameter}+ parameter={parameter}+ pendingRef={pendingRef}+ onCommit={onCommit}+ onBack={goBackToParameter}+ onClose={() => {+ pendingRef.current = () => null;+ setParameter(null);+ onClose();+ }}+ />+ );+ }++ return (+ <Command>+ <div className="px-3 pt-3 pb-1 text-xs text-neutral-500 dark:text-neutral-400">{t("Filter stats by")}</div>+ <CommandInput placeholder={t("Search")} />+ <CommandList>+ <CommandEmpty>{t("No results")}</CommandEmpty>+ <CommandGroup>+ {parameterOptions.map(option => (+ <CommandItem+ key={option.value}+ value={getParameterLabel(option.value)}+ onSelect={() => setParameter(option.value)}+ className="cursor-pointer"+ >+ <div className="flex items-center gap-2 flex-1 min-w-0">+ {option.icon}+ <span className="truncate">{getParameterLabel(option.value)}</span>+ </div>+ <ChevronRight className="h-4 w-4 text-neutral-400" />+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ );+}diff --git a/client/src/app/[site]/components/SubHeader/Filters/Filters.tsx b/client/src/app/[site]/components/SubHeader/Filters/Filters.tsxindex e85fb3cce..3cffd8892 100644--- a/client/src/app/[site]/components/SubHeader/Filters/Filters.tsx+++ b/client/src/app/[site]/components/SubHeader/Filters/Filters.tsx@@ -1,104 +1,47 @@"use client";-import { FilterParameter } from "@rybbit/shared";-import { X } from "lucide-react";+import { FilterParameter, Segment } from "@rybbit/shared";import { useExtracted } from "next-intl";-import { Button } from "../../../../../components/ui/button";-import { ButtonGroup } from "../../../../../components/ui/button-group";+import { useState } from "react";+import { useGetSegments } from "../../../../../api/analytics/hooks/useSegments";import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";-import { useGetRegionName } from "../../../../../lib/geo";import { removeFilter, updateFilter, useStore } from "../../../../../lib/store";-import { cn } from "../../../../../lib/utils";-import { isNumericParameter } from "./const";-import {- formatDisplayValue,- getParameterIcon,- useParameterLabel,- operatorNeedsValue,- useOperatorLabel,-} from "./labels";-import { OperatorPopover } from "./OperatorPopover";-import { ParameterPopover } from "./ParameterPopover";-import { ValuePopover } from "./ValuePopover";+import { FilterChip } from "./FilterChip";+import { SegmentChip } from "./SegmentChip";+import { SegmentDialog } from "./SegmentDialog";+import { filterListKeys, partitionFilters } from "./segmentUtils";export function Filters({ availableFilters }: { availableFilters?: FilterParameter[] }) {const t = useExtracted();- const { filters } = useStore();- const { getRegionName } = useGetRegionName();- const getParameterLabel = useParameterLabel();- const getOperatorLabel = useOperatorLabel();+ const { filters, segmentId, site } = useStore();+ const { data: segments } = useGetSegments(site, { enabled: segmentId !== null });+ const [editing, setEditing] = useState<Segment | null>(null);++ const segment = segmentId === null ? undefined : segments?.find(s => s.segmentId === segmentId);+ const { adHoc, intact } = partitionFilters(filters, segment);+ const keys = filterListKeys(adHoc);return (<div className="flex gap-2 flex-wrap">- {filters.map((filter, i) => {+ {segment && <SegmentChip segment={segment} intact={intact} onEdit={setEditing} />}+ {adHoc.map((filter, position) => {const disabled = availableFilters && !availableFilters.includes(filter.parameter);- const isNumeric = isNumericParameter(filter.parameter);- const displayValue = formatDisplayValue(filter, getRegionName);- const hasValue = filter.value.length > 0;-- const onUpdate = (next: typeof filter) => updateFilter(next, i);+ const index = filters.indexOf(filter);+ const key = keys[position];const pill = (- <ButtonGroup>- <ParameterPopover filter={filter} onUpdate={onUpdate} availableFilters={availableFilters}>- <Button- variant="secondary"- size="sm"- disabled={disabled}- className={cn(- "font-normal py-1.5 px-2 gap-1.5",- disabled- ? "text-neutral-400 dark:text-neutral-500"- : "text-neutral-700 dark:text-neutral-100"- )}- >- {getParameterIcon(filter.parameter)}- {getParameterLabel(filter.parameter)}- </Button>- </ParameterPopover>- <OperatorPopover filter={filter} onUpdate={onUpdate}>- <Button- variant="secondary"- size="sm"- disabled={disabled}- className={cn("font-normal p-1.5 text-neutral-500 dark:text-neutral-400")}- >- {getOperatorLabel(filter.type, isNumeric)}- </Button>- </OperatorPopover>- {operatorNeedsValue(filter.type) && (- <ValuePopover filter={filter} onUpdate={onUpdate}>- <Button- variant="secondary"- size="sm"- disabled={disabled}- className={cn(- "max-w-[260px] truncate py-1.5 px-2",- hasValue- ? "text-neutral-900 dark:text-neutral-100 font-medium"- : "text-neutral-500 dark:text-neutral-400 italic font-normal",- disabled && "text-neutral-400 dark:text-neutral-500"- )}- >- <span className="truncate">{hasValue ? displayValue : t("pick value")}</span>- </Button>- </ValuePopover>- )}- <Button- variant="secondary"- size="sm"- className="text-neutral-500 dark:text-neutral-400 px-1.5"- onClick={() => removeFilter(filter)}- aria-label={t("Remove filter")}- >- <X size={14} strokeWidth={2.5} />- </Button>- </ButtonGroup>+ <FilterChip+ filter={filter}+ availableFilters={availableFilters}+ disabled={disabled}+ onUpdate={next => updateFilter(next, index)}+ onRemove={() => removeFilter(filter)}+ />);if (disabled) {return (- <Tooltip key={i}>+ <Tooltip key={key}><TooltipTrigger asChild>{pill}</TooltipTrigger><TooltipContent><p>{t("Filter not active for this page")}</p>@@ -106,8 +49,15 @@ export function Filters({ availableFilters }: { availableFilters?: FilterParamet</Tooltip>);}- return <div key={i}>{pill}</div>;+ return <div key={key}>{pill}</div>;})}+ <SegmentDialog+ open={editing !== null}+ onOpenChange={open => !open && setEditing(null)}+ siteId={site}+ segment={editing ?? undefined}+ availableFilters={availableFilters}+ /></div>);}diff --git a/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx b/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsxindex 68c79eb20..bb06584d0 100644--- a/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx+++ b/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx@@ -1,404 +1,137 @@"use client";-import { Filter, FilterParameter, FilterType } from "@rybbit/shared";-import { Check, ChevronLeft, ChevronRight, ChevronsUpDown, HelpCircle, ListFilterPlus, Plus } from "lucide-react";+import { Filter, FilterParameter, Segment } from "@rybbit/shared";+import { ListFilterPlus } from "lucide-react";import { useExtracted } from "next-intl";-import { useMemo, useRef, useState } from "react";-import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";+import { useRef, useState } from "react";+import { useUserOrganizations } from "../../../../../api/admin/hooks/useOrganizations";+import { useGetSite } from "../../../../../api/admin/hooks/useSites";import { Button } from "../../../../../components/ui/button";-import { Checkbox } from "../../../../../components/ui/checkbox";-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,-} from "../../../../../components/ui/command";-import { Input } from "../../../../../components/ui/input";import { Popover, PopoverContent, PopoverTrigger } from "../../../../../components/ui/popover";-import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";-import { useGetRegionName } from "../../../../../lib/geo";-import { addFilter } from "../../../../../lib/store";-import { cn, getCountryName, getLanguageName } from "../../../../../lib/utils";-import {- FilterOptions,- isNumericParameter,- NumericOperatorOptions,- StringOperatorOptions,-} from "./const";-import { useOperatorLabel, useOperatorMenuLabel, useParameterLabel, validateRegex } from "./labels";--function RegexExamples() {- const t = useExtracted();- return (- <ul className="text-xs space-y-1">- <li>- <code className="bg-neutral-100 dark:bg-neutral-800 px-1 rounded">{"^/blog/"}</code>- <span className="text-neutral-500 ml-1">— {t("Paths starting with /blog/")}</span>- </li>- <li>- <code className="bg-neutral-100 dark:bg-neutral-800 px-1 rounded">{"/blog/.*"}</code>- <span className="text-neutral-500 ml-1">- — {t("Paths containing /blog/ followed by anything")}- </span>- </li>- <li>- <code className="bg-neutral-100 dark:bg-neutral-800 px-1 rounded">{"\\.(pdf|doc|docx)$"}</code>- <span className="text-neutral-500 ml-1">— {t("Paths ending in .pdf, .doc, or .docx")}</span>- </li>- </ul>- );-}--function ValueStep({- parameter,- onCommit,- onBack,- onClose,- pendingRef,-}: {- parameter: FilterParameter;- onCommit: (filter: Filter) => void;- onBack: () => void;- onClose: () => void;- pendingRef: React.MutableRefObject<() => Filter | null>;-}) {- const t = useExtracted();- const { getRegionName } = useGetRegionName();- const [type, setType] = useState<FilterType>("equals");- const [selected, setSelected] = useState<(string | number)[]>([]);- const [textInput, setTextInput] = useState("");- const [search, setSearch] = useState("");- const [operatorOpen, setOperatorOpen] = useState(false);-- const getParameterLabel = useParameterLabel();- const getOperatorLabel = useOperatorLabel();- const getOperatorMenuLabel = useOperatorMenuLabel();-- const isNumeric = isNumericParameter(parameter);- const isRegex = type === "regex" || type === "not_regex";- const isNumericComparison =- type === "greater_than" ||- type === "less_than" ||- type === "greater_than_or_equal" ||- type === "less_than_or_equal";- const needsValue = type !== "is_null" && type !== "is_not_null";- const needsTextInput = isNumeric || isRegex || isNumericComparison;- const operatorOptions = isNumeric ? NumericOperatorOptions : StringOperatorOptions;-- const { data, isFetching } = useMetric({- parameter,- limit: 1000,- useFilters: false,- });-- const getValueLabel = (val: string | number) => {- if (parameter === "country") return getCountryName(val as string);- if (parameter === "region") return getRegionName(val as string) ?? String(val);- if (parameter === "language") return getLanguageName(val as string);- return String(val);- };-- const suggestions = useMemo(() => {- const fromData =- data?.data?.flatMap(item => {- const val = item.value;- return val ? [{ value: String(val), label: String(getValueLabel(val)) }] : [];- }) ?? [];- const present = new Set(fromData.map(o => o.value));- const selectedExtras = selected- .map(v => String(v))- .filter(v => !present.has(v))- .map(v => ({ value: v, label: String(getValueLabel(v)) }));- return [...selectedExtras, ...fromData];- }, [data, parameter, selected, getRegionName]);-- const trimmedSearch = search.trim();- const matchesExisting = suggestions.some(- o => o.label.toLowerCase() === trimmedSearch.toLowerCase()- );- const canCreate = trimmedSearch.length > 0 && !matchesExisting;-- const toggleValue = (val: string) => {- const exists = selected.some(v => String(v) === val);- setSelected(exists ? selected.filter(v => String(v) !== val) : [...selected, val]);- };-- const addCustomValue = () => {- if (!canCreate) return;- const exists = selected.some(v => String(v) === trimmedSearch);- if (!exists) setSelected([...selected, trimmedSearch]);- setSearch("");- };-- const regexError = useMemo(() => (isRegex ? validateRegex(textInput) : null), [isRegex, textInput]);-- const buildFilter = (): Filter | null => {- if (type === "is_null" || type === "is_not_null") {- return { parameter, type, value: [] };- }- if (needsTextInput) {- if (textInput.trim() === "") return null;- if (isNumeric || isNumericComparison) {- const num = Number(textInput);- if (!Number.isFinite(num)) return null;- return { parameter, type, value: [num] };- }- if (isRegex && validateRegex(textInput)) return null;- return { parameter, type, value: [textInput.trim()] };- }- if (selected.length === 0) return null;- return { parameter, type, value: selected };- };-- const canSave = buildFilter() !== null;- pendingRef.current = buildFilter;-- const commitAndClose = () => {- const f = buildFilter();- if (!f) return;- onCommit(f);- onClose();- };-- const selectOperator = (next: FilterType) => {- setOperatorOpen(false);- if (next === "is_null" || next === "is_not_null") {- onCommit({ parameter, type: next, value: [] });- onClose();- return;- }- setType(next);- setSelected([]);- setTextInput("");- };-- return (- <div className="flex flex-col">- <div className="flex items-center justify-between px-2 py-2 border-b border-neutral-200 dark:border-neutral-800">- <button- type="button"- onClick={onBack}- className="inline-flex items-center gap-1 text-sm font-medium text-neutral-700 dark:text-neutral-200 hover:text-neutral-900 dark:hover:text-neutral-50 px-1"- >- <ChevronLeft className="h-4 w-4" />- {getParameterLabel(parameter)}- </button>- <Popover open={operatorOpen} onOpenChange={setOperatorOpen}>- <PopoverTrigger asChild>- <button- type="button"- className="inline-flex items-center gap-1 text-sm text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200 px-2 py-1 rounded"- >- {getOperatorLabel(type, isNumeric)}- <ChevronsUpDown className="h-3 w-3" />- </button>- </PopoverTrigger>- <PopoverContent className="w-56 p-0" align="end">- <div className="px-3 pt-3 pb-1 text-sm font-medium">{t("Operator")}</div>- <div className="flex flex-col py-1">- {operatorOptions.map(option => {- const isSelected = option.value === type;- return (- <button- key={option.value}- type="button"- onClick={() => selectOperator(option.value as FilterType)}- className={cn(- "text-left px-3 py-2 text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800",- isSelected && "bg-neutral-100 dark:bg-neutral-800"- )}- >- {getOperatorMenuLabel(option.value as FilterType, isNumeric)}- </button>- );- })}- </div>- </PopoverContent>- </Popover>- </div>- {needsValue && (- needsTextInput ? (- <div className="p-3 flex flex-col gap-2">- <div className="flex items-center gap-1">- <Input- autoFocus- value={textInput}- onChange={e => setTextInput(e.target.value)}- onKeyDown={e => {- if (e.key === "Enter") {- e.preventDefault();- commitAndClose();- }- }}- placeholder={isRegex ? t("e.g. ^/blog/.*") : t("Enter value...")}- className={cn("h-9", regexError && "border-red-500 focus-visible:ring-red-500")}- type={isNumeric || isNumericComparison ? "number" : "text"}- />- {isRegex && (- <Tooltip>- <TooltipTrigger asChild>- <button- type="button"- className="h-9 w-9 shrink-0 inline-flex items-center justify-center rounded-md text-neutral-500 hover:text-neutral-300"- >- <HelpCircle className="h-4 w-4" />- </button>- </TooltipTrigger>- <TooltipContent side="bottom" className="max-w-xs">- <div className="space-y-2">- <p className="font-medium">{t("Regex Examples:")}</p>- <RegexExamples />- </div>- </TooltipContent>- </Tooltip>- )}- </div>- {regexError && <div className="text-xs text-red-500 truncate">{regexError}</div>}- </div>- ) : (- <Command>- <CommandInput- placeholder={t("Search or add value")}- value={search}- onValueChange={setSearch}- />- <CommandList>- <CommandEmpty>{isFetching ? t("Loading...") : t("No results")}</CommandEmpty>- {canCreate && (- <CommandGroup>- <CommandItem- value={`__create__${trimmedSearch}`}- onSelect={addCustomValue}- className="cursor-pointer"- >- <Plus className="mr-2 h-4 w-4" />- <span className="truncate">- {t("Add")} "{trimmedSearch}"- </span>- </CommandItem>- </CommandGroup>- )}- <CommandGroup>- {suggestions.map(option => {- const isSelected = selected.some(v => String(v) === option.value);- return (- <CommandItem- key={option.value}- value={option.label}- onSelect={() => toggleValue(option.value)}- className="cursor-pointer"- >- <Checkbox checked={isSelected} className="mr-2" />- <span className="truncate">{option.label}</span>- </CommandItem>- );- })}- </CommandGroup>- </CommandList>- </Command>- )- )}- {needsValue && (- <div className="border-t border-neutral-200 dark:border-neutral-800 p-2">- <Button- type="button"- size="sm"- variant="success"- className="w-full"- disabled={!canSave}- onClick={commitAndClose}- >- <Check className="h-4 w-4" />- {t("Save filter")}- </Button>- </div>- )}- </div>- );-}-+import { authClient } from "../../../../../lib/auth";+import { addFilter, useStore } from "../../../../../lib/store";+import { cn } from "../../../../../lib/utils";+import { FilterPicker } from "./FilterPicker";+import { SegmentDialog } from "./SegmentDialog";+import { SegmentsTab } from "./SegmentsTab";++type Tab = "filters" | "segments";+type DialogState = { segment?: Segment; initialFilters?: Filter[] } | null;++/**+ * The Filter button. Its popover has two tabs: the filter picker that was+ * always here, and the saved segments for this site. Segments live entirely+ * inside this popover so the toolbar gains nothing.+ */export function NewFilterButton({ availableFilters }: { availableFilters?: FilterParameter[] }) {const t = useExtracted();+ const session = authClient.useSession();+ const { site, privateKey, filters } = useStore();+ const { data: siteInfo } = useGetSite(site, { enabled: !!session.data });+ const { data: organizations } = useUserOrganizations();+const [open, setOpen] = useState(false);+ const [tab, setTab] = useState<Tab>("filters");const [parameter, setParameter] = useState<FilterParameter | null>(null);const pendingRef = useRef<() => Filter | null>(() => null);- const getParameterLabel = useParameterLabel();+ const [dialog, setDialog] = useState<DialogState>(null);++ // A signed-in visitor on someone else's public site is not a member; the+ // private-link view is read-only by design even for members.+ const isMember = !!siteInfo?.organizationId && !!organizations?.some(org => org.id === siteInfo.organizationId);+ const canWrite = !!session.data && !privateKey && isMember;- const parameterOptions = availableFilters- ? FilterOptions.filter(o => availableFilters.includes(o.value))- : FilterOptions;+ const resetPicker = () => {+ pendingRef.current = () => null;+ setParameter(null);+ };const handleOpenChange = (isOpen: boolean) => {if (!isOpen) {- const f = pendingRef.current();- if (f) addFilter(f);- pendingRef.current = () => null;- setParameter(null);+ const pending = pendingRef.current();+ if (pending) addFilter(pending);+ resetPicker();}setOpen(isOpen);};- const selectParameter = (param: FilterParameter) => {- setParameter(param);+ // Closing from an action that already did its work must not commit a+ // half-built filter left behind on the Filters tab.+ const closePopover = () => {+ resetPicker();+ setOpen(false);};- const goBackToParameter = () => {- pendingRef.current = () => null;- setParameter(null);+ const selectTab = (next: Tab) => {+ if (next !== tab) resetPicker();+ setTab(next);+ };++ const openDialog = (state: NonNullable<DialogState>) => {+ closePopover();+ setDialog(state);};+ const tabButton = (value: Tab, label: string) => (+ <button+ type="button"+ role="tab"+ aria-selected={tab === value}+ onClick={() => selectTab(value)}+ className={cn(+ "flex-1 py-2 text-xs font-medium border-b-2 -mb-px transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400",+ tab === value+ ? "border-neutral-900 dark:border-neutral-100 text-neutral-900 dark:text-neutral-50"+ : "border-transparent text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200"+ )}+ >+ {label}+ </button>+ );+return (- <Popover open={open} onOpenChange={handleOpenChange}>- <PopoverTrigger asChild>- <Button size="sm" variant="outline" className="gap-1.5">- <ListFilterPlus className="w-4 h-4" />- {t("Filter")}- </Button>- </PopoverTrigger>- <PopoverContent className="w-72 p-0" align="start">- {parameter ? (- <ValueStep- key={parameter}- parameter={parameter}- pendingRef={pendingRef}- onCommit={f => addFilter(f)}- onBack={goBackToParameter}- onClose={() => {- pendingRef.current = () => null;- setParameter(null);- setOpen(false);- }}- />- ) : (- <Command>- <div className="px-3 pt-3 pb-1 text-xs text-neutral-500 dark:text-neutral-400">- {t("Filter stats by")}- </div>- <CommandInput placeholder={t("Search")} />- <CommandList>- <CommandEmpty>{t("No results")}</CommandEmpty>- <CommandGroup>- {parameterOptions.map(option => (- <CommandItem- key={option.value}- value={getParameterLabel(option.value)}- onSelect={() => selectParameter(option.value)}- className="cursor-pointer"- >- <div className="flex items-center gap-2 flex-1 min-w-0">- {option.icon}- <span className="truncate">{getParameterLabel(option.value)}</span>- </div>- <ChevronRight className="h-4 w-4 text-neutral-400" />- </CommandItem>- ))}- </CommandGroup>- </CommandList>- </Command>- )}- </PopoverContent>- </Popover>+ <>+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger asChild>+ <Button size="sm" variant="outline" className="gap-1.5">+ <ListFilterPlus className="w-4 h-4" />+ {t("Filter")}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-72 p-0" align="start">+ <div role="tablist" className="flex border-b border-neutral-200 dark:border-neutral-800">+ {tabButton("filters", t("Filters"))}+ {tabButton("segments", t("Segments"))}+ </div>+ {tab === "filters" ? (+ <FilterPicker+ availableFilters={availableFilters}+ onCommit={addFilter}+ onClose={closePopover}+ pendingRef={pendingRef}+ parameter={parameter}+ setParameter={setParameter}+ />+ ) : (+ <SegmentsTab+ siteId={site}+ canWrite={canWrite}+ onNew={() => openDialog({})}+ onSaveCurrent={() => openDialog({ initialFilters: filters })}+ onEdit={segment => openDialog({ segment })}+ onApplied={closePopover}+ />+ )}+ </PopoverContent>+ </Popover>+ <SegmentDialog+ open={dialog !== null}+ onOpenChange={isOpen => !isOpen && setDialog(null)}+ siteId={site}+ segment={dialog?.segment}+ initialFilters={dialog?.initialFilters}+ availableFilters={availableFilters}+ />+ </>);}diff --git a/client/src/app/[site]/components/SubHeader/Filters/SegmentChip.tsx b/client/src/app/[site]/components/SubHeader/Filters/SegmentChip.tsxnew file mode 100644index 000000000..9cd4ecd5c--- /dev/null+++ b/client/src/app/[site]/components/SubHeader/Filters/SegmentChip.tsx@@ -0,0 +1,132 @@+"use client";++import { Segment } from "@rybbit/shared";+import { Building2, ChevronDown, Layers, Lock, Pencil, X } from "lucide-react";+import { useExtracted } from "next-intl";+import { Button } from "../../../../../components/ui/button";+import { ButtonGroup } from "../../../../../components/ui/button-group";+import { Popover, PopoverContent, PopoverTrigger } from "../../../../../components/ui/popover";+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";+import { useGetRegionName } from "../../../../../lib/geo";+import { clearSegment } from "../../../../../lib/store";+import { isNumericParameter } from "./const";+import {+ formatDisplayValue,+ getParameterIcon,+ operatorNeedsValue,+ useOperatorLabel,+ useParameterLabel,+} from "./labels";++/**+ * One pill for an applied segment. It expands to show the filters it+ * contributed (read-only, so the definition cannot drift by accident) and+ * removes them all at once. "Edited" means one of those filters is no longer+ * in the row, so the segment is a label rather than a guarantee.+ */+export function SegmentChip({+ segment,+ intact,+ onEdit,+}: {+ segment: Segment;+ intact: boolean;+ onEdit?: (segment: Segment) => void;+}) {+ const t = useExtracted();+ const { getRegionName } = useGetRegionName();+ const getParameterLabel = useParameterLabel();+ const getOperatorLabel = useOperatorLabel();++ const remove = () => clearSegment(segment.filters);++ return (+ <ButtonGroup>+ <Popover>+ <PopoverTrigger asChild>+ <Button+ variant="secondary"+ size="sm"+ className="py-1.5 px-2 gap-1.5 text-neutral-900 dark:text-neutral-100 max-w-[320px]"+ >+ <Layers className="h-4 w-4 shrink-0 text-neutral-500 dark:text-neutral-400" />+ <span className="truncate font-medium">{segment.name}</span>+ {!intact && (+ <span className="text-xs font-normal text-neutral-500 dark:text-neutral-400">{t("(edited)")}</span>+ )}+ <ChevronDown className="h-3 w-3 shrink-0 text-neutral-500 dark:text-neutral-400" />+ </Button>+ </PopoverTrigger>+ <PopoverContent align="start" className="w-80 p-0">+ <div className="px-3 pt-3 pb-2 border-b border-neutral-200 dark:border-neutral-800">+ <div className="flex items-center gap-2 text-sm font-medium">+ <span className="truncate">{segment.name}</span>+ {segment.siteId === null && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Building2 className="h-3.5 w-3.5 shrink-0 text-neutral-500 dark:text-neutral-400" />+ </TooltipTrigger>+ <TooltipContent>{t("Shared with every site in the organization")}</TooltipContent>+ </Tooltip>+ )}+ </div>+ {segment.description && (+ <p className="text-xs text-neutral-500 dark:text-neutral-400 mt-1">{segment.description}</p>+ )}+ </div>+ <div className="px-3 py-2">+ <div className="text-[11px] uppercase tracking-wide text-neutral-500 dark:text-neutral-400 mb-1.5">+ {t("Defined as")}+ </div>+ <ul className="flex flex-col gap-1">+ {segment.filters.map((filter, index) => (+ <li key={index} className="flex items-center gap-1.5 text-xs text-neutral-700 dark:text-neutral-200">+ <span className="text-neutral-500 dark:text-neutral-400 [&_svg]:h-3.5 [&_svg]:w-3.5">+ {getParameterIcon(filter.parameter)}+ </span>+ <span>{getParameterLabel(filter.parameter)}</span>+ <span className="text-neutral-500 dark:text-neutral-400">+ {getOperatorLabel(filter.type, isNumericParameter(filter.parameter))}+ </span>+ {operatorNeedsValue(filter.type) && (+ <span className="font-medium truncate">{formatDisplayValue(filter, getRegionName)}</span>+ )}+ </li>+ ))}+ </ul>+ {!intact && (+ <p className="text-xs text-neutral-500 dark:text-neutral-400 mt-2">+ {t("Some of these filters were changed on the dashboard. The segment itself is unchanged.")}+ </p>+ )}+ </div>+ <div className="border-t border-neutral-200 dark:border-neutral-800 p-2 flex items-center justify-between">+ {segment.canEdit && onEdit ? (+ <Button size="sm" variant="ghost" onClick={() => onEdit(segment)} className="gap-1.5">+ <Pencil className="h-3.5 w-3.5" />+ {t("Edit segment")}+ </Button>+ ) : (+ <span className="flex items-center gap-1.5 px-2 text-xs text-neutral-500 dark:text-neutral-400">+ <Lock className="h-3 w-3" />+ {t("Read-only")}+ </span>+ )}+ <Button size="sm" variant="ghost" onClick={remove} className="text-neutral-500 dark:text-neutral-400">+ {t("Remove")}+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ <Button+ variant="secondary"+ size="sm"+ className="text-neutral-500 dark:text-neutral-400 px-1.5"+ onClick={remove}+ aria-label={t("Remove segment")}+ >+ <X size={14} strokeWidth={2.5} />+ </Button>+ </ButtonGroup>+ );+}diff --git a/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx b/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsxnew file mode 100644index 000000000..6b5202803--- /dev/null+++ b/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx@@ -0,0 +1,410 @@+"use client";++import { zodResolver } from "@hookform/resolvers/zod";+import type { Filter, FilterParameter, Segment } from "@rybbit/shared";+import { Building2, Globe, Plus, Trash2 } from "lucide-react";+import { useExtracted } from "next-intl";+import { useRef, useState } from "react";+import { useForm } from "react-hook-form";+import * as z from "zod";+import { useGetSite } from "../../../../../api/admin/hooks/useSites";+import {+ useCreateSegment,+ useDeleteSegment,+ useGetSegments,+ useUpdateSegment,+} from "../../../../../api/analytics/hooks/useSegments";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "../../../../../components/ui/alert-dialog";+import { Button } from "../../../../../components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "../../../../../components/ui/dialog";+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "../../../../../components/ui/form";+import { Input } from "../../../../../components/ui/input";+import { Label } from "../../../../../components/ui/label";+import { Popover, PopoverContent, PopoverTrigger } from "../../../../../components/ui/popover";+import { toast } from "../../../../../components/ui/sonner";+import { Switch } from "../../../../../components/ui/switch";+import { Textarea } from "../../../../../components/ui/textarea";+import { authClient } from "../../../../../lib/auth";+import { useGetRegionName } from "../../../../../lib/geo";+import { applySegment, clearSegment, useStore } from "../../../../../lib/store";+import { cn } from "../../../../../lib/utils";+import { FilterChip } from "./FilterChip";+import { FilterPicker } from "./FilterPicker";+import { formatDisplayValue, operatorNeedsValue, useParameterLabel } from "./labels";+import {+ filterListKeys,+ SEGMENT_DESCRIPTION_MAX_LENGTH,+ SEGMENT_MAX_FILTERS,+ SEGMENT_NAME_MAX_LENGTH,+} from "./segmentUtils";++const filterSchema = z.object({+ parameter: z.string().min(1),+ type: z.string().min(1),+ value: z.array(z.union([z.string(), z.number()])),+});++const formSchema = z.object({+ name: z.string().trim().min(1, "Give the segment a name").max(SEGMENT_NAME_MAX_LENGTH),+ description: z.string().trim().max(SEGMENT_DESCRIPTION_MAX_LENGTH),+ filters: z.array(filterSchema).min(1, "Add at least one filter").max(SEGMENT_MAX_FILTERS),+ scope: z.enum(["site", "organization"]),+ isPublic: z.boolean(),+});++type FormValues = z.infer<typeof formSchema>;++export interface SegmentDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ siteId: string;+ /** Edit this segment; omit to create a new one. */+ segment?: Segment;+ /** Starting filters for a new segment, e.g. the dashboard's current chips. */+ initialFilters?: Filter[];+ availableFilters?: FilterParameter[];+}++/**+ * Create or edit a segment. The filters are edited inside the dialog with the+ * same chips and picker as the filter bar, so a segment can be built from+ * scratch without first applying anything to the dashboard.+ */+export function SegmentDialog(props: SegmentDialogProps) {+ const t = useExtracted();+ const { open, onOpenChange, segment } = props;+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{segment ? t("Edit segment") : t("New segment")}</DialogTitle>+ <DialogDescription>+ {segment+ ? t("Changes apply everywhere this segment is used.")+ : t("A segment is a named set of filters you can apply to any report with one click.")}+ </DialogDescription>+ </DialogHeader>+ {open && <SegmentForm {...props} />}+ </DialogContent>+ </Dialog>+ );+}++function SegmentForm({ onOpenChange, siteId, segment, initialFilters, availableFilters }: SegmentDialogProps) {+ const t = useExtracted();+ const { data: site } = useGetSite(siteId);+ const { data: activeOrganization } = authClient.useActiveOrganization();+ const { getRegionName } = useGetRegionName();+ const getParameterLabel = useParameterLabel();+ const appliedSegmentId = useStore(state => state.segmentId);+ const { data: segments } = useGetSegments(siteId);+ // Applying the new segment must drop the filters the currently applied one+ // contributed, or they linger in the row as anonymous ad-hoc chips.+ const appliedSegment = segments?.find(s => s.segmentId === appliedSegmentId);++ const { mutateAsync: createSegment, isPending: isCreating } = useCreateSegment();+ const { mutateAsync: updateSegment, isPending: isUpdating } = useUpdateSegment();+ const { mutate: deleteSegment, isPending: isDeleting } = useDeleteSegment();++ const startingFilters = segment?.filters ?? initialFilters ?? [];+ const suggestedName = startingFilters+ .map(filter => (operatorNeedsValue(filter.type) ? formatDisplayValue(filter, getRegionName) : getParameterLabel(filter.parameter)))+ .filter(Boolean)+ .join(" · ");++ const form = useForm<FormValues>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ name: segment?.name ?? suggestedName,+ description: segment?.description ?? "",+ filters: startingFilters,+ scope: segment ? (segment.siteId === null ? "organization" : "site") : "site",+ isPublic: segment?.isPublic ?? false,+ },+ });++ const filters = form.watch("filters") as Filter[];+ const filterKeys = filterListKeys(filters);+ const scope = form.watch("scope");+ const setFilters = (next: Filter[]) => form.setValue("filters", next, { shouldValidate: true, shouldDirty: true });++ const [pickerOpen, setPickerOpen] = useState(false);+ const [pickerParameter, setPickerParameter] = useState<FilterParameter | null>(null);+ const pendingRef = useRef<() => Filter | null>(() => null);++ const addFilter = (filter: Filter) => {+ const index = filters.findIndex(f => f.parameter === filter.parameter && f.type === filter.type);+ setFilters(index === -1 ? [...filters, filter] : filters.map((f, i) => (i === index ? filter : f)));+ };++ const handlePickerOpenChange = (isOpen: boolean) => {+ if (!isOpen) {+ const pending = pendingRef.current();+ if (pending) addFilter(pending);+ pendingRef.current = () => null;+ setPickerParameter(null);+ }+ setPickerOpen(isOpen);+ };++ // Org-wide scope is an admin decision on the server; only offer it when the+ // toggle can succeed, or when the segment is already org-wide.+ const canChooseScope = !!site?.isOwner || segment?.siteId === null;+ const organizationName = activeOrganization?.name;+ const isSaving = isCreating || isUpdating;++ const onSubmit = async (values: FormValues) => {+ const body = {+ name: values.name,+ description: values.description.length > 0 ? values.description : null,+ filters: values.filters as Filter[],+ isPublic: values.isPublic,+ scope: values.scope,+ };+ try {+ if (segment) {+ const updated = await updateSegment({ siteId, segmentId: segment.segmentId, body });+ // An applied segment whose filters changed is re-applied so the row+ // matches the new definition instead of silently going "edited".+ if (appliedSegmentId === segment.segmentId) applySegment(updated, segment.filters);+ toast.success(t("Saved segment “{name}”", { name: updated.name }));+ } else {+ const created = await createSegment({ siteId, body });+ applySegment(created, appliedSegment?.filters);+ toast.success(t("Saved segment “{name}”", { name: created.name }));+ }+ onOpenChange(false);+ } catch (error) {+ toast.error(error instanceof Error ? error.message : t("Failed to save segment"));+ }+ };++ const onDelete = () => {+ if (!segment) return;+ deleteSegment(+ { siteId, segmentId: segment.segmentId },+ {+ onSuccess: () => {+ if (appliedSegmentId === segment.segmentId) clearSegment(segment.filters);+ toast.success(t("Deleted segment “{name}”", { name: segment.name }));+ onOpenChange(false);+ },+ onError: error => toast.error(error instanceof Error ? error.message : t("Failed to delete segment")),+ }+ );+ };++ return (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>{t("Name")}</FormLabel>+ <FormControl>+ <Input {...field} placeholder={t("e.g. Mobile organic from Germany")} autoFocus maxLength={SEGMENT_NAME_MAX_LENGTH} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="filters"+ render={() => (+ <FormItem>+ <FormLabel>{t("Filters")}</FormLabel>+ <div className="flex flex-wrap gap-2">+ {filters.map((filter, index) => (+ <FilterChip+ key={filterKeys[index]}+ filter={filter}+ availableFilters={availableFilters}+ onUpdate={next => setFilters(filters.map((f, i) => (i === index ? next : f)))}+ onRemove={() => setFilters(filters.filter((_, i) => i !== index))}+ />+ ))}+ <Popover open={pickerOpen} onOpenChange={handlePickerOpenChange}>+ <PopoverTrigger asChild>+ <Button type="button" size="sm" variant="outline" className="gap-1.5">+ <Plus className="h-4 w-4" />+ {t("Add filter")}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-72 p-0" align="start">+ <FilterPicker+ availableFilters={availableFilters}+ onCommit={addFilter}+ onClose={() => setPickerOpen(false)}+ pendingRef={pendingRef}+ parameter={pickerParameter}+ setParameter={setPickerParameter}+ />+ </PopoverContent>+ </Popover>+ </div>+ <p className="text-xs text-neutral-500 dark:text-neutral-400">+ {t("Every filter must match. Values within one filter are alternatives.")}+ </p>+ <FormMessage />+ </FormItem>+ )}+ />++ {canChooseScope && (+ <FormField+ control={form.control}+ name="scope"+ render={({ field }) => (+ <FormItem>+ <FormLabel>{t("Available on")}</FormLabel>+ <div className="inline-flex rounded-lg border border-neutral-200 dark:border-neutral-800 overflow-hidden">+ <ScopeOption+ selected={field.value === "site"}+ onSelect={() => field.onChange("site")}+ icon={<Globe className="h-3.5 w-3.5" />}+ label={t("This site")}+ />+ <ScopeOption+ selected={field.value === "organization"}+ onSelect={() => field.onChange("organization")}+ icon={<Building2 className="h-3.5 w-3.5" />}+ label={+ organizationName+ ? t("All sites in {organization}", { organization: organizationName })+ : t("All sites in the organization")+ }+ />+ </div>+ {scope === "organization" && (+ <p className="text-xs text-neutral-500 dark:text-neutral-400">+ {t("Site-specific values such as paths may not mean the same thing on every site.")}+ </p>+ )}+ </FormItem>+ )}+ />+ )}++ <FormField+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ {t("Description")}{" "}+ <span className="font-normal text-neutral-500 dark:text-neutral-400">{t("optional")}</span>+ </FormLabel>+ <FormControl>+ <Textarea {...field} rows={2} maxLength={SEGMENT_DESCRIPTION_MAX_LENGTH} placeholder={t("Why this group matters")} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="isPublic"+ render={({ field }) => (+ <FormItem className="flex items-center gap-2 space-y-0">+ <FormControl>+ <Switch id="segment-public" checked={field.value} onCheckedChange={field.onChange} />+ </FormControl>+ <Label htmlFor="segment-public" className="font-normal">+ {t("Show on the public dashboard and private links")}+ </Label>+ </FormItem>+ )}+ />++ <DialogFooter className="sm:justify-between gap-2">+ <div>+ {segment?.canEdit && (+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button type="button" variant="ghost" className="text-red-600 dark:text-red-400 gap-1.5" disabled={isDeleting}>+ <Trash2 className="h-4 w-4" />+ {t("Delete")}+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Delete segment?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(+ "“{name}” will be removed for everyone who uses it. Links that already expanded its filters keep working.",+ { name: segment.name }+ )}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>+ <AlertDialogAction onClick={onDelete}>{t("Delete")}</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ )}+ </div>+ <div className="flex gap-2">+ <Button type="button" variant="secondary" onClick={() => onOpenChange(false)} disabled={isSaving}>+ {t("Cancel")}+ </Button>+ <Button type="submit" variant="success" disabled={isSaving}>+ {isSaving ? t("Saving...") : segment ? t("Save changes") : t("Save segment")}+ </Button>+ </div>+ </DialogFooter>+ </form>+ </Form>+ );+}++function ScopeOption({+ selected,+ onSelect,+ icon,+ label,+}: {+ selected: boolean;+ onSelect: () => void;+ icon: React.ReactNode;+ label: string;+}) {+ return (+ <button+ type="button"+ onClick={onSelect}+ aria-pressed={selected}+ className={cn(+ "inline-flex items-center gap-1.5 px-3 py-1.5 text-xs border-r last:border-r-0 border-neutral-200 dark:border-neutral-800 transition-colors",+ selected+ ? "bg-neutral-100 dark:bg-neutral-800 text-neutral-900 dark:text-neutral-50 font-medium"+ : "text-neutral-600 dark:text-neutral-400 hover:bg-neutral-50 dark:hover:bg-neutral-800/60"+ )}+ >+ {icon}+ {label}+ </button>+ );+}diff --git a/client/src/app/[site]/components/SubHeader/Filters/SegmentsTab.tsx b/client/src/app/[site]/components/SubHeader/Filters/SegmentsTab.tsxnew file mode 100644index 000000000..e1ef23224--- /dev/null+++ b/client/src/app/[site]/components/SubHeader/Filters/SegmentsTab.tsx@@ -0,0 +1,259 @@+"use client";++import { Segment } from "@rybbit/shared";+import { BookmarkPlus, Building2, Check, Eye, Layers, MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react";+import { useExtracted } from "next-intl";+import { useState } from "react";+import { useDeleteSegment, useGetSegments } from "../../../../../api/analytics/hooks/useSegments";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "../../../../../components/ui/alert-dialog";+import { Button } from "../../../../../components/ui/button";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "../../../../../components/ui/command";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "../../../../../components/ui/dropdown-menu";+import { Skeleton } from "../../../../../components/ui/skeleton";+import { toast } from "../../../../../components/ui/sonner";+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";+import { useGetRegionName } from "../../../../../lib/geo";+import { applySegment, clearSegment, useStore } from "../../../../../lib/store";+import { cn } from "../../../../../lib/utils";+import { isNumericParameter } from "./const";+import { formatDisplayValue, operatorNeedsValue, useOperatorLabel, useParameterLabel } from "./labels";+import { partitionFilters } from "./segmentUtils";++function useSegmentSummary() {+ const { getRegionName } = useGetRegionName();+ const getParameterLabel = useParameterLabel();+ const getOperatorLabel = useOperatorLabel();+ return (segment: Segment) =>+ segment.filters+ .map(filter => {+ const parts = [+ getParameterLabel(filter.parameter),+ getOperatorLabel(filter.type, isNumericParameter(filter.parameter)),+ ];+ if (operatorNeedsValue(filter.type)) parts.push(formatDisplayValue(filter, getRegionName));+ return parts.join(" ");+ })+ .join(" · ");+}++/**+ * The Segments tab of the Filter popover: every saved segment for this site,+ * click to apply, a row menu for edit and delete, and the two ways to make a+ * new one (from scratch, or from whatever filters are on the dashboard).+ */+export function SegmentsTab({+ siteId,+ canWrite,+ onNew,+ onSaveCurrent,+ onEdit,+ onApplied,+}: {+ siteId: string;+ /** False for public-dashboard and private-link viewers: no create, save, edit, or delete. */+ canWrite: boolean;+ onNew: () => void;+ onSaveCurrent: () => void;+ onEdit: (segment: Segment) => void;+ onApplied: () => void;+}) {+ const t = useExtracted();+ const { data: segments, isLoading } = useGetSegments(siteId);+ const { filters, segmentId } = useStore();+ const summarize = useSegmentSummary();+ const { mutate: deleteSegment, isPending: isDeleting } = useDeleteSegment();+ const [pendingDelete, setPendingDelete] = useState<Segment | null>(null);++ const active = segments?.find(segment => segment.segmentId === segmentId);+ const { adHoc } = partitionFilters(filters, active);+ const canSaveCurrent = canWrite && (active ? adHoc.length > 0 : filters.length > 0);++ const toggle = (segment: Segment) => {+ if (segment.segmentId === segmentId) {+ clearSegment(segment.filters);+ } else {+ applySegment(segment, active?.filters);+ }+ onApplied();+ };++ const confirmDelete = () => {+ if (!pendingDelete) return;+ const target = pendingDelete;+ deleteSegment(+ { siteId, segmentId: target.segmentId },+ {+ onSuccess: () => {+ if (target.segmentId === segmentId) clearSegment(target.filters);+ toast.success(t("Deleted segment “{name}”", { name: target.name }));+ setPendingDelete(null);+ },+ onError: error => {+ toast.error(error instanceof Error ? error.message : t("Failed to delete segment"));+ setPendingDelete(null);+ },+ }+ );+ };++ const footer = canWrite && (+ <div className="border-t border-neutral-200 dark:border-neutral-800 p-2 flex flex-col gap-1.5">+ {canSaveCurrent && (+ <Button size="sm" variant="success" className="w-full gap-1.5" onClick={onSaveCurrent}>+ <BookmarkPlus className="h-4 w-4" />+ {t("Save current filters as segment")}+ </Button>+ )}+ <Button size="sm" variant={canSaveCurrent ? "ghost" : "outline"} className="w-full gap-1.5" onClick={onNew}>+ <Plus className="h-4 w-4" />+ {t("New segment")}+ </Button>+ </div>+ );++ if (isLoading) {+ return (+ <div className="p-3 flex flex-col gap-2">+ <Skeleton className="h-8 w-full" />+ <Skeleton className="h-8 w-full" />+ <Skeleton className="h-8 w-2/3" />+ </div>+ );+ }++ if (!segments || segments.length === 0) {+ return (+ <div>+ <div className="px-4 py-6 text-center flex flex-col items-center gap-1.5">+ <Layers className="h-6 w-6 text-neutral-400 dark:text-neutral-500" />+ <div className="text-sm font-medium">{t("No segments yet")}</div>+ <p className="text-xs text-neutral-500 dark:text-neutral-400 max-w-[30ch]">+ {canWrite+ ? t("Save a set of filters to reuse it on any report with one click.")+ : t("The site owner has not shared any segments on this dashboard.")}+ </p>+ </div>+ {footer}+ </div>+ );+ }++ return (+ <div>+ <Command>+ <CommandInput placeholder={t("Search segments")} />+ <CommandList>+ <CommandEmpty>{t("No results")}</CommandEmpty>+ <CommandGroup>+ {segments.map(segment => {+ const isActive = segment.segmentId === segmentId;+ return (+ <CommandItem+ key={segment.segmentId}+ value={`${segment.name} ${segment.segmentId}`}+ onSelect={() => toggle(segment)}+ className={cn("cursor-pointer items-start gap-2 py-2", isActive && "bg-neutral-100 dark:bg-neutral-800")}+ >+ <Layers className="h-4 w-4 mt-0.5 shrink-0 text-neutral-500 dark:text-neutral-400" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-1.5 min-w-0">+ <span className={cn("truncate", isActive && "font-medium")}>{segment.name}</span>+ {segment.siteId === null && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Building2 className="h-3 w-3 shrink-0 text-neutral-400 dark:text-neutral-500" />+ </TooltipTrigger>+ <TooltipContent>{t("Shared with every site in the organization")}</TooltipContent>+ </Tooltip>+ )}+ {segment.isPublic && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Eye className="h-3 w-3 shrink-0 text-neutral-400 dark:text-neutral-500" />+ </TooltipTrigger>+ <TooltipContent>{t("Shown on the public dashboard")}</TooltipContent>+ </Tooltip>+ )}+ </div>+ <div className="text-[11px] text-neutral-500 dark:text-neutral-400 truncate">+ {summarize(segment)}+ </div>+ </div>+ <Check className={cn("h-4 w-4 mt-0.5 shrink-0", !isActive && "invisible")} />+ {segment.canEdit && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t("Segment actions")}+ onClick={event => event.stopPropagation()}+ className="-mr-1 mt-0.5 rounded p-0.5 text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-200"+ >+ <MoreHorizontal className="h-4 w-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => onEdit(segment)}>+ <Pencil className="h-4 w-4 mr-2" />+ {t("Edit segment")}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => setPendingDelete(segment)}+ className="text-red-600 dark:text-red-400"+ >+ <Trash2 className="h-4 w-4 mr-2" />+ {t("Delete")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </CommandItem>+ );+ })}+ </CommandGroup>+ </CommandList>+ </Command>+ {footer}+ <AlertDialog open={pendingDelete !== null} onOpenChange={open => !open && setPendingDelete(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Delete segment?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(+ "“{name}” will be removed for everyone who uses it. Links that already expanded its filters keep working.",+ { name: pendingDelete?.name ?? "" }+ )}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={isDeleting}>{t("Cancel")}</AlertDialogCancel>+ <AlertDialogAction onClick={confirmDelete} disabled={isDeleting}>+ {t("Delete")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}diff --git a/client/src/app/[site]/components/SubHeader/Filters/segmentUtils.ts b/client/src/app/[site]/components/SubHeader/Filters/segmentUtils.tsnew file mode 100644index 000000000..5b0a0c89d--- /dev/null+++ b/client/src/app/[site]/components/SubHeader/Filters/segmentUtils.ts@@ -0,0 +1,48 @@+import type { Filter, Segment } from "@rybbit/shared";++// @rybbit/shared is a types-only dependency of the client (its imports are+// erased at compile time), so these mirror shared/src/segments.ts. The server+// enforces the same limits; keep the two in sync.+export const SEGMENT_NAME_MAX_LENGTH = 80;+export const SEGMENT_DESCRIPTION_MAX_LENGTH = 500;+export const SEGMENT_MAX_FILTERS = 20;++export const filterKey = (filter: Filter) => JSON.stringify([filter.parameter, filter.type, filter.value]);++/**+ * React keys that follow a filter rather than its position, so removing an+ * earlier chip does not hand its popover state to the next one. Identical+ * filters (rare, but allowed) get a suffix to stay unique.+ */+export function filterListKeys(filters: Filter[]): string[] {+ const seen = new Map<string, number>();+ return filters.map(filter => {+ const key = filterKey(filter);+ const n = seen.get(key) ?? 0;+ seen.set(key, n + 1);+ return n === 0 ? key : `${key}#${n}`;+ });+}++/**+ * Splits the dashboard's filters into the ones an applied segment contributed+ * and the ad-hoc rest. A segment filter that is no longer present means the+ * user edited the segment's part of the row (or followed an edited link), so+ * the chip can say so instead of pretending the segment still applies intact.+ */+export function partitionFilters(filters: Filter[], segment: Segment | undefined) {+ if (!segment) {+ return { adHoc: filters, intact: true };+ }+ const segmentKeys = new Set(segment.filters.map(filterKey));+ const present = new Set<string>();+ const adHoc = filters.filter(filter => {+ const key = filterKey(filter);+ if (segmentKeys.has(key)) {+ present.add(key);+ return false;+ }+ return true;+ });+ return { adHoc, intact: present.size === segmentKeys.size };+}diff --git a/client/src/app/settings/account/components/ApiKeyScopePicker.tsx b/client/src/app/settings/account/components/ApiKeyScopePicker.tsxindex 80dc72f4a..783c912ae 100644--- a/client/src/app/settings/account/components/ApiKeyScopePicker.tsx+++ b/client/src/app/settings/account/components/ApiKeyScopePicker.tsx@@ -18,6 +18,7 @@ const SCOPE_MATRIX = {goals: ["read", "write"],funnels: ["read", "write"],dashboards: ["read", "write"],+ segments: ["read", "write"],flags: ["read", "write"],experiments: ["read", "write"],sites: ["read", "write"],@@ -39,6 +40,7 @@ const SCOPE_DESCRIPTORS: { resource: ScopeResource; label: string; description:{ resource: "goals", label: "Goals", description: "Conversion goals" },{ resource: "funnels", label: "Funnels", description: "Saved and ad-hoc conversion funnels" },{ resource: "dashboards", label: "Dashboards", description: "Saved dashboards" },+ { resource: "segments", label: "Segments", description: "Saved filter segments" },{ resource: "flags", label: "Feature flags", description: "Feature flag definitions and evaluation" },{ resource: "experiments", label: "Experiments", description: "A/B experiments and their results" },{ resource: "sites", label: "Sites", description: "Site configuration; write covers create, update, and delete" },diff --git a/client/src/lib/parsers.ts b/client/src/lib/parsers.tsindex a82a7d264..1c5dd41c0 100644--- a/client/src/lib/parsers.ts+++ b/client/src/lib/parsers.ts@@ -109,9 +109,12 @@ function isFilter(value: unknown): value is Filter {if (!value || typeof value !== "object") return false;const candidate = value as Partial<Filter>;+ const parameter = candidate.parameter;+ const knownParameter =+ typeof parameter === "string" &&+ (filterParameterSet.has(parameter as FilterParameter) || parameter.startsWith("feature_flag:"));return (- typeof candidate.parameter === "string" &&- filterParameterSet.has(candidate.parameter as FilterParameter) &&+ knownParameter &&typeof candidate.type === "string" &&filterTypeSet.has(candidate.type as FilterType) &&Array.isArray(candidate.value) &&@@ -165,6 +168,9 @@ export const analyticsParsers = {bucket: parseAsTimeBucket,stat: parseAsStatType,filters: parseAsFilters,+ // Saved segment whose filters are already expanded into `filters`; keeps+ // the chip labelled on shared links.+ segment: parseAsInteger,// Feature flagsembed: parseAsBoolean,diff --git a/client/src/lib/store.ts b/client/src/lib/store.tsindex e40b4897a..2a8a44591 100644--- a/client/src/lib/store.ts+++ b/client/src/lib/store.ts@@ -60,6 +60,9 @@ type Store = {setSelectedStat: (stat: StatType) => void;filters: Filter[];setFilters: (filters: Filter[]) => void;+ /** The saved segment whose filters are part of `filters`; null when none is applied. */+ segmentId: number | null;+ setSegmentId: (segmentId: number | null) => void;timezone: string;setTimezone: (timezone: string) => void;};@@ -83,6 +86,7 @@ const getSiteStateForUrl = (state: Store, site: string, privateKey?: string | nuconst hasBucketInUrl = urlParams?.has("bucket");const hasStatInUrl = urlParams?.has("stat");const hasFiltersInUrl = urlParams?.has("filters");+ const hasSegmentInUrl = urlParams?.has("segment");const defaultTimeState = getDefaultTimeState();return {@@ -94,6 +98,7 @@ const getSiteStateForUrl = (state: Store, site: string, privateKey?: string | nubucket: hasBucketInUrl ? state.bucket : defaultTimeState.bucket,selectedStat: hasStatInUrl ? state.selectedStat : "users",filters: hasFiltersInUrl ? state.filters : [],+ segmentId: hasSegmentInUrl ? state.segmentId : null,};};@@ -128,6 +133,8 @@ export const useStore = create<Store, [["zustand/persist", PersistedStore]]>(setSelectedStat: stat => set({ selectedStat: stat }),filters: [],setFilters: filters => set({ filters }),+ segmentId: null,+ setSegmentId: segmentId => set({ segmentId }),timezone: "system",setTimezone: newTimezone => {const state = get();@@ -173,13 +180,15 @@ export const toUserTimezone = (dt: DateTime): DateTime => {};export const resetStore = () => {- const { setSite, setPrivateKey, setTime, setSelectedStat, setFilters, setComparison } = useStore.getState();+ const { setSite, setPrivateKey, setTime, setSelectedStat, setFilters, setSegmentId, setComparison } =+ useStore.getState();setSite("");setPrivateKey(null);setComparison(DEFAULT_COMPARISON);setTime(getDefaultTime());setSelectedStat("users");setFilters([]);+ setSegmentId(null);};export const goBack = () => {@@ -223,6 +232,34 @@ export const updateFilter = (filter: Filter, index: number) => {setFilters(filters.map((f, i) => (i === index ? filter : f)));};+const filterKey = (filter: Filter) => JSON.stringify([filter.parameter, filter.type, filter.value]);++/**+ * Applies a saved segment: its filters go first, ad-hoc filters that are not+ * already part of it follow, and the filters of the segment being replaced+ * (if any) are dropped. Every report keeps reading `filters`, so nothing+ * else in the dashboard learns what a segment is.+ */+export const applySegment = (+ segment: { segmentId: number; filters: Filter[] },+ replacing: Filter[] = []+) => {+ const { filters, setFilters, setSegmentId } = useStore.getState();+ const dropped = new Set(replacing.map(filterKey));+ const segmentKeys = new Set(segment.filters.map(filterKey));+ const adHoc = filters.filter(f => !dropped.has(filterKey(f)) && !segmentKeys.has(filterKey(f)));+ setFilters([...segment.filters, ...adHoc]);+ setSegmentId(segment.segmentId);+};++/** Removes an applied segment and the filters it contributed; ad-hoc filters stay. */+export const clearSegment = (segmentFilters: Filter[]) => {+ const { filters, setFilters, setSegmentId } = useStore.getState();+ const segmentKeys = new Set(segmentFilters.map(filterKey));+ setFilters(filters.filter(f => !segmentKeys.has(filterKey(f))));+ setSegmentId(null);+};+export const getFilteredFilters = (parameters: FilterParameter[]) => {const { filters } = useStore.getState();return filters.filter(f => parameters.includes(f.parameter));diff --git a/client/src/lib/urlParams.ts b/client/src/lib/urlParams.tsindex 8cb2b115d..748dbd3b3 100644--- a/client/src/lib/urlParams.ts+++ b/client/src/lib/urlParams.ts@@ -19,11 +19,13 @@ export const useSyncStateWithUrl = () => {bucket,selectedStat,filters,+ segmentId,comparison,setTime,setBucket,setSelectedStat,setFilters,+ setSegmentId,setComparison,site,} = useStore();@@ -76,6 +78,7 @@ export const useSyncStateWithUrl = () => {}setFilters(urlParams.filters ?? []);+ setSegmentId(urlParams.segment ?? null);setHydratedUrlKey(hydrationKey);}, [@@ -87,6 +90,7 @@ export const useSyncStateWithUrl = () => {setBucket,setSelectedStat,setFilters,+ setSegmentId,setComparison,urlParams,]);@@ -105,6 +109,7 @@ export const useSyncStateWithUrl = () => {bucket,stat: selectedStat,filters: filters.length > 0 ? filters : null,+ segment: segmentId,};// Note: embed params are automatically preserved by nuqs@@ -114,6 +119,7 @@ export const useSyncStateWithUrl = () => {bucket,selectedStat,filters,+ segmentId,comparison,site,setUrlParams,diff --git a/docs/content/docs/(docs)/feature-guides/main-tab.mdx b/docs/content/docs/(docs)/feature-guides/main-tab.mdxindex 886553b94..1ca995e2c 100644--- a/docs/content/docs/(docs)/feature-guides/main-tab.mdx+++ b/docs/content/docs/(docs)/feature-guides/main-tab.mdx@@ -28,6 +28,8 @@ Combine filters for granular analysis:- Referrer, UTM parameters- Custom event properties+A set of filters you use often can be saved as a [segment](/docs/segments) from the **Segments** tab of the Filter button, then applied to any report with one click.+## Main ChartShows your selected metric over time. Click the metric selector to switch between Users, Sessions, Pageviews, Bounce Rate, Pages Per Session, or Session Duration.diff --git a/docs/content/docs/(docs)/meta.json b/docs/content/docs/(docs)/meta.jsonindex 8ac15bfe4..3ca2f8a7b 100644--- a/docs/content/docs/(docs)/meta.json+++ b/docs/content/docs/(docs)/meta.json@@ -21,6 +21,7 @@"hiding-own-traffic","filter-traffic","bot-detection",+ "segments","goals","funnels","embeds",diff --git a/docs/content/docs/(docs)/segments.mdx b/docs/content/docs/(docs)/segments.mdxnew file mode 100644index 000000000..7783d4df4--- /dev/null+++ b/docs/content/docs/(docs)/segments.mdx@@ -0,0 +1,62 @@+---+title: Segments+description: Save a set of filters as a named segment and apply it to any report with one click+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Step, Steps } from 'fumadocs-ui/components/steps';++A segment is a named, reusable set of [filters](/docs/feature-guides/main-tab#filters). Instead of rebuilding "mobile visitors from Germany who came from search" every time, save it once and apply it to the main dashboard, pages, sessions, funnels, journeys, retention, and exports with one click.++Segments live inside the **Filter** button. Nothing else changes in the dashboard: applying a segment expands its filters into the same filter bar every report already reads.++## Creating a segment++Open the **Filter** button and switch to the **Segments** tab. There are two ways to create one:++<Steps>+<Step>+### From scratch+Click **New segment**. The dialog has its own filter editor, so you can build the definition without applying anything to the dashboard first.+</Step>+<Step>+### From the current filters+Once the dashboard has filters applied, the Segments tab offers **Save current filters as segment**. The dialog opens with those filters and a suggested name.+</Step>+</Steps>++Every segment has:++- **Name** — what the group means to you, such as "Paid traffic" or "Logged-in users"+- **Filters** — at least one. Every filter must match; multiple values inside one filter are alternatives+- **Available on** — this site only, or every site in the organization (organization-wide segments can only be created by admins and owners)+- **Description** — optional notes for your team+- **Show on the public dashboard and private links** — off by default++<Callout type="info">+Filters in a segment are validated against the same schema as the filter bar, so a segment can never save something the dashboard could not query.+</Callout>++## Applying a segment++In the **Segments** tab, click a segment to apply it. It appears in the filter bar as a single chip named after the segment. Click the chip to see the filters it contains; click the **×** to remove all of them at once.++Ad-hoc filters work alongside an applied segment. Add a filter the usual way and it is ANDed with the segment. If one of the segment's own filters is changed on the dashboard, the chip reads **(edited)** so you know the row no longer matches the saved definition; the segment itself is unchanged.++Segments are part of the URL, so a dashboard link with a segment applied opens the same view for whoever you share it with.++## Editing and deleting++Use the **⋯** menu on a segment in the Segments tab, or **Edit segment** from the applied chip. Changes apply everywhere the segment is used. Deleting a segment removes it for everyone; links that already expanded its filters keep working.++## Permissions++| Role | Read and apply | Create | Edit and delete |+| --- | --- | --- | --- |+| Owner or admin | All segments | Site and organization-wide | Any segment |+| Member | All segments | Site segments | Segments they created |+| Public dashboard or private-link viewer | Segments marked as shown on the public dashboard | — | — |++## API and MCP++Every analytics endpoint accepts a `segment_id` query parameter that is expanded server-side, ANDed with any `filters` you also pass. Segments themselves are managed through the [Segments endpoints](/docs/api/segments/list). The [MCP server](/docs/mcp) exposes `list_segments` and `apply_segment`.diff --git a/docs/content/docs/api/getting-started.mdx b/docs/content/docs/api/getting-started.mdxindex 7f9236555..103adead9 100644--- a/docs/content/docs/api/getting-started.mdx+++ b/docs/content/docs/api/getting-started.mdx@@ -219,6 +219,12 @@ All endpoints require date-based, exact datetime, or relative time parameters:The `filters` parameter accepts a JSON-encoded array of filter objects to narrow down your data.+You can also pass `segment_id`, the ID of a [saved segment](/docs/segments), instead of or alongside `filters`. The segment's filters are expanded on the server and ANDed with any `filters` you pass. Use the [Segments endpoints](/docs/api/segments/list) to find IDs. Public and private-link callers can only use segments marked as shown on the public dashboard.++```+?start_date=2024-01-01&end_date=2024-01-31&time_zone=UTC&segment_id=12+```+#### Filter Object Structure<TypeTablediff --git a/docs/content/docs/api/meta.json b/docs/content/docs/api/meta.jsonindex 7c584a230..13c0f9e59 100644--- a/docs/content/docs/api/meta.json+++ b/docs/content/docs/api/meta.json@@ -20,6 +20,7 @@"events","goals","funnels",+ "segments","performance","errors","bots",diff --git a/docs/content/docs/api/segments/create.mdx b/docs/content/docs/api/segments/create.mdxnew file mode 100644index 000000000..04a2f77bb--- /dev/null+++ b/docs/content/docs/api/segments/create.mdx@@ -0,0 +1,154 @@+---+title: Create Segment+description: Creates a saved segment. Members create site segments they own; admins and owners can also create organization-wide segments.+full: true+method: POST+---++import { TypeTable } from 'fumadocs-ui/components/type-table';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';++<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">+<div>++```+POST /api/sites/:site/segments+```++Creates a saved segment. Members create site segments they own; admins and owners can also create organization-wide segments.++### Path Parameters++<TypeTable+ type={{+ site: {+ description: 'Site ID or site identifier',+ type: 'string | number',+ required: true,+ },+ }}+/>++### Request Body++<TypeTable+ type={{+ name: {+ description: 'Segment name (1–80 characters)',+ type: 'string',+ required: true,+ },+ filters: {+ description: 'Filters that define the segment (1–20). Validated with the same schema as the `filters` parameter',+ type: 'Filter[]',+ typeDescription: 'See Filter Parameters in Getting Started',+ required: true,+ },+ description: {+ description: 'Optional notes (up to 500 characters)',+ type: 'string | null',+ required: false,+ },+ scope: {+ description: 'Where the segment is available. Organization-wide segments require an admin or owner',+ type: 'string',+ typeDescription: '"site" | "organization"',+ default: 'site',+ required: false,+ },+ isPublic: {+ description: 'Show on the public dashboard and private links',+ type: 'boolean',+ default: 'false',+ required: false,+ },+ }}+/>+### Response++Returns the created segment with status 201.++<TypeTable+ type={{+ segmentId: { description: 'Segment ID', type: 'number' },+ siteId: { description: 'Site ID, or null for an organization-wide segment', type: 'number | null' },+ organizationId: { description: 'Owning organization', type: 'string' },+ userId: { description: 'Creator, or null once that account is deleted', type: 'string | null' },+ name: { description: 'Segment name', type: 'string' },+ description: { description: 'Notes', type: 'string | null' },+ filters: { description: 'The filters that define the segment', type: 'Filter[]' },+ isPublic: { description: 'Shown on the public dashboard and private links', type: 'boolean' },+ type: { description: 'Always "segment" today; reserved for cohorts', type: 'string' },+ canEdit: { description: 'Whether the caller may edit or delete this segment', type: 'boolean' },+ createdAt: { description: 'ISO 8601 timestamp', type: 'string' },+ updatedAt: { description: 'ISO 8601 timestamp', type: 'string' },+ }}+/>++</div>+<div className="flex flex-col gap-4">++<Tabs items={['cURL', 'JavaScript', 'Python']}>+ <Tab value="cURL">+```bash title="Request"+curl -X POST "https://app.rybbit.io/api/sites/1/segments" \+ -H "Authorization: Bearer your_api_key_here" \+ -H "Content-Type: application/json" \+ -d '{"name": "Mobile organic from Germany", "filters": [{"parameter": "device_type", "type": "equals", "value": ["Mobile"]}, {"parameter": "channel", "type": "equals", "value": ["Organic Search"]}, {"parameter": "country", "type": "equals", "value": ["DE"]}]}'+```+ </Tab>+ <Tab value="JavaScript">+```javascript title="Request"+const response = await fetch(+ 'https://app.rybbit.io/api/sites/1/segments',+ {+ method: 'POST',+ headers: {+ 'Authorization': 'Bearer your_api_key_here',+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({"name": "Mobile organic from Germany", "filters": [{"parameter": "device_type", "type": "equals", "value": ["Mobile"]}, {"parameter": "channel", "type": "equals", "value": ["Organic Search"]}, {"parameter": "country", "type": "equals", "value": ["DE"]}]})+ }+);++const data = await response.json();+```+ </Tab>+ <Tab value="Python">+```python title="Request"+import requests++response = requests.post(+ 'https://app.rybbit.io/api/sites/1/segments',+ json={"name": "Mobile organic from Germany", "filters": [{"parameter": "device_type", "type": "equals", "value": ["Mobile"]}, {"parameter": "channel", "type": "equals", "value": ["Organic Search"]}, {"parameter": "country", "type": "equals", "value": ["DE"]}]},+ headers={'Authorization': 'Bearer your_api_key_here'}+)++data = response.json()+```+ </Tab>+</Tabs>++```json title="Response"+{+ "segmentId": 12,+ "siteId": 1,+ "organizationId": "org_abc123",+ "userId": "user_xyz",+ "name": "Mobile organic from Germany",+ "description": null,+ "filters": [+ { "parameter": "device_type", "type": "equals", "value": ["Mobile"] },+ { "parameter": "channel", "type": "equals", "value": ["Organic Search"] },+ { "parameter": "country", "type": "equals", "value": ["DE"] }+ ],+ "isPublic": false,+ "type": "segment",+ "canEdit": true,+ "createdAt": "2026-09-02T10:15:00.000Z",+ "updatedAt": "2026-09-02T10:15:00.000Z"+}+```++</div>+</div>diff --git a/docs/content/docs/api/segments/delete.mdx b/docs/content/docs/api/segments/delete.mdxnew file mode 100644index 000000000..be55cece9--- /dev/null+++ b/docs/content/docs/api/segments/delete.mdx@@ -0,0 +1,94 @@+---+title: Delete Segment+description: Deletes a saved segment. Admins and owners can delete any segment; members can delete segments they created. Links that already expanded the segment's filters keep working.+full: true+method: DELETE+---++import { TypeTable } from 'fumadocs-ui/components/type-table';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';++<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">+<div>++```+DELETE /api/sites/:site/segments/:segmentId+```++Deletes a saved segment. Admins and owners can delete any segment; members can delete segments they created. Links that already expanded the segment's filters keep working.++### Path Parameters++<TypeTable+ type={{+ site: {+ description: 'Site ID or site identifier',+ type: 'string | number',+ required: true,+ },+ segmentId: {+ description: 'Segment ID',+ type: 'number',+ required: true,+ },+ }}+/>++### Response++<TypeTable+ type={{+ success: {+ description: 'Whether the segment was deleted',+ type: 'boolean',+ },+ }}+/>++</div>+<div className="flex flex-col gap-4">++<Tabs items={['cURL', 'JavaScript', 'Python']}>+ <Tab value="cURL">+```bash title="Request"+curl -X DELETE "https://app.rybbit.io/api/sites/1/segments/12" \+ -H "Authorization: Bearer your_api_key_here"+```+ </Tab>+ <Tab value="JavaScript">+```javascript title="Request"+const response = await fetch(+ 'https://app.rybbit.io/api/sites/1/segments/12',+ {+ method: 'DELETE',+ headers: {+ 'Authorization': 'Bearer your_api_key_here'+ }+ }+);++const data = await response.json();+```+ </Tab>+ <Tab value="Python">+```python title="Request"+import requests++response = requests.delete(+ 'https://app.rybbit.io/api/sites/1/segments/12',+ headers={'Authorization': 'Bearer your_api_key_here'}+)++data = response.json()+```+ </Tab>+</Tabs>++```json title="Response"+{+ "success": true+}+```++</div>+</div>diff --git a/docs/content/docs/api/segments/get.mdx b/docs/content/docs/api/segments/get.mdxnew file mode 100644index 000000000..c89ee2fc5--- /dev/null+++ b/docs/content/docs/api/segments/get.mdx@@ -0,0 +1,119 @@+---+title: Get Segment+description: Returns one saved segment.+full: true+method: GET+---++import { TypeTable } from 'fumadocs-ui/components/type-table';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';++<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">+<div>++```+GET /api/sites/:site/segments/:segmentId+```++Returns one saved segment.++### Path Parameters++<TypeTable+ type={{+ site: {+ description: 'Site ID or site identifier',+ type: 'string | number',+ required: true,+ },+ segmentId: {+ description: 'Segment ID',+ type: 'number',+ required: true,+ },+ }}+/>++### Response++Returns the segment.++<TypeTable+ type={{+ segmentId: { description: 'Segment ID', type: 'number' },+ siteId: { description: 'Site ID, or null for an organization-wide segment', type: 'number | null' },+ organizationId: { description: 'Owning organization', type: 'string' },+ userId: { description: 'Creator, or null once that account is deleted', type: 'string | null' },+ name: { description: 'Segment name', type: 'string' },+ description: { description: 'Notes', type: 'string | null' },+ filters: { description: 'The filters that define the segment', type: 'Filter[]' },+ isPublic: { description: 'Shown on the public dashboard and private links', type: 'boolean' },+ type: { description: 'Always "segment" today; reserved for cohorts', type: 'string' },+ canEdit: { description: 'Whether the caller may edit or delete this segment', type: 'boolean' },+ createdAt: { description: 'ISO 8601 timestamp', type: 'string' },+ updatedAt: { description: 'ISO 8601 timestamp', type: 'string' },+ }}+/>++</div>+<div className="flex flex-col gap-4">++<Tabs items={['cURL', 'JavaScript', 'Python']}>+ <Tab value="cURL">+```bash title="Request"+curl -X GET "https://app.rybbit.io/api/sites/1/segments/12" \+ -H "Authorization: Bearer your_api_key_here"+```+ </Tab>+ <Tab value="JavaScript">+```javascript title="Request"+const response = await fetch(+ 'https://app.rybbit.io/api/sites/1/segments/12',+ {+ method: 'GET',+ headers: {+ 'Authorization': 'Bearer your_api_key_here'+ }+ }+);++const data = await response.json();+```+ </Tab>+ <Tab value="Python">+```python title="Request"+import requests++response = requests.get(+ 'https://app.rybbit.io/api/sites/1/segments/12',+ headers={'Authorization': 'Bearer your_api_key_here'}+)++data = response.json()+```+ </Tab>+</Tabs>++```json title="Response"+{+ "segmentId": 12,+ "siteId": 1,+ "organizationId": "org_abc123",+ "userId": "user_xyz",+ "name": "Mobile organic from Germany",+ "description": null,+ "filters": [+ { "parameter": "device_type", "type": "equals", "value": ["Mobile"] },+ { "parameter": "channel", "type": "equals", "value": ["Organic Search"] },+ { "parameter": "country", "type": "equals", "value": ["DE"] }+ ],+ "isPublic": false,+ "type": "segment",+ "canEdit": true,+ "createdAt": "2026-09-02T10:15:00.000Z",+ "updatedAt": "2026-09-02T10:15:00.000Z"+}+```++</div>+</div>diff --git a/docs/content/docs/api/segments/list.mdx b/docs/content/docs/api/segments/list.mdxnew file mode 100644index 000000000..1349006f5--- /dev/null+++ b/docs/content/docs/api/segments/list.mdx@@ -0,0 +1,116 @@+---+title: Get Segments+description: Returns the saved segments available on a site: its own plus organization-wide ones. Callers without site access only see segments shown on the public dashboard.+full: true+method: GET+---++import { TypeTable } from 'fumadocs-ui/components/type-table';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';++<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">+<div>++```+GET /api/sites/:site/segments+```++Returns the saved segments available on a site: its own plus organization-wide ones. Callers without site access only see segments shown on the public dashboard.++### Path Parameters++<TypeTable+ type={{+ site: {+ description: 'Site ID or site identifier',+ type: 'string | number',+ required: true,+ },+ }}+/>++### Response++Returns an array of segments, sorted by name.++<TypeTable+ type={{+ segmentId: { description: 'Segment ID', type: 'number' },+ siteId: { description: 'Site ID, or null for an organization-wide segment', type: 'number | null' },+ organizationId: { description: 'Owning organization', type: 'string' },+ userId: { description: 'Creator, or null once that account is deleted', type: 'string | null' },+ name: { description: 'Segment name', type: 'string' },+ description: { description: 'Notes', type: 'string | null' },+ filters: { description: 'The filters that define the segment', type: 'Filter[]' },+ isPublic: { description: 'Shown on the public dashboard and private links', type: 'boolean' },+ type: { description: 'Always "segment" today; reserved for cohorts', type: 'string' },+ canEdit: { description: 'Whether the caller may edit or delete this segment', type: 'boolean' },+ createdAt: { description: 'ISO 8601 timestamp', type: 'string' },+ updatedAt: { description: 'ISO 8601 timestamp', type: 'string' },+ }}+/>++</div>+<div className="flex flex-col gap-4">++<Tabs items={['cURL', 'JavaScript', 'Python']}>+ <Tab value="cURL">+```bash title="Request"+curl -X GET "https://app.rybbit.io/api/sites/1/segments" \+ -H "Authorization: Bearer your_api_key_here"+```+ </Tab>+ <Tab value="JavaScript">+```javascript title="Request"+const response = await fetch(+ 'https://app.rybbit.io/api/sites/1/segments',+ {+ method: 'GET',+ headers: {+ 'Authorization': 'Bearer your_api_key_here'+ }+ }+);++const data = await response.json();+```+ </Tab>+ <Tab value="Python">+```python title="Request"+import requests++response = requests.get(+ 'https://app.rybbit.io/api/sites/1/segments',+ headers={'Authorization': 'Bearer your_api_key_here'}+)++data = response.json()+```+ </Tab>+</Tabs>++```json title="Response"+[+ {+ "segmentId": 12,+ "siteId": 1,+ "organizationId": "org_abc123",+ "userId": "user_xyz",+ "name": "Mobile organic from Germany",+ "description": null,+ "filters": [+ { "parameter": "device_type", "type": "equals", "value": ["Mobile"] },+ { "parameter": "channel", "type": "equals", "value": ["Organic Search"] },+ { "parameter": "country", "type": "equals", "value": ["DE"] }+ ],+ "isPublic": false,+ "type": "segment",+ "canEdit": true,+ "createdAt": "2026-09-02T10:15:00.000Z",+ "updatedAt": "2026-09-02T10:15:00.000Z"+ }+]+```++</div>+</div>diff --git a/docs/content/docs/api/segments/meta.json b/docs/content/docs/api/segments/meta.jsonnew file mode 100644index 000000000..5a2cead9b--- /dev/null+++ b/docs/content/docs/api/segments/meta.json@@ -0,0 +1,10 @@+{+ "title": "Segments",+ "pages": [+ "list",+ "get",+ "create",+ "update",+ "delete"+ ]+}diff --git a/docs/content/docs/api/segments/update.mdx b/docs/content/docs/api/segments/update.mdxnew file mode 100644index 000000000..0f2221ea2--- /dev/null+++ b/docs/content/docs/api/segments/update.mdx@@ -0,0 +1,159 @@+---+title: Update Segment+description: Updates a saved segment. Admins and owners can edit any segment; members can edit segments they created. Only the fields you send change.+full: true+method: PUT+---++import { TypeTable } from 'fumadocs-ui/components/type-table';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';++<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">+<div>++```+PUT /api/sites/:site/segments/:segmentId+```++Updates a saved segment. Admins and owners can edit any segment; members can edit segments they created. Only the fields you send change.++### Path Parameters++<TypeTable+ type={{+ site: {+ description: 'Site ID or site identifier',+ type: 'string | number',+ required: true,+ },+ segmentId: {+ description: 'Segment ID',+ type: 'number',+ required: true,+ },+ }}+/>++### Request Body++<TypeTable+ type={{+ name: {+ description: 'Segment name (1–80 characters)',+ type: 'string',+ required: false,+ },+ filters: {+ description: 'Filters that define the segment (1–20). Validated with the same schema as the `filters` parameter',+ type: 'Filter[]',+ typeDescription: 'See Filter Parameters in Getting Started',+ required: false,+ },+ description: {+ description: 'Optional notes (up to 500 characters)',+ type: 'string | null',+ required: false,+ },+ scope: {+ description: 'Where the segment is available. Organization-wide segments require an admin or owner',+ type: 'string',+ typeDescription: '"site" | "organization"',+ default: 'site',+ required: false,+ },+ isPublic: {+ description: 'Show on the public dashboard and private links',+ type: 'boolean',+ default: 'false',+ required: false,+ },+ }}+/>+### Response++Returns the updated segment.++<TypeTable+ type={{+ segmentId: { description: 'Segment ID', type: 'number' },+ siteId: { description: 'Site ID, or null for an organization-wide segment', type: 'number | null' },+ organizationId: { description: 'Owning organization', type: 'string' },+ userId: { description: 'Creator, or null once that account is deleted', type: 'string | null' },+ name: { description: 'Segment name', type: 'string' },+ description: { description: 'Notes', type: 'string | null' },+ filters: { description: 'The filters that define the segment', type: 'Filter[]' },+ isPublic: { description: 'Shown on the public dashboard and private links', type: 'boolean' },+ type: { description: 'Always "segment" today; reserved for cohorts', type: 'string' },+ canEdit: { description: 'Whether the caller may edit or delete this segment', type: 'boolean' },+ createdAt: { description: 'ISO 8601 timestamp', type: 'string' },+ updatedAt: { description: 'ISO 8601 timestamp', type: 'string' },+ }}+/>++</div>+<div className="flex flex-col gap-4">++<Tabs items={['cURL', 'JavaScript', 'Python']}>+ <Tab value="cURL">+```bash title="Request"+curl -X PUT "https://app.rybbit.io/api/sites/1/segments/12" \+ -H "Authorization: Bearer your_api_key_here" \+ -H "Content-Type: application/json" \+ -d '{"name": "Mobile organic (DE)", "isPublic": true}'+```+ </Tab>+ <Tab value="JavaScript">+```javascript title="Request"+const response = await fetch(+ 'https://app.rybbit.io/api/sites/1/segments/12',+ {+ method: 'PUT',+ headers: {+ 'Authorization': 'Bearer your_api_key_here',+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({"name": "Mobile organic (DE)", "isPublic": true})+ }+);++const data = await response.json();+```+ </Tab>+ <Tab value="Python">+```python title="Request"+import requests++response = requests.put(+ 'https://app.rybbit.io/api/sites/1/segments/12',+ json={"name": "Mobile organic (DE)", "isPublic": true},+ headers={'Authorization': 'Bearer your_api_key_here'}+)++data = response.json()+```+ </Tab>+</Tabs>++```json title="Response"+{+ "segmentId": 12,+ "siteId": 1,+ "organizationId": "org_abc123",+ "userId": "user_xyz",+ "name": "Mobile organic (DE)",+ "description": null,+ "filters": [+ { "parameter": "device_type", "type": "equals", "value": ["Mobile"] },+ { "parameter": "channel", "type": "equals", "value": ["Organic Search"] },+ { "parameter": "country", "type": "equals", "value": ["DE"] }+ ],+ "isPublic": true,+ "type": "segment",+ "canEdit": true,+ "createdAt": "2026-09-02T10:15:00.000Z",+ "updatedAt": "2026-09-02T10:15:00.000Z"+}+```++</div>+</div>diff --git a/docs/src/app/[locale]/(home)/compare/cloudflare-analytics/comparison-data.tsx b/docs/src/app/[locale]/(home)/compare/cloudflare-analytics/comparison-data.tsxindex 2eb47af8a..835ef38a3 100644--- a/docs/src/app/[locale]/(home)/compare/cloudflare-analytics/comparison-data.tsx+++ b/docs/src/app/[locale]/(home)/compare/cloudflare-analytics/comparison-data.tsx@@ -10,6 +10,7 @@ export const cloudflareAnalyticsComparisonData: ComparisonSection[] = [{ name: "Funnels", rybbitValue: true, competitorValue: false },{ name: "User journeys (Sankey)", rybbitValue: true, competitorValue: false },{ name: "Conversion goals", rybbitValue: true, competitorValue: false },+ { name: "Saved segments", rybbitValue: true, competitorValue: false },{ name: "UTM tracking", rybbitValue: true, competitorValue: false },{ name: "Public dashboards", rybbitValue: true, competitorValue: false },],diff --git a/docs/src/app/[locale]/(home)/compare/fathom/comparison-data.tsx b/docs/src/app/[locale]/(home)/compare/fathom/comparison-data.tsxindex 8e7fbacbc..3d0b3f7e4 100644--- a/docs/src/app/[locale]/(home)/compare/fathom/comparison-data.tsx+++ b/docs/src/app/[locale]/(home)/compare/fathom/comparison-data.tsx@@ -10,6 +10,7 @@ export const fathomComparisonData: ComparisonSection[] = [{ name: "Funnels", rybbitValue: true, competitorValue: false },{ name: "User journeys (Sankey)", rybbitValue: true, competitorValue: false },{ name: "Conversion goals", rybbitValue: true, competitorValue: true },+ { name: "Saved segments", rybbitValue: true, competitorValue: true },{ name: "UTM tracking", rybbitValue: true, competitorValue: true },{ name: "Public dashboards", rybbitValue: true, competitorValue: true },],diff --git a/docs/src/app/[locale]/(home)/compare/google-analytics/comparison-data.tsx b/docs/src/app/[locale]/(home)/compare/google-analytics/comparison-data.tsxindex 78a0799f3..37c66c0c3 100644--- a/docs/src/app/[locale]/(home)/compare/google-analytics/comparison-data.tsx+++ b/docs/src/app/[locale]/(home)/compare/google-analytics/comparison-data.tsx@@ -10,6 +10,7 @@ export const googleAnalyticsComparisonData: ComparisonSection[] = [{ name: "Funnels", rybbitValue: true, competitorValue: true },{ name: "User journeys (Sankey)", rybbitValue: true, competitorValue: true },{ name: "Conversion goals", rybbitValue: true, competitorValue: true },+ { name: "Saved segments", rybbitValue: true, competitorValue: "Explorations only" },{ name: "UTM tracking", rybbitValue: true, competitorValue: true },{ name: "Public dashboards", rybbitValue: true, competitorValue: false },],diff --git a/docs/src/app/[locale]/(home)/compare/matomo/comparison-data.tsx b/docs/src/app/[locale]/(home)/compare/matomo/comparison-data.tsxindex b0a22bf4f..293380e79 100644--- a/docs/src/app/[locale]/(home)/compare/matomo/comparison-data.tsx+++ b/docs/src/app/[locale]/(home)/compare/matomo/comparison-data.tsx@@ -10,6 +10,7 @@ export const matomoComparisonData: ComparisonSection[] = [{ name: "Funnels", rybbitValue: true, competitorValue: true },{ name: "User journeys (Sankey)", rybbitValue: true, competitorValue: false },{ name: "Conversion goals", rybbitValue: true, competitorValue: true },+ { name: "Saved segments", rybbitValue: true, competitorValue: true },{ name: "UTM tracking", rybbitValue: true, competitorValue: true },{ name: "Public dashboards", rybbitValue: true, competitorValue: false },],diff --git a/docs/src/app/[locale]/(home)/compare/plausible/comparison-data.tsx b/docs/src/app/[locale]/(home)/compare/plausible/comparison-data.tsxindex 696224f04..a1d62a23e 100644--- a/docs/src/app/[locale]/(home)/compare/plausible/comparison-data.tsx+++ b/docs/src/app/[locale]/(home)/compare/plausible/comparison-data.tsx@@ -10,6 +10,7 @@ export const plausibleComparisonData: ComparisonSection[] = [{ name: "Funnels", rybbitValue: "All plans", competitorValue: "Business plan only" },{ name: "User journeys (Sankey)", rybbitValue: true, competitorValue: false },{ name: "Conversion goals", rybbitValue: true, competitorValue: true },+ { name: "Saved segments", rybbitValue: true, competitorValue: true },{ name: "UTM tracking", rybbitValue: true, competitorValue: true },{ name: "Public dashboards", rybbitValue: true, competitorValue: true },],diff --git a/docs/src/app/[locale]/(home)/compare/posthog/comparison-data.tsx b/docs/src/app/[locale]/(home)/compare/posthog/comparison-data.tsxindex a3a01a4bc..97d0859bf 100644--- a/docs/src/app/[locale]/(home)/compare/posthog/comparison-data.tsx+++ b/docs/src/app/[locale]/(home)/compare/posthog/comparison-data.tsx@@ -10,6 +10,7 @@ export const posthogComparisonData: ComparisonSection[] = [{ name: "Funnels", rybbitValue: true, competitorValue: true },{ name: "User journeys (Sankey)", rybbitValue: true, competitorValue: true },{ name: "Conversion goals", rybbitValue: true, competitorValue: true },+ { name: "Saved segments", rybbitValue: true, competitorValue: "Cohorts" },{ name: "UTM tracking", rybbitValue: true, competitorValue: true },{ name: "Public dashboards", rybbitValue: true, competitorValue: true },],diff --git a/docs/src/app/[locale]/(home)/compare/simpleanalytics/comparison-data.tsx b/docs/src/app/[locale]/(home)/compare/simpleanalytics/comparison-data.tsxindex f49f81d2a..19bace051 100644--- a/docs/src/app/[locale]/(home)/compare/simpleanalytics/comparison-data.tsx+++ b/docs/src/app/[locale]/(home)/compare/simpleanalytics/comparison-data.tsx@@ -10,6 +10,7 @@ export const simpleAnalyticsComparisonData: ComparisonSection[] = [{ name: "Funnels", rybbitValue: true, competitorValue: false },{ name: "User journeys (Sankey)", rybbitValue: true, competitorValue: false },{ name: "Conversion goals", rybbitValue: true, competitorValue: true },+ { name: "Saved segments", rybbitValue: true, competitorValue: false },{ name: "UTM tracking", rybbitValue: true, competitorValue: true },{ name: "Public dashboards", rybbitValue: true, competitorValue: true },],diff --git a/docs/src/app/[locale]/(home)/compare/umami/comparison-data.tsx b/docs/src/app/[locale]/(home)/compare/umami/comparison-data.tsxindex c714cb947..bdb01b33a 100644--- a/docs/src/app/[locale]/(home)/compare/umami/comparison-data.tsx+++ b/docs/src/app/[locale]/(home)/compare/umami/comparison-data.tsx@@ -10,6 +10,7 @@ export const umamiComparisonData: ComparisonSection[] = [{ name: "Funnels", rybbitValue: true, competitorValue: true },{ name: "User journeys (Sankey)", rybbitValue: true, competitorValue: true },{ name: "Conversion goals", rybbitValue: true, competitorValue: true },+ { name: "Saved segments", rybbitValue: true, competitorValue: true },{ name: "UTM tracking", rybbitValue: true, competitorValue: true },{ name: "Public dashboards", rybbitValue: true, competitorValue: true },],diff --git a/docs/src/lib/openapi.ts b/docs/src/lib/openapi.tsindex 4c92e305f..3e9e115d6 100644--- a/docs/src/lib/openapi.ts+++ b/docs/src/lib/openapi.ts@@ -94,6 +94,7 @@ const commonParameterReferences = ["PastMinutesStart","PastMinutesEnd","Filters",+ "SegmentId",].map(name => ({ $ref: `#/components/parameters/${name}` }));function pathParameters(path: string): Array<Record<string, unknown>> {@@ -256,6 +257,13 @@ export function buildOpenApiDocument(): OpenApiDocument {description: "JSON-encoded array of analytics filters.",schema: { type: "string" },},+ SegmentId: {+ name: "segment_id",+ in: "query",+ description:+ "ID of a saved segment whose filters are applied server-side, ANDed with any `filters` also passed.",+ schema: { type: "integer", minimum: 1 },+ },},schemas: {ApiError: {diff --git a/server/drizzle/0016_shocking_vance_astro.sql b/server/drizzle/0016_shocking_vance_astro.sqlnew file mode 100644index 000000000..75e015106--- /dev/null+++ b/server/drizzle/0016_shocking_vance_astro.sql@@ -0,0 +1,19 @@+CREATE TABLE "segments" (+ "segment_id" serial PRIMARY KEY NOT NULL,+ "organization_id" text NOT NULL,+ "site_id" integer,+ "user_id" text,+ "name" text NOT NULL,+ "description" text,+ "filters" jsonb DEFAULT '[]'::jsonb NOT NULL,+ "is_public" boolean DEFAULT false NOT NULL,+ "type" text DEFAULT 'segment' NOT NULL,+ "created_at" timestamp DEFAULT now(),+ "updated_at" timestamp DEFAULT now()+);+--> statement-breakpoint+ALTER TABLE "segments" ADD CONSTRAINT "segments_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "segments" ADD CONSTRAINT "segments_site_id_sites_site_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("site_id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "segments" ADD CONSTRAINT "segments_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+CREATE INDEX "segments_organization_idx" ON "segments" USING btree ("organization_id");--> statement-breakpoint+CREATE INDEX "segments_site_idx" ON "segments" USING btree ("site_id");\ No newline at end of filediff --git a/server/drizzle/meta/0016_snapshot.json b/server/drizzle/meta/0016_snapshot.jsonnew file mode 100644index 000000000..2d091569e--- /dev/null+++ b/server/drizzle/meta/0016_snapshot.json@@ -0,0 +1,3164 @@+{+ "id": "f2ba75dc-5cab-41b7-9221-bffb0f9ea629",+ "prevId": "dceb98ae-704d-44a6-b038-41469969e981",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "accountId": {+ "name": "accountId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "providerId": {+ "name": "providerId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "accessToken": {+ "name": "accessToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refreshToken": {+ "name": "refreshToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "idToken": {+ "name": "idToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accessTokenExpiresAt": {+ "name": "accessTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refreshTokenExpiresAt": {+ "name": "refreshTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "account_userId_user_id_fk": {+ "name": "account_userId_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.active_sessions": {+ "name": "active_sessions",+ "schema": "",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "last_activity": {+ "name": "last_activity",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "referenceId": {+ "name": "referenceId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refillInterval": {+ "name": "refillInterval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refillAmount": {+ "name": "refillAmount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lastRefillAt": {+ "name": "lastRefillAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "rateLimitEnabled": {+ "name": "rateLimitEnabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "rateLimitTimeWindow": {+ "name": "rateLimitTimeWindow",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "rateLimitMax": {+ "name": "rateLimitMax",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "requestCount": {+ "name": "requestCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "lastRequest": {+ "name": "lastRequest",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "configId": {+ "name": "configId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.cancellation_feedback": {+ "name": "cancellation_feedback",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason_details": {+ "name": "reason_details",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "retention_offer_shown": {+ "name": "retention_offer_shown",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "retention_offer_accepted": {+ "name": "retention_offer_accepted",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "plan_name_at_cancellation": {+ "name": "plan_name_at_cancellation",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthly_event_count_at_cancellation": {+ "name": "monthly_event_count_at_cancellation",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.dashboards": {+ "name": "dashboards",+ "schema": "",+ "columns": {+ "dashboard_id": {+ "name": "dashboard_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{\"cards\":[]}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "dashboards_site_id_sites_site_id_fk": {+ "name": "dashboards_site_id_sites_site_id_fk",+ "tableFrom": "dashboards",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "dashboards_user_id_user_id_fk": {+ "name": "dashboards_user_id_user_id_fk",+ "tableFrom": "dashboards",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.experiments": {+ "name": "experiments",+ "schema": "",+ "columns": {+ "experiment_id": {+ "name": "experiment_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "feature_flag_id": {+ "name": "feature_flag_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "primary_goal_id": {+ "name": "primary_goal_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "hypothesis": {+ "name": "hypothesis",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'draft'"+ },+ "winning_variant": {+ "name": "winning_variant",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "ended_at": {+ "name": "ended_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "experiments_site_idx": {+ "name": "experiments_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "experiments_feature_flag_idx": {+ "name": "experiments_feature_flag_idx",+ "columns": [+ {+ "expression": "feature_flag_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "experiments_primary_goal_idx": {+ "name": "experiments_primary_goal_idx",+ "columns": [+ {+ "expression": "primary_goal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "experiments_site_id_sites_site_id_fk": {+ "name": "experiments_site_id_sites_site_id_fk",+ "tableFrom": "experiments",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",+ "tableFrom": "experiments",+ "tableTo": "feature_flags",+ "columnsFrom": [+ "feature_flag_id"+ ],+ "columnsTo": [+ "flag_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "experiments_primary_goal_id_goals_goal_id_fk": {+ "name": "experiments_primary_goal_id_goals_goal_id_fk",+ "tableFrom": "experiments",+ "tableTo": "goals",+ "columnsFrom": [+ "primary_goal_id"+ ],+ "columnsTo": [+ "goal_id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "experiments_site_flag_unique": {+ "name": "experiments_site_flag_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "feature_flag_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "experiments_status_check": {+ "name": "experiments_status_check",+ "value": "status IN ('draft', 'running', 'paused', 'completed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.feature_flags": {+ "name": "feature_flags",+ "schema": "",+ "columns": {+ "flag_id": {+ "name": "flag_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "runtime": {+ "name": "runtime",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'client'"+ },+ "flag_type": {+ "name": "flag_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'boolean'"+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "variants": {+ "name": "variants",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "rollout_percentage": {+ "name": "rollout_percentage",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 100+ },+ "rules": {+ "name": "rules",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "condition_sets": {+ "name": "condition_sets",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "salt": {+ "name": "salt",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "md5(random()::text || clock_timestamp()::text)"+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "feature_flags_site_idx": {+ "name": "feature_flags_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "feature_flags_site_id_sites_site_id_fk": {+ "name": "feature_flags_site_id_sites_site_id_fk",+ "tableFrom": "feature_flags",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "feature_flags_site_key_unique": {+ "name": "feature_flags_site_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "feature_flags_rollout_check": {+ "name": "feature_flags_rollout_check",+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"+ },+ "feature_flags_runtime_check": {+ "name": "feature_flags_runtime_check",+ "value": "runtime IN ('client', 'server', 'both')"+ },+ "feature_flags_type_check": {+ "name": "feature_flags_type_check",+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"+ }+ },+ "isRLSEnabled": false+ },+ "public.funnels": {+ "name": "funnels",+ "schema": "",+ "columns": {+ "report_id": {+ "name": "report_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "data": {+ "name": "data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "funnels_site_id_sites_site_id_fk": {+ "name": "funnels_site_id_sites_site_id_fk",+ "tableFrom": "funnels",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "funnels_user_id_user_id_fk": {+ "name": "funnels_user_id_user_id_fk",+ "tableFrom": "funnels",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.goals": {+ "name": "goals",+ "schema": "",+ "columns": {+ "goal_id": {+ "name": "goal_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "goal_type": {+ "name": "goal_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "goals_site_id_sites_site_id_fk": {+ "name": "goals_site_id_sites_site_id_fk",+ "tableFrom": "goals",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.gsc_connections": {+ "name": "gsc_connections",+ "schema": "",+ "columns": {+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "gsc_property_url": {+ "name": "gsc_property_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "gsc_connections_site_id_sites_site_id_fk": {+ "name": "gsc_connections_site_id_sites_site_id_fk",+ "tableFrom": "gsc_connections",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.import_status": {+ "name": "import_status",+ "schema": "",+ "columns": {+ "import_id": {+ "name": "import_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "platform": {+ "name": "platform",+ "type": "import_platform_enum",+ "typeSchema": "public",+ "primaryKey": false,+ "notNull": true+ },+ "imported_events": {+ "name": "imported_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "skipped_events": {+ "name": "skipped_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "invalid_events": {+ "name": "invalid_events",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "import_status_site_id_sites_site_id_fk": {+ "name": "import_status_site_id_sites_site_id_fk",+ "tableFrom": "import_status",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "import_status_organization_id_organization_id_fk": {+ "name": "import_status_organization_id_organization_id_fk",+ "tableFrom": "import_status",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "inviterId": {+ "name": "inviterId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "has_restricted_site_access": {+ "name": "has_restricted_site_access",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "site_ids": {+ "name": "site_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "teamId": {+ "name": "teamId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "invitation_inviterId_user_id_fk": {+ "name": "invitation_inviterId_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": [+ "inviterId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "invitation_organizationId_organization_id_fk": {+ "name": "invitation_organizationId_organization_id_fk",+ "tableFrom": "invitation",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "invitation_teamId_team_id_fk": {+ "name": "invitation_teamId_team_id_fk",+ "tableFrom": "invitation",+ "tableTo": "team",+ "columnsFrom": [+ "teamId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.lifecycle_email_log": {+ "name": "lifecycle_email_log",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_key": {+ "name": "email_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "sent_at": {+ "name": "sent_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "lifecycle_email_log_user_id_user_id_fk": {+ "name": "lifecycle_email_log_user_id_user_id_fk",+ "tableFrom": "lifecycle_email_log",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "lifecycle_email_log_user_email_key_unique": {+ "name": "lifecycle_email_log_user_email_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "email_key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member": {+ "name": "member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "has_restricted_site_access": {+ "name": "has_restricted_site_access",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "member_organizationId_organization_id_fk": {+ "name": "member_organizationId_organization_id_fk",+ "tableFrom": "member",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "member_userId_user_id_fk": {+ "name": "member_userId_user_id_fk",+ "tableFrom": "member",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.member_site_access": {+ "name": "member_site_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "member_id": {+ "name": "member_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "member_site_access_member_idx": {+ "name": "member_site_access_member_idx",+ "columns": [+ {+ "expression": "member_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "member_site_access_site_idx": {+ "name": "member_site_access_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "member_site_access_member_id_member_id_fk": {+ "name": "member_site_access_member_id_member_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "member",+ "columnsFrom": [+ "member_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_site_access_site_id_sites_site_id_fk": {+ "name": "member_site_access_site_id_sites_site_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "member_site_access_created_by_user_id_fk": {+ "name": "member_site_access_created_by_user_id_fk",+ "tableFrom": "member_site_access",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "member_site_access_unique": {+ "name": "member_site_access_unique",+ "nullsNotDistinct": false,+ "columns": [+ "member_id",+ "site_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauthAccessToken": {+ "name": "oauthAccessToken",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "accessToken": {+ "name": "accessToken",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refreshToken": {+ "name": "refreshToken",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accessTokenExpiresAt": {+ "name": "accessTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "refreshTokenExpiresAt": {+ "name": "refreshTokenExpiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "clientId": {+ "name": "clientId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "oauthAccessToken_clientId_oauthApplication_clientId_fk": {+ "name": "oauthAccessToken_clientId_oauthApplication_clientId_fk",+ "tableFrom": "oauthAccessToken",+ "tableTo": "oauthApplication",+ "columnsFrom": [+ "clientId"+ ],+ "columnsTo": [+ "clientId"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauthAccessToken_userId_user_id_fk": {+ "name": "oauthAccessToken_userId_user_id_fk",+ "tableFrom": "oauthAccessToken",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauthAccessToken_accessToken_unique": {+ "name": "oauthAccessToken_accessToken_unique",+ "nullsNotDistinct": false,+ "columns": [+ "accessToken"+ ]+ },+ "oauthAccessToken_refreshToken_unique": {+ "name": "oauthAccessToken_refreshToken_unique",+ "nullsNotDistinct": false,+ "columns": [+ "refreshToken"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauthApplication": {+ "name": "oauthApplication",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "clientId": {+ "name": "clientId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "clientSecret": {+ "name": "clientSecret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "redirectUrls": {+ "name": "redirectUrls",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "oauthApplication_userId_user_id_fk": {+ "name": "oauthApplication_userId_user_id_fk",+ "tableFrom": "oauthApplication",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauthApplication_clientId_unique": {+ "name": "oauthApplication_clientId_unique",+ "nullsNotDistinct": false,+ "columns": [+ "clientId"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauthConsent": {+ "name": "oauthConsent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "clientId": {+ "name": "clientId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "consentGiven": {+ "name": "consentGiven",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "oauthConsent_clientId_oauthApplication_clientId_fk": {+ "name": "oauthConsent_clientId_oauthApplication_clientId_fk",+ "tableFrom": "oauthConsent",+ "tableTo": "oauthApplication",+ "columnsFrom": [+ "clientId"+ ],+ "columnsTo": [+ "clientId"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauthConsent_userId_user_id_fk": {+ "name": "oauthConsent_userId_user_id_fk",+ "tableFrom": "oauthConsent",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.organization": {+ "name": "organization",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monthlyEventCount": {+ "name": "monthlyEventCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "overMonthlyLimit": {+ "name": "overMonthlyLimit",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "approachingLimitNotifiedPeriodStart": {+ "name": "approachingLimitNotifiedPeriodStart",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "planOverride": {+ "name": "planOverride",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "custom_plan": {+ "name": "custom_plan",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "organization_slug_unique": {+ "name": "organization_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.segments": {+ "name": "segments",+ "schema": "",+ "columns": {+ "segment_id": {+ "name": "segment_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "filters": {+ "name": "filters",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'segment'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {+ "segments_organization_idx": {+ "name": "segments_organization_idx",+ "columns": [+ {+ "expression": "organization_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "segments_site_idx": {+ "name": "segments_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "segments_organization_id_organization_id_fk": {+ "name": "segments_organization_id_organization_id_fk",+ "tableFrom": "segments",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "segments_site_id_sites_site_id_fk": {+ "name": "segments_site_id_sites_site_id_fk",+ "tableFrom": "segments",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "segments_user_id_user_id_fk": {+ "name": "segments_user_id_user_id_fk",+ "tableFrom": "segments",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ipAddress": {+ "name": "ipAddress",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "userAgent": {+ "name": "userAgent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "impersonatedBy": {+ "name": "impersonatedBy",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activeOrganizationId": {+ "name": "activeOrganizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activeTeamId": {+ "name": "activeTeamId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_userId_user_id_fk": {+ "name": "session_userId_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.sites": {+ "name": "sites",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "site_id": {+ "name": "site_id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "domain": {+ "name": "domain",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "public": {+ "name": "public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "embed_enabled": {+ "name": "embed_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "saltUserIds": {+ "name": "saltUserIds",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "blockBots": {+ "name": "blockBots",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "first_party_proxy": {+ "name": "first_party_proxy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "excluded_ips": {+ "name": "excluded_ips",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_countries": {+ "name": "excluded_countries",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_paths": {+ "name": "excluded_paths",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_hostnames": {+ "name": "excluded_hostnames",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_user_agents": {+ "name": "excluded_user_agents",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_asns": {+ "name": "excluded_asns",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "excluded_query_params": {+ "name": "excluded_query_params",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "sessionReplay": {+ "name": "sessionReplay",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "webVitals": {+ "name": "webVitals",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackErrors": {+ "name": "trackErrors",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackOutbound": {+ "name": "trackOutbound",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackUrlParams": {+ "name": "trackUrlParams",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackInitialPageView": {+ "name": "trackInitialPageView",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackSpaNavigation": {+ "name": "trackSpaNavigation",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "trackIp": {+ "name": "trackIp",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackButtonClicks": {+ "name": "trackButtonClicks",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackCopy": {+ "name": "trackCopy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "trackFormInteractions": {+ "name": "trackFormInteractions",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "api_key": {+ "name": "api_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "private_link_key": {+ "name": "private_link_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tags": {+ "name": "tags",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ },+ "detected_platform": {+ "name": "detected_platform",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "sites_created_by_user_id_fk": {+ "name": "sites_created_by_user_id_fk",+ "tableFrom": "sites",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "sites_organization_id_organization_id_fk": {+ "name": "sites_organization_id_organization_id_fk",+ "tableFrom": "sites",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "sites_type_check": {+ "name": "sites_type_check",+ "value": "\"sites\".\"type\" IS NULL OR \"sites\".\"type\" IN ('web', 'mobile')"+ }+ },+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "organizationId": {+ "name": "organizationId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "team_organizationId_organization_id_fk": {+ "name": "team_organizationId_organization_id_fk",+ "tableFrom": "team",+ "tableTo": "organization",+ "columnsFrom": [+ "organizationId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.teamMember": {+ "name": "teamMember",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "teamId": {+ "name": "teamId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "userId": {+ "name": "userId",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "teamMember_teamId_team_id_fk": {+ "name": "teamMember_teamId_team_id_fk",+ "tableFrom": "teamMember",+ "tableTo": "team",+ "columnsFrom": [+ "teamId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "teamMember_userId_user_id_fk": {+ "name": "teamMember_userId_user_id_fk",+ "tableFrom": "teamMember",+ "tableTo": "user",+ "columnsFrom": [+ "userId"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_site_access": {+ "name": "team_site_access",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_site_access_team_idx": {+ "name": "team_site_access_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_site_access_site_idx": {+ "name": "team_site_access_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_site_access_team_id_team_id_fk": {+ "name": "team_site_access_team_id_team_id_fk",+ "tableFrom": "team_site_access",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_site_access_site_id_sites_site_id_fk": {+ "name": "team_site_access_site_id_sites_site_id_fk",+ "tableFrom": "team_site_access",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_site_access_unique": {+ "name": "team_site_access_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "site_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.telemetry": {+ "name": "telemetry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "instance_id": {+ "name": "instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "timestamp": {+ "name": "timestamp",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "version": {+ "name": "version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "table_counts": {+ "name": "table_counts",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "clickhouse_size_gb": {+ "name": "clickhouse_size_gb",+ "type": "real",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'user'"+ },+ "displayUsername": {+ "name": "displayUsername",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banned": {+ "name": "banned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "banReason": {+ "name": "banReason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "banExpires": {+ "name": "banExpires",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "stripeCustomerId": {+ "name": "stripeCustomerId",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "overMonthlyLimit": {+ "name": "overMonthlyLimit",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "monthlyEventCount": {+ "name": "monthlyEventCount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "sendAutoEmailReports": {+ "name": "sendAutoEmailReports",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "scheduled_tip_email_ids": {+ "name": "scheduled_tip_email_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[]'::jsonb"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_username_unique": {+ "name": "user_username_unique",+ "nullsNotDistinct": false,+ "columns": [+ "username"+ ]+ },+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_aliases": {+ "name": "user_aliases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "anonymous_id": {+ "name": "anonymous_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_aliases_user_idx": {+ "name": "user_aliases_user_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_aliases_anon_idx": {+ "name": "user_aliases_anon_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "anonymous_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_aliases_site_id_sites_site_id_fk": {+ "name": "user_aliases_site_id_sites_site_id_fk",+ "tableFrom": "user_aliases",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_aliases_site_anon_unique": {+ "name": "user_aliases_site_anon_unique",+ "nullsNotDistinct": false,+ "columns": [+ "site_id",+ "anonymous_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_profiles": {+ "name": "user_profiles",+ "schema": "",+ "columns": {+ "site_id": {+ "name": "site_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "traits": {+ "name": "traits",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_profiles_site_idx": {+ "name": "user_profiles_site_idx",+ "columns": [+ {+ "expression": "site_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_profiles_site_id_sites_site_id_fk": {+ "name": "user_profiles_site_id_sites_site_id_fk",+ "tableFrom": "user_profiles",+ "tableTo": "sites",+ "columnsFrom": [+ "site_id"+ ],+ "columnsTo": [+ "site_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "user_profiles_site_id_user_id_pk": {+ "name": "user_profiles_site_id_user_id_pk",+ "columns": [+ "site_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expiresAt": {+ "name": "expiresAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "createdAt": {+ "name": "createdAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "updatedAt": {+ "name": "updatedAt",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {+ "public.import_platform_enum": {+ "name": "import_platform_enum",+ "schema": "public",+ "values": [+ "umami",+ "simple_analytics",+ "plausible"+ ]+ }+ },+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.jsonindex ea604da8f..105dde9f9 100644--- a/server/drizzle/meta/_journal.json+++ b/server/drizzle/meta/_journal.json@@ -113,6 +113,13 @@"when": 1788371100067,"tag": "0015_round_trish_tilby","breakpoints": true+ },+ {+ "idx": 16,+ "version": "7",+ "when": 1788386038776,+ "tag": "0016_shocking_vance_astro",+ "breakpoints": true}]}\ No newline at end of filediff --git a/server/src/api/analytics/index.ts b/server/src/api/analytics/index.tsindex 43718b8de..8ef8cd391 100644--- a/server/src/api/analytics/index.ts+++ b/server/src/api/analytics/index.ts@@ -23,6 +23,14 @@ export { getDashboards } from "./dashboards/getDashboards.js";export { updateDashboard } from "./dashboards/updateDashboard.js";export { runDashboardCardQuery } from "./runDashboardCardQuery.js";+// Segments+export { createSegment } from "./segments/createSegment.js";+export { deleteSegment } from "./segments/deleteSegment.js";+export { getSegment } from "./segments/getSegment.js";+export { getSegments } from "./segments/getSegments.js";+export { updateSegment } from "./segments/updateSegment.js";+export { expandSegmentParam } from "./segments/expandSegmentParam.js";+// Goalsexport { createGoal } from "./goals/createGoal.js";export { deleteGoal } from "./goals/deleteGoal.js";diff --git a/server/src/api/analytics/segments/createSegment.ts b/server/src/api/analytics/segments/createSegment.tsnew file mode 100644index 000000000..2f83d1f95--- /dev/null+++ b/server/src/api/analytics/segments/createSegment.ts@@ -0,0 +1,62 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { z } from "zod";+import { db } from "../../../db/postgres/postgres.js";+import { segments } from "../../../db/postgres/schema.js";+import { getSiteOrganizationId, parsePositiveId, resolveSegmentActor, serializeSegment } from "./segmentAccess.js";+import { createSegmentSchema } from "./segmentSchema.js";++export async function createSegment(+ request: FastifyRequest<{ Params: { siteId: string }; Body: unknown }>,+ reply: FastifyReply+) {+ const siteId = parsePositiveId(request.params.siteId);+ if (!siteId) {+ return reply.status(400).send({ error: "Invalid site ID" });+ }++ try {+ const body = createSegmentSchema.parse(request.body);++ const organizationId = await getSiteOrganizationId(siteId);+ if (!organizationId) {+ return reply.status(404).send({ error: "Site not found" });+ }++ // Site access is enforced by the requireSiteAccess preHandler; the actor+ // is still resolved because org-wide scope is an admin decision.+ const actor = await resolveSegmentActor(request, siteId, organizationId);+ if (!actor.hasSiteAccess) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ const orgWide = body.scope === "organization";+ if (orgWide && !actor.isAdmin) {+ return reply.status(403).send({ error: "Only organization admins can create organization-wide segments" });+ }++ const [row] = await db+ .insert(segments)+ .values({+ organizationId,+ siteId: orgWide ? null : siteId,+ userId: actor.userId,+ name: body.name,+ description: body.description ?? null,+ filters: body.filters,+ isPublic: body.isPublic ?? false,+ })+ .returning();++ if (!row) {+ return reply.status(500).send({ error: "Failed to create segment" });+ }++ return reply.status(201).send(serializeSegment(row, actor));+ } catch (error) {+ if (error instanceof z.ZodError) {+ return reply.status(400).send({ error: "Validation error", details: error.errors });+ }+ request.log.error({ err: error }, "Error creating segment");+ return reply.status(500).send({ error: "Failed to create segment" });+ }+}diff --git a/server/src/api/analytics/segments/deleteSegment.ts b/server/src/api/analytics/segments/deleteSegment.tsnew file mode 100644index 000000000..eaf9d220d--- /dev/null+++ b/server/src/api/analytics/segments/deleteSegment.ts@@ -0,0 +1,54 @@+import { eq } from "drizzle-orm";+import { FastifyReply, FastifyRequest } from "fastify";+import { db } from "../../../db/postgres/postgres.js";+import { segments } from "../../../db/postgres/schema.js";+import {+ canEditSegment,+ canReadSegment,+ loadSegmentForSite,+ parsePositiveId,+ resolveSegmentActor,+} from "./segmentAccess.js";++export async function deleteSegment(+ request: FastifyRequest<{ Params: { siteId: string; segmentId: string } }>,+ reply: FastifyReply+) {+ const siteId = parsePositiveId(request.params.siteId);+ const segmentId = parsePositiveId(request.params.segmentId);+ if (!siteId) {+ return reply.status(400).send({ error: "Invalid site ID" });+ }+ if (!segmentId) {+ return reply.status(400).send({ error: "Invalid segment ID" });+ }++ try {+ const loaded = await loadSegmentForSite(siteId, segmentId);+ if (!loaded) {+ return reply.status(404).send({ error: "Segment not found" });+ }++ const actor = await resolveSegmentActor(request, siteId, loaded.organizationId);+ if (!canReadSegment(loaded.segment, actor)) {+ return reply.status(404).send({ error: "Segment not found" });+ }+ if (!canEditSegment(loaded.segment, actor)) {+ return reply.status(403).send({ error: "You can only delete segments you created" });+ }++ const result = await db+ .delete(segments)+ .where(eq(segments.segmentId, segmentId))+ .returning({ deleted: segments.segmentId });++ if (result.length === 0) {+ return reply.status(500).send({ error: "Failed to delete segment" });+ }++ return reply.send({ success: true });+ } catch (error) {+ request.log.error({ err: error }, "Error deleting segment");+ return reply.status(500).send({ error: "Failed to delete segment" });+ }+}diff --git a/server/src/api/analytics/segments/expandSegmentParam.test.ts b/server/src/api/analytics/segments/expandSegmentParam.test.tsnew file mode 100644index 000000000..2e827bff9--- /dev/null+++ b/server/src/api/analytics/segments/expandSegmentParam.test.ts@@ -0,0 +1,122 @@+import type { Filter } from "@rybbit/shared";+import { beforeEach, describe, expect, it, vi } from "vitest";++const state = vi.hoisted(() => ({+ loaded: null as null | { segment: any; organizationId: string },+ actor: { userId: null as string | null, hasSiteAccess: false, isAdmin: false },+}));++vi.mock("./segmentAccess.js", async () => {+ const actual = await vi.importActual<typeof import("./segmentAccess.js")>("./segmentAccess.js");+ return {+ ...actual,+ loadSegmentForSite: async () => state.loaded,+ resolveSegmentActor: async () => state.actor,+ };+});++vi.mock("../../../db/postgres/postgres.js", () => ({ db: {} }));++import { expandSegmentParam, mergeSegmentFilters } from "./expandSegmentParam.js";++const mobile: Filter = { parameter: "device_type", type: "equals", value: ["Mobile"] };+const germany: Filter = { parameter: "country", type: "equals", value: ["DE"] };+const chrome: Filter = { parameter: "browser", type: "equals", value: ["Chrome"] };++function run(+ query: Record<string, unknown>,+ params: Record<string, string> = { siteId: "1" },+ extra: Record<string, unknown> = {}+) {+ const request: any = { query, params, headers: {}, ...extra };+ const reply: any = { statusCode: 200 };+ reply.status = vi.fn((code: number) => {+ reply.statusCode = code;+ return reply;+ });+ reply.send = vi.fn((payload: unknown) => {+ reply.payload = payload;+ return reply;+ });+ return expandSegmentParam(request, reply).then(() => ({ request, reply }));+}++beforeEach(() => {+ state.loaded = {+ segment: { segmentId: 7, siteId: 1, organizationId: "org_1", userId: "u", isPublic: false, filters: [mobile, germany] },+ organizationId: "org_1",+ };+ state.actor = { userId: "u", hasSiteAccess: true, isAdmin: false };+});++describe("mergeSegmentFilters", () => {+ it("puts the segment first and drops ad-hoc duplicates", () => {+ expect(mergeSegmentFilters([mobile, germany], [chrome, { ...mobile }])).toEqual([mobile, germany, chrome]);+ });++ it("keeps a filter that differs only in value", () => {+ const mobileTablet = { ...mobile, value: ["Mobile", "Tablet"] };+ expect(mergeSegmentFilters([mobile], [mobileTablet])).toEqual([mobile, mobileTablet]);+ });+});++describe("expandSegmentParam", () => {+ it("does nothing when segment_id is absent", async () => {+ const { request, reply } = await run({ filters: JSON.stringify([chrome]) });+ expect(reply.status).not.toHaveBeenCalled();+ expect(request.query.filters).toBe(JSON.stringify([chrome]));+ });++ it("expands the segment into filters, ANDed with the caller's own", async () => {+ const { request, reply } = await run({ segment_id: "7", filters: JSON.stringify([chrome]) });+ expect(reply.status).not.toHaveBeenCalled();+ expect(JSON.parse(request.query.filters)).toEqual([mobile, germany, chrome]);+ });++ it("expands with no ad-hoc filters at all", async () => {+ const { request } = await run({ segment_id: 7 });+ expect(JSON.parse(request.query.filters)).toEqual([mobile, germany]);+ });++ it("rejects a malformed segment_id", async () => {+ const { reply } = await run({ segment_id: "seven" });+ expect(reply.statusCode).toBe(400);+ expect(reply.payload.error).toBe("Invalid segment_id");+ });++ it("answers 404 for a segment outside the site", async () => {+ state.loaded = null;+ const { reply } = await run({ segment_id: "7" });+ expect(reply.statusCode).toBe(404);+ });++ it("hides a private segment from a public-dashboard viewer but expands a public one", async () => {+ state.actor = { userId: null, hasSiteAccess: false, isAdmin: false };+ const privateResult = await run({ segment_id: "7" });+ expect(privateResult.reply.statusCode).toBe(404);++ state.loaded!.segment.isPublic = true;+ const publicResult = await run({ segment_id: "7" });+ expect(publicResult.reply.status).not.toHaveBeenCalled();+ expect(JSON.parse(publicResult.request.query.filters)).toEqual([mobile, germany]);+ });++ it("requires segments:read from a scoped bearer credential, even when the route only needs analytics:read", async () => {+ const scoped = { bearerAuth: true, bearerStatements: { analytics: ["read"] } };+ const denied = await run({ segment_id: "7" }, { siteId: "1" }, scoped);+ expect(denied.reply.statusCode).toBe(403);+ expect(denied.reply.payload).toEqual({ error: "Insufficient scope", required: "segments:read" });++ const allowed = await run({ segment_id: "7" }, { siteId: "1" }, { bearerAuth: true, bearerStatements: { segments: ["read"] } });+ expect(allowed.reply.status).not.toHaveBeenCalled();++ const legacy = await run({ segment_id: "7" }, { siteId: "1" }, { bearerAuth: true, bearerStatements: null });+ expect(legacy.reply.status).not.toHaveBeenCalled();+ });++ it("rejects caller filters that fail validation instead of silently dropping them", async () => {+ const { reply } = await run({ segment_id: "7", filters: "not json" });+ expect(reply.statusCode).toBe(400);+ expect(reply.payload.error).toBe("Invalid filters");+ });+});diff --git a/server/src/api/analytics/segments/expandSegmentParam.ts b/server/src/api/analytics/segments/expandSegmentParam.tsnew file mode 100644index 000000000..46bff7381--- /dev/null+++ b/server/src/api/analytics/segments/expandSegmentParam.ts@@ -0,0 +1,73 @@+import type { Filter } from "@rybbit/shared";+import { FastifyReply, FastifyRequest } from "fastify";+import { hasScope, scopeToString } from "../../../lib/scopes.js";+import { validateFilters } from "../utils/query-validation.js";+import { canReadSegment, loadSegmentForSite, resolveSegmentActor } from "./segmentAccess.js";++const SEGMENTS_READ = { resource: "segments", action: "read" } as const;++const filterKey = (filter: Filter) => JSON.stringify([filter.parameter, filter.type, filter.value]);++/**+ * Segment filters first, then any ad-hoc filters that are not already part of+ * the segment. Order matters only for readability of the expanded URL; every+ * filter is ANDed by getFilterStatement.+ */+export function mergeSegmentFilters(segmentFilters: Filter[], extra: Filter[]): Filter[] {+ const seen = new Set(segmentFilters.map(filterKey));+ return [...segmentFilters, ...extra.filter(filter => !seen.has(filterKey(filter)))];+}++/**+ * Expands `segment_id` into the `filters` query param before an analytics+ * handler runs, so every endpoint that already reads `filters` accepts a+ * segment with no per-endpoint change. Runs after the site access guard: a+ * caller without site access only expands public segments.+ */+export async function expandSegmentParam(request: FastifyRequest, reply: FastifyReply) {+ const query = request.query as Record<string, unknown> | undefined;+ const raw = query?.segment_id;+ if (raw === undefined || raw === null || raw === "") {+ return;+ }++ const segmentId = Number(raw);+ if (!Number.isInteger(segmentId) || segmentId <= 0) {+ return reply.status(400).send({ error: "Invalid segment_id" });+ }++ const params = request.params as { siteId?: string } | undefined;+ const siteId = Number(params?.siteId);+ if (!Number.isInteger(siteId) || siteId <= 0) {+ return reply.status(400).send({ error: "Site ID required" });+ }++ // The route guard only checked the endpoint's own scope. A scoped bearer+ // credential must also hold segments:read, or it could infer a private+ // segment's definition through this param that it cannot fetch directly.+ if (request.bearerAuth && !hasScope(request.bearerStatements ?? null, SEGMENTS_READ)) {+ return reply.status(403).send({ error: "Insufficient scope", required: scopeToString(SEGMENTS_READ) });+ }++ const loaded = await loadSegmentForSite(siteId, segmentId);+ if (!loaded) {+ return reply.status(404).send({ error: "Segment not found" });+ }++ const actor = await resolveSegmentActor(request, siteId, loaded.organizationId);+ if (!canReadSegment(loaded.segment, actor)) {+ return reply.status(404).send({ error: "Segment not found" });+ }++ let existing: Filter[] = [];+ const rawFilters = query!.filters;+ if (typeof rawFilters === "string" && rawFilters.length > 0) {+ try {+ existing = validateFilters(rawFilters);+ } catch {+ return reply.status(400).send({ error: "Invalid filters" });+ }+ }++ query!.filters = JSON.stringify(mergeSegmentFilters(loaded.segment.filters, existing));+}diff --git a/server/src/api/analytics/segments/getSegment.ts b/server/src/api/analytics/segments/getSegment.tsnew file mode 100644index 000000000..77549fd8a--- /dev/null+++ b/server/src/api/analytics/segments/getSegment.ts@@ -0,0 +1,35 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { canReadSegment, loadSegmentForSite, parsePositiveId, resolveSegmentActor, serializeSegment } from "./segmentAccess.js";++export async function getSegment(+ request: FastifyRequest<{ Params: { siteId: string; segmentId: string } }>,+ reply: FastifyReply+) {+ const siteId = parsePositiveId(request.params.siteId);+ const segmentId = parsePositiveId(request.params.segmentId);+ if (!siteId) {+ return reply.status(400).send({ error: "Invalid site ID" });+ }+ if (!segmentId) {+ return reply.status(400).send({ error: "Invalid segment ID" });+ }++ try {+ const loaded = await loadSegmentForSite(siteId, segmentId);+ if (!loaded) {+ return reply.status(404).send({ error: "Segment not found" });+ }++ const actor = await resolveSegmentActor(request, siteId, loaded.organizationId);+ // A private segment is indistinguishable from a missing one to a viewer+ // without site access, so its existence is never confirmed.+ if (!canReadSegment(loaded.segment, actor)) {+ return reply.status(404).send({ error: "Segment not found" });+ }++ return reply.send(serializeSegment(loaded.segment, actor));+ } catch (error) {+ request.log.error({ err: error }, "Error fetching segment");+ return reply.status(500).send({ error: "Failed to fetch segment" });+ }+}diff --git a/server/src/api/analytics/segments/getSegments.ts b/server/src/api/analytics/segments/getSegments.tsnew file mode 100644index 000000000..22210d2ee--- /dev/null+++ b/server/src/api/analytics/segments/getSegments.ts@@ -0,0 +1,42 @@+import { asc } from "drizzle-orm";+import { FastifyReply, FastifyRequest } from "fastify";+import { db } from "../../../db/postgres/postgres.js";+import { segments } from "../../../db/postgres/schema.js";+import {+ canReadSegment,+ getSiteOrganizationId,+ parsePositiveId,+ resolveSegmentActor,+ segmentsForSiteCondition,+ serializeSegment,+} from "./segmentAccess.js";++export async function getSegments(+ request: FastifyRequest<{ Params: { siteId: string } }>,+ reply: FastifyReply+) {+ const siteId = parsePositiveId(request.params.siteId);+ if (!siteId) {+ return reply.status(400).send({ error: "Invalid site ID" });+ }++ try {+ const organizationId = await getSiteOrganizationId(siteId);+ if (!organizationId) {+ return reply.status(404).send({ error: "Site not found" });+ }++ const [actor, rows] = await Promise.all([+ resolveSegmentActor(request, siteId, organizationId),+ db.query.segments.findMany({+ where: segmentsForSiteCondition(siteId, organizationId),+ orderBy: [asc(segments.name)],+ }),+ ]);++ return reply.send(rows.filter(row => canReadSegment(row, actor)).map(row => serializeSegment(row, actor)));+ } catch (error) {+ request.log.error({ err: error }, "Error fetching segments");+ return reply.status(500).send({ error: "Failed to fetch segments" });+ }+}diff --git a/server/src/api/analytics/segments/segmentAccess.test.ts b/server/src/api/analytics/segments/segmentAccess.test.tsnew file mode 100644index 000000000..d8e444db9--- /dev/null+++ b/server/src/api/analytics/segments/segmentAccess.test.ts@@ -0,0 +1,364 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++/**+ * Exercises the segment auth rules end to end through the real handlers, with+ * the Postgres layer, the site-access lookup, and the org membership lookup+ * replaced by fixtures. The rule under test: anyone with site access can read+ * and apply; admins and owners create, edit, and delete anything; members+ * create their own and edit only those; viewers without access see only+ * public segments and can never write.+ */+const state = vi.hoisted(() => ({+ site: { organizationId: "org_1" } as { organizationId: string | null } | undefined,+ segments: [] as any[],+ siteAccess: false,+ membership: null as null | { role: string },+ systemAdmin: false,+ writes: [] as Array<{ op: string; values?: unknown }>,+}));++vi.mock("../../../db/postgres/postgres.js", () => {+ const returningAll = () => Promise.resolve(state.segments);+ return {+ db: {+ query: {+ sites: { findFirst: async () => state.site },+ segments: {+ findFirst: async () => state.segments[0],+ findMany: async () => state.segments,+ },+ },+ insert: () => ({+ values: (values: unknown) => {+ state.writes.push({ op: "insert", values });+ return { returning: () => Promise.resolve([{ segmentId: 99, ...(values as object) }]) };+ },+ }),+ update: () => ({+ set: (values: unknown) => {+ state.writes.push({ op: "update", values });+ return { where: () => ({ returning: () => Promise.resolve([{ ...state.segments[0], ...(values as object) }]) }) };+ },+ }),+ delete: () => ({+ where: () => {+ state.writes.push({ op: "delete" });+ return { returning: returningAll };+ },+ }),+ },+ };+});++vi.mock("../../../lib/auth-utils.js", () => ({+ getUserHasAccessToSite: async () => state.siteAccess,+ getIsUserAdmin: async () => state.systemAdmin,+}));++vi.mock("../../../lib/access.js", () => ({+ getOrgMembership: async () => state.membership,+ isOrgAdmin: (m: { role: string } | null) => m?.role === "admin" || m?.role === "owner",+}));++import { createSegment } from "./createSegment.js";+import { deleteSegment } from "./deleteSegment.js";+import { getSegment } from "./getSegment.js";+import { getSegments } from "./getSegments.js";+import { canEditSegment, canReadSegment, resolveSegmentActor, segmentBelongsToSite } from "./segmentAccess.js";+import { updateSegment } from "./updateSegment.js";++const filters = [{ parameter: "device_type", type: "equals", value: ["Mobile"] }];++const segmentRow = (overrides: Partial<Record<string, unknown>> = {}) => ({+ segmentId: 7,+ organizationId: "org_1",+ siteId: 1,+ userId: "member_1",+ name: "Mobile",+ description: null,+ filters,+ isPublic: false,+ type: "segment",+ createdAt: "2026-09-01T00:00:00Z",+ updatedAt: "2026-09-01T00:00:00Z",+ ...overrides,+});++function fakeRequest(overrides: Record<string, unknown> = {}) {+ return {+ params: { siteId: "1", segmentId: "7" },+ body: {},+ query: {},+ headers: {},+ log: { error: vi.fn() },+ ...overrides,+ } as any;+}++function fakeReply() {+ const reply: any = { statusCode: 200 };+ reply.status = vi.fn((code: number) => {+ reply.statusCode = code;+ return reply;+ });+ reply.send = vi.fn((payload: unknown) => {+ reply.payload = payload;+ return reply;+ });+ return reply;+}++const asMember = (userId = "member_1") => {+ state.siteAccess = true;+ state.membership = { role: "member" };+ return fakeRequest({ user: { id: userId } });+};+const asAdmin = () => {+ state.siteAccess = true;+ state.membership = { role: "admin" };+ return fakeRequest({ user: { id: "admin_1" } });+};+const asViewer = () => {+ state.siteAccess = false;+ state.membership = null;+ return fakeRequest();+};++beforeEach(() => {+ state.site = { organizationId: "org_1" };+ state.segments = [];+ state.siteAccess = false;+ state.membership = null;+ state.systemAdmin = false;+ state.writes = [];+});++describe("resolveSegmentActor", () => {+ it("treats an organization API key as an admin of its own org only", async () => {+ const own = await resolveSegmentActor(fakeRequest({ apiKeyOrganizationId: "org_1" }), 1, "org_1");+ expect(own).toEqual({ userId: null, hasSiteAccess: true, isAdmin: true });++ const other = await resolveSegmentActor(fakeRequest({ apiKeyOrganizationId: "org_2" }), 1, "org_1");+ expect(other).toEqual({ userId: null, hasSiteAccess: false, isAdmin: false });+ });++ it("gives an anonymous viewer no access at all", async () => {+ expect(await resolveSegmentActor(fakeRequest(), 1, "org_1")).toEqual({+ userId: null,+ hasSiteAccess: false,+ isAdmin: false,+ });+ });++ it("marks org owners, org admins, and system admins as admins", async () => {+ state.siteAccess = true;+ state.membership = { role: "owner" };+ expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).isAdmin).toBe(true);++ state.membership = { role: "member" };+ expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).isAdmin).toBe(false);++ state.systemAdmin = true;+ expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).isAdmin).toBe(true);+ });+});++describe("rule predicates", () => {+ const admin = { userId: "a", hasSiteAccess: true, isAdmin: true };+ const member = { userId: "member_1", hasSiteAccess: true, isAdmin: false };+ const viewer = { userId: null, hasSiteAccess: false, isAdmin: false };++ it("reads: site access sees everything, viewers see public only", () => {+ expect(canReadSegment({ isPublic: false }, member)).toBe(true);+ expect(canReadSegment({ isPublic: false }, viewer)).toBe(false);+ expect(canReadSegment({ isPublic: true }, viewer)).toBe(true);+ });++ it("edits: admins edit anything, members only their own, viewers nothing", () => {+ expect(canEditSegment({ userId: "someone_else" }, admin)).toBe(true);+ expect(canEditSegment({ userId: "member_1" }, member)).toBe(true);+ expect(canEditSegment({ userId: "someone_else" }, member)).toBe(false);+ expect(canEditSegment({ userId: null }, member)).toBe(false);+ expect(canEditSegment({ userId: null }, viewer)).toBe(false);+ });++ it("scopes a segment to its own site or its whole organization", () => {+ expect(segmentBelongsToSite({ siteId: 1, organizationId: "org_1" }, 1, "org_1")).toBe(true);+ expect(segmentBelongsToSite({ siteId: null, organizationId: "org_1" }, 2, "org_1")).toBe(true);+ expect(segmentBelongsToSite({ siteId: 2, organizationId: "org_1" }, 1, "org_1")).toBe(false);+ expect(segmentBelongsToSite({ siteId: null, organizationId: "org_2" }, 1, "org_1")).toBe(false);+ });+});++describe("GET /segments", () => {+ it("hides private segments from a public-dashboard viewer and marks nothing editable", async () => {+ state.segments = [segmentRow({ isPublic: true }), segmentRow({ segmentId: 8, isPublic: false })];+ const reply = fakeReply();+ await getSegments(asViewer(), reply);+ expect(reply.statusCode).toBe(200);+ expect(reply.payload.map((s: any) => s.segmentId)).toEqual([7]);+ expect(reply.payload[0].canEdit).toBe(false);+ expect(reply.payload[0].userId).toBeNull();+ });++ it("shows a member every segment and flags only their own as editable", async () => {+ state.segments = [segmentRow({ userId: "member_1" }), segmentRow({ segmentId: 8, userId: "admin_1" })];+ const reply = fakeReply();+ await getSegments(asMember(), reply);+ expect(reply.payload.map((s: any) => [s.segmentId, s.canEdit])).toEqual([+ [7, true],+ [8, false],+ ]);+ });++ it("returns 404 for a site that does not exist", async () => {+ state.site = undefined;+ const reply = fakeReply();+ await getSegments(asMember(), reply);+ expect(reply.statusCode).toBe(404);+ });+});++describe("GET /segments/:id", () => {+ it("answers 404, not 403, when a viewer asks for a private segment", async () => {+ state.segments = [segmentRow({ isPublic: false })];+ const reply = fakeReply();+ await getSegment(asViewer(), reply);+ expect(reply.statusCode).toBe(404);+ });++ it("refuses a segment that belongs to another site", async () => {+ state.segments = [segmentRow({ siteId: 2 })];+ const reply = fakeReply();+ await getSegment(asAdmin(), reply);+ expect(reply.statusCode).toBe(404);+ });+});++describe("POST /segments", () => {+ it("lets a member create a site segment and records them as its owner", async () => {+ const request = asMember();+ request.body = { name: "Mobile", filters };+ const reply = fakeReply();+ await createSegment(request, reply);+ expect(reply.statusCode).toBe(201);+ expect(state.writes[0]).toMatchObject({+ op: "insert",+ values: { organizationId: "org_1", siteId: 1, userId: "member_1", isPublic: false },+ });+ expect(reply.payload.canEdit).toBe(true);+ });++ it("refuses org-wide scope from a member but accepts it from an admin", async () => {+ const memberRequest = asMember();+ memberRequest.body = { name: "Paid", filters, scope: "organization" };+ const memberReply = fakeReply();+ await createSegment(memberRequest, memberReply);+ expect(memberReply.statusCode).toBe(403);+ expect(state.writes).toHaveLength(0);++ const adminRequest = asAdmin();+ adminRequest.body = { name: "Paid", filters, scope: "organization" };+ const adminReply = fakeReply();+ await createSegment(adminRequest, adminReply);+ expect(adminReply.statusCode).toBe(201);+ expect(state.writes[0]).toMatchObject({ values: { siteId: null } });+ });++ it("rejects a body whose filters would not survive the query validator", async () => {+ const request = asAdmin();+ request.body = { name: "Bad", filters: [{ parameter: "session_id", type: "equals", value: ["x"] }] };+ const reply = fakeReply();+ await createSegment(request, reply);+ expect(reply.statusCode).toBe(400);+ expect(reply.payload.error).toBe("Validation error");+ expect(state.writes).toHaveLength(0);+ });++ it("refuses a viewer even if the route guard let them through", async () => {+ const request = asViewer();+ request.body = { name: "Mobile", filters };+ const reply = fakeReply();+ await createSegment(request, reply);+ expect(reply.statusCode).toBe(403);+ });+});++describe("PUT /segments/:id", () => {+ it("lets a member edit their own segment", async () => {+ state.segments = [segmentRow({ userId: "member_1" })];+ const request = asMember();+ request.body = { name: "Renamed" };+ const reply = fakeReply();+ await updateSegment(request, reply);+ expect(reply.statusCode).toBe(200);+ expect(state.writes[0]).toMatchObject({ op: "update", values: { name: "Renamed" } });+ });++ it("stops a member editing someone else's segment", async () => {+ state.segments = [segmentRow({ userId: "admin_1" })];+ const request = asMember();+ request.body = { name: "Renamed" };+ const reply = fakeReply();+ await updateSegment(request, reply);+ expect(reply.statusCode).toBe(403);+ expect(state.writes).toHaveLength(0);+ });++ it("lets an admin edit anyone's segment", async () => {+ state.segments = [segmentRow({ userId: "member_1" })];+ const request = asAdmin();+ request.body = { isPublic: true };+ const reply = fakeReply();+ await updateSegment(request, reply);+ expect(reply.statusCode).toBe(200);+ expect(state.writes[0]).toMatchObject({ values: { isPublic: true } });+ });++ it("only an admin can widen a site segment to the whole organization", async () => {+ state.segments = [segmentRow({ userId: "member_1", siteId: 1 })];+ const request = asMember();+ request.body = { scope: "organization" };+ const reply = fakeReply();+ await updateSegment(request, reply);+ expect(reply.statusCode).toBe(403);+ expect(state.writes).toHaveLength(0);+ });++ it("validates replacement filters against the filter schema", async () => {+ state.segments = [segmentRow()];+ const request = asAdmin();+ request.body = { filters: [{ parameter: "browser", type: "equals", value: [] }] };+ const reply = fakeReply();+ await updateSegment(request, reply);+ expect(reply.statusCode).toBe(400);+ });+});++describe("DELETE /segments/:id", () => {+ it("member deletes own, not others; admin deletes any; viewer sees 404", async () => {+ state.segments = [segmentRow({ userId: "member_1" })];+ let reply = fakeReply();+ await deleteSegment(asMember(), reply);+ expect(reply.statusCode).toBe(200);+ expect(state.writes.map(w => w.op)).toEqual(["delete"]);++ state.writes = [];+ state.segments = [segmentRow({ userId: "admin_1" })];+ reply = fakeReply();+ await deleteSegment(asMember(), reply);+ expect(reply.statusCode).toBe(403);+ expect(state.writes).toHaveLength(0);++ reply = fakeReply();+ await deleteSegment(asAdmin(), reply);+ expect(reply.statusCode).toBe(200);++ state.writes = [];+ state.segments = [segmentRow({ isPublic: true })];+ reply = fakeReply();+ await deleteSegment(asViewer(), reply);+ expect(reply.statusCode).toBe(403);+ expect(state.writes).toHaveLength(0);+ });+});diff --git a/server/src/api/analytics/segments/segmentAccess.ts b/server/src/api/analytics/segments/segmentAccess.tsnew file mode 100644index 000000000..b0884baaa--- /dev/null+++ b/server/src/api/analytics/segments/segmentAccess.ts@@ -0,0 +1,123 @@+import type { Segment } from "@rybbit/shared";+import { and, eq, isNull, or } from "drizzle-orm";+import { FastifyRequest } from "fastify";+import { db } from "../../../db/postgres/postgres.js";+import { segments, sites } from "../../../db/postgres/schema.js";+import { getOrgMembership, isOrgAdmin } from "../../../lib/access.js";+import { getIsUserAdmin, getUserHasAccessToSite } from "../../../lib/auth-utils.js";++export type SegmentRow = typeof segments.$inferSelect;++/**+ * Who is asking, reduced to the three facts the segment rules depend on.+ * Public-dashboard and private-link viewers have neither site access nor a+ * user id; they only ever see public segments.+ */+export interface SegmentActor {+ userId: string | null;+ /** Session member of the site's org, a user API key with site access, or the org's own key. */+ hasSiteAccess: boolean;+ /** Org admin/owner, system admin, or an organization-owned API key. */+ isAdmin: boolean;+}++export const NO_ACCESS_ACTOR: SegmentActor = { userId: null, hasSiteAccess: false, isAdmin: false };++export async function getSiteOrganizationId(siteId: number): Promise<string | null> {+ const site = await db.query.sites.findFirst({+ where: eq(sites.siteId, siteId),+ columns: { organizationId: true },+ });+ return site?.organizationId ?? null;+}++export async function resolveSegmentActor(+ request: FastifyRequest,+ siteId: number,+ organizationId: string+): Promise<SegmentActor> {+ // Organization-owned API keys carry org-admin authority over their own+ // organization's sites and nothing else (see getSitesUserHasAccessTo).+ if (!request.user?.id && request.apiKeyOrganizationId) {+ const ownsSite = request.apiKeyOrganizationId === organizationId;+ return { userId: null, hasSiteAccess: ownsSite, isAdmin: ownsSite };+ }++ const userId: string | null = request.user?.id ?? null;+ if (!userId) {+ return NO_ACCESS_ACTOR;+ }++ const [hasSiteAccess, membership, isSystemAdmin] = await Promise.all([+ getUserHasAccessToSite(request, siteId),+ getOrgMembership(userId, organizationId),+ getIsUserAdmin(request),+ ]);++ return { userId, hasSiteAccess, isAdmin: isSystemAdmin || isOrgAdmin(membership) };+}++/** Anyone with site access reads every segment; everyone else reads public ones. */+export function canReadSegment(segment: Pick<SegmentRow, "isPublic">, actor: SegmentActor): boolean {+ return actor.hasSiteAccess || segment.isPublic;+}++/** Admins and owners edit any segment; members edit the ones they created. */+export function canEditSegment(segment: Pick<SegmentRow, "userId">, actor: SegmentActor): boolean {+ if (actor.isAdmin) {+ return true;+ }+ return actor.hasSiteAccess && actor.userId !== null && segment.userId === actor.userId;+}++/** A segment applies to a site when it is that site's own or org-wide within the site's org. */+export function segmentBelongsToSite(+ segment: Pick<SegmentRow, "siteId" | "organizationId">,+ siteId: number,+ organizationId: string+): boolean {+ return segment.organizationId === organizationId && (segment.siteId === null || segment.siteId === siteId);+}++export const segmentsForSiteCondition = (siteId: number, organizationId: string) =>+ and(eq(segments.organizationId, organizationId), or(isNull(segments.siteId), eq(segments.siteId, siteId)));++export async function loadSegmentForSite(+ siteId: number,+ segmentId: number+): Promise<{ segment: SegmentRow; organizationId: string } | null> {+ const organizationId = await getSiteOrganizationId(siteId);+ if (!organizationId) {+ return null;+ }++ const segment = await db.query.segments.findFirst({ where: eq(segments.segmentId, segmentId) });+ if (!segment || !segmentBelongsToSite(segment, siteId, organizationId)) {+ return null;+ }++ return { segment, organizationId };+}++export function serializeSegment(row: SegmentRow, actor: SegmentActor): Segment {+ return {+ segmentId: row.segmentId,+ siteId: row.siteId,+ organizationId: row.organizationId,+ // The creator's account id is only meaningful to members of the site.+ userId: actor.hasSiteAccess ? row.userId : null,+ name: row.name,+ description: row.description,+ filters: row.filters,+ isPublic: row.isPublic,+ type: row.type,+ createdAt: row.createdAt ?? "",+ updatedAt: row.updatedAt ?? "",+ canEdit: canEditSegment(row, actor),+ };+}++export function parsePositiveId(raw: string): number | null {+ const id = parseInt(raw, 10);+ return Number.isNaN(id) || id <= 0 ? null : id;+}diff --git a/server/src/api/analytics/segments/segmentSchema.test.ts b/server/src/api/analytics/segments/segmentSchema.test.tsnew file mode 100644index 000000000..f74633105--- /dev/null+++ b/server/src/api/analytics/segments/segmentSchema.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from "vitest";+import { createSegmentSchema, segmentFiltersSchema, updateSegmentSchema } from "./segmentSchema.js";++const mobileDe = [+ { parameter: "device_type", type: "equals", value: ["Mobile"] },+ { parameter: "country", type: "equals", value: ["DE"] },+];++describe("segmentFiltersSchema", () => {+ it("accepts every filter shape the filter bar can produce", () => {+ const filters = [+ ...mobileDe,+ { parameter: "pathname", type: "starts_with", value: ["/docs"] },+ { parameter: "user_id", type: "is_not_null", value: [] },+ { parameter: "referrer", type: "regex", value: ["^https://(www\\.)?producthunt\\.com"] },+ { parameter: "lat", type: "greater_than", value: [48.1] },+ { parameter: "feature_flag:new-checkout", type: "equals", value: ["true"] },+ { parameter: "channel", type: "not_equals", value: ["Paid Search", "Paid Social"] },+ ];+ expect(segmentFiltersSchema.parse(filters)).toEqual(filters);+ });++ it("rejects a parameter the ClickHouse layer does not know", () => {+ const result = segmentFiltersSchema.safeParse([{ parameter: "session_id", type: "equals", value: ["x"] }]);+ expect(result.success).toBe(false);+ });++ it("rejects an unknown operator", () => {+ const result = segmentFiltersSchema.safeParse([{ parameter: "browser", type: "like", value: ["Chrome"] }]);+ expect(result.success).toBe(false);+ });++ it("rejects a value-taking operator with no values", () => {+ const result = segmentFiltersSchema.safeParse([{ parameter: "browser", type: "equals", value: [] }]);+ expect(result.success).toBe(false);+ expect(result.success ? "" : result.error.issues[0].message).toContain("at least one value");+ });++ it("allows null checks with no values", () => {+ const result = segmentFiltersSchema.safeParse([{ parameter: "user_id", type: "is_null", value: [] }]);+ expect(result.success).toBe(true);+ });++ it("rejects an invalid regular expression", () => {+ const result = segmentFiltersSchema.safeParse([{ parameter: "pathname", type: "regex", value: ["(unclosed"] }]);+ expect(result.success).toBe(false);+ expect(result.success ? "" : result.error.issues[0].message).toContain("Invalid regular expression");+ });++ it("holds stored regexes to the query path's limits: non-empty, at most 500 chars, RE2-compatible, one pattern", () => {+ const regex = (value: unknown[]) => segmentFiltersSchema.safeParse([{ parameter: "pathname", type: "regex", value }]);+ expect(regex([""]).success).toBe(false);+ expect(regex(["a".repeat(501)]).success).toBe(false);+ expect(regex(["^(?!.*test).*$"]).success).toBe(false);+ expect(regex(["^/docs/(?=guide)"]).success).toBe(false);+ expect(regex(["(a)\\1"]).success).toBe(false);+ expect(regex(["^/a", "^/b"]).success).toBe(false);+ expect(regex(["^/docs/[a-z-]+$"]).success).toBe(true);+ });++ it("rejects non-numeric values on numeric comparisons and coordinates", () => {+ expect(segmentFiltersSchema.safeParse([{ parameter: "lat", type: "equals", value: ["north"] }]).success).toBe(false);+ expect(+ segmentFiltersSchema.safeParse([{ parameter: "browser_version", type: "greater_than", value: ["latest"] }]).success+ ).toBe(false);+ });++ it("rejects values that are neither strings nor numbers", () => {+ const result = segmentFiltersSchema.safeParse([{ parameter: "browser", type: "equals", value: [{ name: "Chrome" }] }]);+ expect(result.success).toBe(false);+ });++ it("bounds the values a single filter may carry", () => {+ const many = Array.from({ length: 51 }, (_, i) => `v${i}`);+ expect(segmentFiltersSchema.safeParse([{ parameter: "country", type: "equals", value: many }]).success).toBe(false);+ expect(+ segmentFiltersSchema.safeParse([{ parameter: "pathname", type: "contains", value: ["x".repeat(501)] }]).success+ ).toBe(false);+ expect(+ segmentFiltersSchema.safeParse([{ parameter: "country", type: "equals", value: many.slice(0, 50) }]).success+ ).toBe(true);+ });++ it("requires at least one filter and caps the count", () => {+ expect(segmentFiltersSchema.safeParse([]).success).toBe(false);+ const tooMany = Array.from({ length: 21 }, (_, i) => ({ parameter: "browser", type: "equals", value: [`b${i}`] }));+ expect(segmentFiltersSchema.safeParse(tooMany).success).toBe(false);+ });+});++describe("createSegmentSchema", () => {+ it("trims the name and defaults the optional fields", () => {+ const parsed = createSegmentSchema.parse({ name: " Mobile DE ", filters: mobileDe });+ expect(parsed.name).toBe("Mobile DE");+ expect(parsed.isPublic).toBeUndefined();+ expect(parsed.scope).toBeUndefined();+ });++ it("rejects a blank name, an unknown scope, and unknown keys", () => {+ expect(createSegmentSchema.safeParse({ name: " ", filters: mobileDe }).success).toBe(false);+ expect(createSegmentSchema.safeParse({ name: "x", filters: mobileDe, scope: "team" }).success).toBe(false);+ expect(createSegmentSchema.safeParse({ name: "x", filters: mobileDe, siteId: 4 }).success).toBe(false);+ });++ it("caps name and description length", () => {+ expect(createSegmentSchema.safeParse({ name: "n".repeat(81), filters: mobileDe }).success).toBe(false);+ expect(+ createSegmentSchema.safeParse({ name: "ok", description: "d".repeat(501), filters: mobileDe }).success+ ).toBe(false);+ });+});++describe("updateSegmentSchema", () => {+ it("accepts a partial body but still validates the filters it carries", () => {+ expect(updateSegmentSchema.safeParse({ name: "Renamed" }).success).toBe(true);+ expect(updateSegmentSchema.safeParse({ isPublic: true }).success).toBe(true);+ expect(updateSegmentSchema.safeParse({ filters: [] }).success).toBe(false);+ expect(+ updateSegmentSchema.safeParse({ filters: [{ parameter: "nope", type: "equals", value: ["x"] }] }).success+ ).toBe(false);+ });+});diff --git a/server/src/api/analytics/segments/segmentSchema.ts b/server/src/api/analytics/segments/segmentSchema.tsnew file mode 100644index 000000000..0f4e6df62--- /dev/null+++ b/server/src/api/analytics/segments/segmentSchema.ts@@ -0,0 +1,97 @@+import { SEGMENT_DESCRIPTION_MAX_LENGTH, SEGMENT_MAX_FILTERS, SEGMENT_NAME_MAX_LENGTH } from "@rybbit/shared";+import { z } from "zod";+import { validateRegexPattern } from "../utils/getFilterStatement.js";+import { filterSchema } from "../utils/query-validation.js";++const NO_VALUE_TYPES = new Set(["is_null", "is_not_null"]);+// A public segment is expanded by anyone who knows its id, so its size is+// bounded here rather than left to whoever saved it.+export const SEGMENT_MAX_VALUES_PER_FILTER = 50;+export const SEGMENT_MAX_VALUE_LENGTH = 500;+const REGEX_TYPES = new Set(["regex", "not_regex"]);+const NUMERIC_TYPES = new Set(["greater_than", "less_than", "greater_than_or_equal", "less_than_or_equal"]);++// A stored segment feeds getFilterStatement on every request that applies it,+// so the same schema that guards the `filters` query param guards the row.+// Shapes the query path merely tolerates (an empty value list, an invalid+// regex, a non-numeric comparison) are rejected here so a saved segment can+// never carry a filter the filter bar itself would refuse.+export const segmentFilterSchema = filterSchema.superRefine((filter, ctx) => {+ if (NO_VALUE_TYPES.has(filter.type)) {+ return;+ }++ if (filter.value.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Filter on "${filter.parameter}" needs at least one value`,+ path: ["value"],+ });+ return;+ }++ if (filter.value.length > SEGMENT_MAX_VALUES_PER_FILTER) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `A filter can have at most ${SEGMENT_MAX_VALUES_PER_FILTER} values`,+ path: ["value"],+ });+ return;+ }+ if (filter.value.some(value => String(value).length > SEGMENT_MAX_VALUE_LENGTH)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Filter values are limited to ${SEGMENT_MAX_VALUE_LENGTH} characters`,+ path: ["value"],+ });+ return;+ }++ if (REGEX_TYPES.has(filter.type)) {+ // The query path only ever runs the first value of a regex filter, so a+ // stored regex filter carries exactly one pattern.+ if (filter.value.length !== 1) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "A regex filter takes exactly one pattern", path: ["value"] });+ }+ for (const value of filter.value) {+ const error = validateRegexPattern(String(value));+ if (error) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: error, path: ["value"] });+ }+ }+ }++ if (NUMERIC_TYPES.has(filter.type) || filter.parameter === "lat" || filter.parameter === "lon") {+ for (const value of filter.value) {+ if (!Number.isFinite(Number(value))) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Filter on "${filter.parameter}" needs numeric values`,+ path: ["value"],+ });+ }+ }+ }+});++export const segmentFiltersSchema = z+ .array(segmentFilterSchema)+ .min(1, "A segment needs at least one filter")+ .max(SEGMENT_MAX_FILTERS, `A segment can have at most ${SEGMENT_MAX_FILTERS} filters`);++export const segmentScopeSchema = z.enum(["site", "organization"]);++export const createSegmentSchema = z+ .object({+ name: z.string().trim().min(1, "Segment name is required").max(SEGMENT_NAME_MAX_LENGTH),+ description: z.string().trim().max(SEGMENT_DESCRIPTION_MAX_LENGTH).nullable().optional(),+ filters: segmentFiltersSchema,+ isPublic: z.boolean().optional(),+ scope: segmentScopeSchema.optional(),+ })+ .strict();++export const updateSegmentSchema = createSegmentSchema.partial().strict();++export type CreateSegmentBody = z.infer<typeof createSegmentSchema>;+export type UpdateSegmentBody = z.infer<typeof updateSegmentSchema>;diff --git a/server/src/api/analytics/segments/updateSegment.ts b/server/src/api/analytics/segments/updateSegment.tsnew file mode 100644index 000000000..8e10c0066--- /dev/null+++ b/server/src/api/analytics/segments/updateSegment.ts@@ -0,0 +1,75 @@+import { eq } from "drizzle-orm";+import { FastifyReply, FastifyRequest } from "fastify";+import { z } from "zod";+import { db } from "../../../db/postgres/postgres.js";+import { segments } from "../../../db/postgres/schema.js";+import {+ canEditSegment,+ canReadSegment,+ loadSegmentForSite,+ parsePositiveId,+ resolveSegmentActor,+ serializeSegment,+} from "./segmentAccess.js";+import { updateSegmentSchema } from "./segmentSchema.js";++export async function updateSegment(+ request: FastifyRequest<{ Params: { siteId: string; segmentId: string }; Body: unknown }>,+ reply: FastifyReply+) {+ const siteId = parsePositiveId(request.params.siteId);+ const segmentId = parsePositiveId(request.params.segmentId);+ if (!siteId) {+ return reply.status(400).send({ error: "Invalid site ID" });+ }+ if (!segmentId) {+ return reply.status(400).send({ error: "Invalid segment ID" });+ }++ try {+ const body = updateSegmentSchema.parse(request.body);++ const loaded = await loadSegmentForSite(siteId, segmentId);+ if (!loaded) {+ return reply.status(404).send({ error: "Segment not found" });+ }++ const actor = await resolveSegmentActor(request, siteId, loaded.organizationId);+ if (!canReadSegment(loaded.segment, actor)) {+ return reply.status(404).send({ error: "Segment not found" });+ }+ if (!canEditSegment(loaded.segment, actor)) {+ return reply.status(403).send({ error: "You can only edit segments you created" });+ }++ const becomesOrgWide = body.scope === "organization" && loaded.segment.siteId !== null;+ if (becomesOrgWide && !actor.isAdmin) {+ return reply.status(403).send({ error: "Only organization admins can share a segment with every site" });+ }++ const [row] = await db+ .update(segments)+ .set({+ ...(body.name !== undefined ? { name: body.name } : {}),+ ...(body.description !== undefined ? { description: body.description } : {}),+ ...(body.filters !== undefined ? { filters: body.filters } : {}),+ ...(body.isPublic !== undefined ? { isPublic: body.isPublic } : {}),+ ...(body.scope !== undefined ? { siteId: body.scope === "organization" ? null : siteId } : {}),+ updatedAt: new Date().toISOString(),+ })+ .where(eq(segments.segmentId, segmentId))+ .returning();++ if (!row) {+ return reply.status(500).send({ error: "Failed to update segment" });+ }++ return reply.send(serializeSegment(row, actor));+ } catch (error) {+ if (error instanceof z.ZodError) {+ return reply.status(400).send({ error: "Validation error", details: error.errors });+ }+ request.log.error({ err: error }, "Error updating segment");+ return reply.status(500).send({ error: "Failed to update segment" });+ }+}diff --git a/server/src/api/analytics/utils/getFilterStatement.ts b/server/src/api/analytics/utils/getFilterStatement.tsindex b301e27b1..776b16666 100644--- a/server/src/api/analytics/utils/getFilterStatement.ts+++ b/server/src/api/analytics/utils/getFilterStatement.ts@@ -66,6 +66,36 @@ const filterTypeToOperator = (type: FilterType) => {// value remain functional.const escapeLikePattern = (value: string): string => value.replace(/[\\%_]/g, "\\$&");+export const MAX_REGEX_PATTERN_LENGTH = 500;++// RE2 (what ClickHouse's match() runs) has no lookaround or backreferences;+// JavaScript accepts them, so a JS-only check would let a pattern through+// that fails at query time.+const RE2_UNSUPPORTED = /\(\?<?[=!]|\\[1-9]/;++/**+ * Why a regex filter pattern cannot run, or null when it can. Shared by the+ * query path and by stored segments so a saved pattern is held to exactly the+ * constraints it will be executed under.+ */+export function validateRegexPattern(pattern: string): string | null {+ if (!pattern) {+ return "Regex pattern cannot be empty";+ }+ if (pattern.length > MAX_REGEX_PATTERN_LENGTH) {+ return `Regex pattern too long (max ${MAX_REGEX_PATTERN_LENGTH} characters)`;+ }+ try {+ new RegExp(pattern);+ } catch (e) {+ return `Invalid regex pattern: ${e instanceof Error ? e.message : "Unknown error"}`;+ }+ if (RE2_UNSUPPORTED.test(pattern)) {+ return "Regex pattern uses lookaround or backreferences, which are not supported";+ }+ return null;+}+export const wrapLikeValue = (type: FilterType, value: string | number): string => {const v = String(value);if (type === "contains" || type === "not_contains") return `%${escapeLikePattern(v)}%`;@@ -94,18 +124,9 @@ export const buildStringFilterCondition = (if (filterType === "regex" || filterType === "not_regex") {const pattern = String(values[0] ?? "");- if (!pattern) {- throw new Error("Regex pattern cannot be empty");- }-- try {- new RegExp(pattern);- } catch (e) {- throw new Error(`Invalid regex pattern: ${e instanceof Error ? e.message : "Unknown error"}`);- }-- if (pattern.length > 500) {- throw new Error("Regex pattern too long (max 500 characters)");+ const regexError = validateRegexPattern(pattern);+ if (regexError) {+ throw new Error(regexError);}const matchExpr = `match(${expression}, ${SqlString.escape(pattern)})`;diff --git a/server/src/api/analytics/utils/query-validation.ts b/server/src/api/analytics/utils/query-validation.tsindex 14c02e192..92728e747 100644--- a/server/src/api/analytics/utils/query-validation.ts+++ b/server/src/api/analytics/utils/query-validation.ts@@ -69,7 +69,7 @@ export const filterParamSchema: z.ZodType<FilterParameter> = z.union([/*** Schema for filter objects*/-const filterSchema = z.object({+export const filterSchema = z.object({parameter: filterParamSchema,type: filterTypeSchema,value: z.array(z.string().or(z.number())),diff --git a/server/src/api/sites/applySiteMove.ts b/server/src/api/sites/applySiteMove.tsindex d263ae306..fbc7cb417 100644--- a/server/src/api/sites/applySiteMove.ts+++ b/server/src/api/sites/applySiteMove.ts@@ -1,6 +1,6 @@import { eq } from "drizzle-orm";import { db } from "../../db/postgres/postgres.js";-import { memberSiteAccess, sites, teamSiteAccess } from "../../db/postgres/schema.js";+import { memberSiteAccess, segments, sites, teamSiteAccess } from "../../db/postgres/schema.js";import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";/**@@ -24,6 +24,11 @@ export async function applySiteMove(.where(eq(sites.siteId, siteId));await tx.delete(memberSiteAccess).where(eq(memberSiteAccess.siteId, siteId));await tx.delete(teamSiteAccess).where(eq(teamSiteAccess.siteId, siteId));+ // Site-specific segments travel with the site; they are looked up by+ // (organization, site), so leaving the old organization on them would+ // hide them from the moved site and let the old org's deletion cascade+ // over them. Org-wide segments (null site_id) stay with their org.+ await tx.update(segments).set({ organizationId: targetOrganizationId }).where(eq(segments.siteId, siteId));});const orgIds = sourceOrganizationId ? [sourceOrganizationId, targetOrganizationId] : [targetOrganizationId];diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 6cf906d59..a81678a20 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -1,5 +1,5 @@import { sql } from "drizzle-orm";-import type { DashboardConfig } from "@rybbit/shared";+import type { DashboardConfig, Filter, SegmentType } from "@rybbit/shared";import {boolean,check,@@ -142,6 +142,32 @@ export const dashboards = pgTable("dashboards", {updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),});+// Saved segments: a named, reusable set of analytics filters. A segment is+// scoped to one site or, with a null site_id, to every site in its+// organization. `type` is reserved so cohorts can share the table later.+export const segments = pgTable(+ "segments",+ {+ segmentId: serial("segment_id").primaryKey().notNull(),+ organizationId: text("organization_id")+ .notNull()+ .references(() => organization.id, { onDelete: "cascade" }),+ siteId: integer("site_id").references(() => sites.siteId, { onDelete: "cascade" }),+ userId: text("user_id").references(() => user.id, { onDelete: "set null" }),+ name: text("name").notNull(),+ description: text("description"),+ filters: jsonb("filters").notNull().$type<Filter[]>().default([]),+ isPublic: boolean("is_public").default(false).notNull(),+ type: text("type").notNull().default("segment").$type<SegmentType>(),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ },+ table => [+ index("segments_organization_idx").on(table.organizationId),+ index("segments_site_idx").on(table.siteId),+ ]+);+// Account table (BetterAuth)export const account = pgTable("account", {id: text().primaryKey().notNull(),diff --git a/server/src/index.ts b/server/src/index.tsindex 288a0fbf9..ae15f67f6 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -23,15 +23,19 @@ import {} from "./api/admin/index.js";import {createDashboard,+ createSegment,createFunnel,createGoal,deleteDashboard,+ deleteSegment,deleteFunnel,deleteGoal,deleteUser,generatePdfReport,getDashboard,getDashboards,+ getSegment,+ getSegments,getBotAiSummary,getBotDimension,getBotOverview,@@ -81,6 +85,8 @@ import {runCustomQuery,runDashboardCardQuery,updateDashboard,+ updateSegment,+ expandSegmentParam,updateGoal,updateUserTraits,} from "./api/analytics/index.js";@@ -183,6 +189,7 @@ import {import { mapHeaders } from "./lib/auth-utils.js";import { registerApiErrorResponses } from "./lib/api-errors.js";import type { ScopeAction, ScopeResource } from "./lib/scopes.js";+import type { ScopeStatements } from "@rybbit/shared";import { auth } from "./lib/auth.js";import { mcpRoutes } from "./mcp/index.js";import { oauthWellKnownRoutes } from "./mcp/wellKnown.js";@@ -221,11 +228,19 @@ const validateTimeParams = async (request: FastifyRequest, reply: FastifyReply)// host a time-taking route: absent params always pass, and the two chains that// went without it were how /org-event-count and /admin/service-event-count came// to answer a malformed date with all-time data and a 200.+// expandSegmentParam turns a `segment_id` query param into `filters` after the+// access guard has run, so every analytics endpoint accepts a saved segment+// with no per-endpoint change. It is a no-op when the param is absent.const publicSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({- preHandler: [resolveSiteId, allowPublicSiteAccess({ resource, action }), validateTimeParams] as any,+ preHandler: [+ resolveSiteId,+ allowPublicSiteAccess({ resource, action }),+ validateTimeParams,+ expandSegmentParam,+ ] as any,});const authSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({- preHandler: [resolveSiteId, requireSiteAccess({ resource, action }), validateTimeParams] as any,+ preHandler: [resolveSiteId, requireSiteAccess({ resource, action }), validateTimeParams, expandSegmentParam] as any,});const adminSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({preHandler: [resolveSiteId, requireSiteAdminAccess({ resource, action }), validateTimeParams] as any,@@ -259,6 +274,8 @@ const authOrgRead = authOnlyScoped("org", "read");const adminSitesRead = adminSiteScoped("sites", "read");const authDashboardsRead = authSiteScoped("dashboards", "read");const authDashboardsWrite = authSiteScoped("dashboards", "write");+const publicSegmentsRead = publicSiteScoped("segments", "read");+const authSegmentsWrite = authSiteScoped("segments", "write");const authFlagsRead = authSiteScoped("flags", "read");const authExperimentsRead = authSiteScoped("experiments", "read");const authSitesRead = authSiteScoped("sites", "read");@@ -438,6 +455,14 @@ async function analyticsRoutes(fastify: FastifyInstance) {fastify.post("/sites/:siteId/dashboards", authDashboardsWrite, createDashboard);fastify.put("/sites/:siteId/dashboards/:dashboardId", authDashboardsWrite, updateDashboard);fastify.delete("/sites/:siteId/dashboards/:dashboardId", authDashboardsWrite, deleteDashboard);++ // Saved segments. Reads allow public/private-link viewers (they only see+ // public segments); writes need site access and are further gated per row.+ fastify.get("/sites/:siteId/segments", publicSegmentsRead, getSegments);+ fastify.get("/sites/:siteId/segments/:segmentId", publicSegmentsRead, getSegment);+ fastify.post("/sites/:siteId/segments", authSegmentsWrite, createSegment);+ fastify.put("/sites/:siteId/segments/:segmentId", authSegmentsWrite, updateSegment);+ fastify.delete("/sites/:siteId/segments/:segmentId", authSegmentsWrite, deleteSegment);fastify.post("/sites/:siteId/dashboards/run-card",withRateLimit(authDashboardsRead, customQueryRateLimit),@@ -713,5 +738,9 @@ declare module "fastify" {user?: any; // Or define a more specific user type/** Set by the auth guards when the bearer credential is an org-owned API key. */apiKeyOrganizationId?: string;+ /** True when the request was authenticated with a bearer credential (API key or OAuth token). */+ bearerAuth?: boolean;+ /** Scope statements of that credential; null = unrestricted. */+ bearerStatements?: ScopeStatements | null;}}diff --git a/server/src/lib/auth-middleware.ts b/server/src/lib/auth-middleware.tsindex 55ac1aa5c..71479121e 100644--- a/server/src/lib/auth-middleware.ts+++ b/server/src/lib/auth-middleware.ts@@ -113,6 +113,10 @@ const sendRateLimited = (reply: FastifyReply, apiKeyResult: BearerAuthResult) =>// resolver (getSitesUserHasAccessTo) maps to the org's full site set.const attachApiKeyUser = (request: FastifyRequest, reply: FastifyReply, apiKeyResult: BearerAuthResult) => {applyRateLimitHeaders(reply, apiKeyResult);+ // Later handlers (e.g. expandSegmentParam) may need to check a scope the+ // route itself does not require, without re-verifying the credential.+ request.bearerAuth = true;+ request.bearerStatements = apiKeyResult.statements;if (apiKeyResult.userId) {request.user = { id: apiKeyResult.userId };} else if (apiKeyResult.organizationId) {diff --git a/server/src/mcp/mcp.test.ts b/server/src/mcp/mcp.test.tsindex 346b9965d..77c2cc3aa 100644--- a/server/src/mcp/mcp.test.ts+++ b/server/src/mcp/mcp.test.ts@@ -325,7 +325,7 @@ describe("mcp endpoint", () => {const tools = await listTools(app);const names = tools.map(tool => tool.name);- expect(tools).toHaveLength(39);+ expect(tools).toHaveLength(41);expect(names).toContain("list_sites");expect(names).toContain("get_overview");expect(names).toContain("get_breakdown");@@ -363,7 +363,7 @@ describe("mcp endpoint", () => {it("legacy OAuth grants with only standard scopes stay unrestricted", async () => {const tools = await listTools(app, "Bearer oauth_valid_token");- expect(tools).toHaveLength(39);+ expect(tools).toHaveLength(41);});it("partitions tools into reads, writes, and destructive deletes", async () => {diff --git a/server/src/mcp/tools/index.ts b/server/src/mcp/tools/index.tsindex 879ca9fc5..81998c956 100644--- a/server/src/mcp/tools/index.ts+++ b/server/src/mcp/tools/index.ts@@ -5,6 +5,7 @@ import { registerFunnelTools } from "./funnels.js";import { registerGoalTools } from "./goals.js";import { registerOrganizationTools } from "./organizations.js";import { registerRawDataTools } from "./rawData.js";+import { registerSegmentTools } from "./segments.js";import { createGuard, createScopeCheck, type ToolRegistrationConfig } from "./shared.js";import { registerSiteTools } from "./sites.js";import { registerUserTools } from "./users.js";@@ -18,6 +19,7 @@ export function registerTools(server: McpServer, api: RybbitApiClient, config: TregisterAnalyticsTools(server, api, guard, allowed);registerGoalTools(server, api, guard, allowed);registerFunnelTools(server, api, guard, allowed);+ registerSegmentTools(server, api, guard, allowed);registerUserTools(server, api, guard, allowed);registerOrganizationTools(server, api, guard, allowed);registerRawDataTools(server, api, guard, allowed);diff --git a/server/src/mcp/tools/segments.ts b/server/src/mcp/tools/segments.tsnew file mode 100644index 000000000..6272ad519--- /dev/null+++ b/server/src/mcp/tools/segments.ts@@ -0,0 +1,61 @@+import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { z } from "zod";+import { RybbitApiClient } from "../apiClient.js";+import { siteIdInput, timeInputs } from "../inputs.js";+import { looseRow, looseRows, ok, readOnly, siteQuery, type ScopeCheck, type ToolGuard } from "./shared.js";++const segmentIdInput = z.number().int().positive().describe("Segment ID from list_segments");++const segmentOutput = z+ .object({+ segmentId: z.number(),+ siteId: z.number().nullable(),+ name: z.string(),+ description: z.string().nullable(),+ filters: looseRows,+ isPublic: z.boolean(),+ })+ .partial()+ .passthrough();++export function registerSegmentTools(+ server: McpServer,+ api: RybbitApiClient,+ guard: ToolGuard,+ allowed: ScopeCheck+): void {+ if (allowed("segments", "read"))+ server.registerTool(+ "list_segments",+ {+ title: "Saved segments",+ description:+ "Saved segments for a site: named, reusable sets of analytics filters (for example \"Mobile organic from Germany\"). A segment with a null siteId is shared by every site in the organization. Apply one with apply_segment, or pass its filters to any analytics tool.",+ inputSchema: { site_id: siteIdInput },+ outputSchema: z.object({ data: z.array(segmentOutput) }),+ annotations: readOnly,+ },+ guard(async ({ site_id }) => ok({ data: await api.call("GET", `/sites/${site_id}/segments`) }))+ );++ if (allowed("segments", "read") && allowed("analytics", "read"))+ server.registerTool(+ "apply_segment",+ {+ title: "Overview for a segment",+ description:+ "Sessions, pageviews, users, bounce rate, and session duration over the time range for visitors matching a saved segment. Returns the segment's filters alongside the metrics so follow-up breakdowns can reuse them.",+ inputSchema: { site_id: siteIdInput, segment_id: segmentIdInput, ...timeInputs },+ outputSchema: z.object({ segment: segmentOutput, data: looseRow.optional() }).passthrough(),+ annotations: readOnly,+ },+ guard(async ({ site_id, segment_id, ...rest }) => {+ const [segment, overview] = await Promise.all([+ api.call("GET", `/sites/${site_id}/segments/${segment_id}`),+ api.call("GET", `/sites/${site_id}/overview`, { query: { ...siteQuery(rest), segment_id } }),+ ]);+ const data = (overview as { data?: unknown } | null)?.data;+ return ok({ segment, data });+ })+ );+}diff --git a/shared/src/index.ts b/shared/src/index.tsindex f90923a89..698b5ec59 100644--- a/shared/src/index.ts+++ b/shared/src/index.ts@@ -3,6 +3,7 @@ export * from "./dashboards";export * from "./filters";export * from "./params";export * from "./scopes";+export * from "./segments";export * from "./time";export * from "./performance";export * from "./aiOperators";diff --git a/shared/src/scopes.ts b/shared/src/scopes.tsindex 1403ad7fc..e53f88cbf 100644--- a/shared/src/scopes.ts+++ b/shared/src/scopes.ts@@ -16,6 +16,7 @@ export const SCOPE_MATRIX = {goals: ["read", "write"],funnels: ["read", "write"],dashboards: ["read", "write"],+ segments: ["read", "write"],flags: ["read", "write"],experiments: ["read", "write"],sites: ["read", "write"],diff --git a/shared/src/segments.ts b/shared/src/segments.tsnew file mode 100644index 000000000..615d1ef32--- /dev/null+++ b/shared/src/segments.ts@@ -0,0 +1,32 @@+import type { Filter } from "./filters";++/**+ * A saved, named set of filters. `type` is reserved so cohorts (groups fixed+ * by a date or event) can share the table later without a migration.+ */+export type SegmentType = "segment";++export interface Segment {+ segmentId: number;+ /** Null for organization-wide segments, which apply to every site in the org. */+ siteId: number | null;+ organizationId: string;+ /** Creator; null once that account is deleted. */+ userId: string | null;+ name: string;+ description: string | null;+ filters: Filter[];+ /** Visible to public-dashboard and private-link viewers. */+ isPublic: boolean;+ type: SegmentType;+ createdAt: string;+ updatedAt: string;+ /** Whether the caller may edit or delete this segment; computed per request. */+ canEdit: boolean;+}++export type SegmentScope = "site" | "organization";++export const SEGMENT_NAME_MAX_LENGTH = 80;+export const SEGMENT_DESCRIPTION_MAX_LENGTH = 500;+export const SEGMENT_MAX_FILTERS = 20;