domma-cms 1.58.0 → 1.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/admin/js/app.js +2 -2
- package/admin/js/lib/chat-toast.js +2 -0
- package/admin/js/lib/notifications-arrange.js +1 -1
- package/admin/js/templates/docs/usage-chat.html +8 -2
- package/admin/js/views/notifications.js +10 -4
- package/docs/DommaFeatures.md +1 -1
- package/package.json +1 -1
- package/server/routes/api/contacts.js +67 -12
- package/server/services/chat/ai.js +16 -5
- package/server/services/chat/conversation.js +40 -2
- package/server/services/permissionRegistry.js +11 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.59.0] - 2026-11-11
|
|
4
|
+
|
|
5
|
+
- **Contacts: own address book only.** A new permission, `contacts-restricted`, is for outside accounts such as a Job Board's candidates and companies. A role holding it uses Contacts for its own contacts and only the groups it made: it does not see anyone else's group names, cannot file a contact in someone else's group, and someone else's group is "not found" to it. Contacts Pro reads it too: no list of people, no sharing, no changes to the shared custom fields. It changes nothing for a person who also holds a role that gives Contacts without it, or for the top role.
|
|
6
|
+
- **Chat notifications.** Admins get a notification when a visitor starts a chat (with their first message and the page), and when the AI turns a visitor's question down: off-topic, or something the launcher's rules forbid. Each is its own source in Notifications settings (Visitor chat started, Chat question turned down), so either can be switched off or sent to other people. Turned-down questions need the Manager's launcher-chat update. While the admin is open these, and a visitor asking for a person or leaving a message, also pop up as messages with an **Open Chats** button (within 30 seconds; **Chat pop-ups** in the Notifications settings cog turns them off for a browser).
|
|
7
|
+
|
|
3
8
|
## [1.58.0] - 2026-11-11
|
|
4
9
|
|
|
5
10
|
- **AI Assist.** AI chat answers (chat launchers, admin launchers and the admin assistant) now come with the AI Assist Tool, in the Pro plan, instead of riding on the Site Builder. A Tool switches them on with `hooks.enableAiAssist()` (paid, closed-source plugins only). Without AI Assist, chats answer from the Knowledge alone and the launcher editor says so under **AI answers**.
|
package/admin/js/app.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wireNotificationMenu as tt}from"./lib/topbar-notifications.js";import{installSmoothCarets as et}from"./lib/smooth-caret.js";import{viewLoaders as at}from"./views/index.js";import{createLazyViews as it}from"./lib/lazy-views.js";import{withPluginChrome as K}from"./lib/plugin-chrome.js";import{api as r,getUser as O,isAuthenticated as p,logout as ot,sendToLogin as st}from"./api.js";import{claimDrafts as nt}from"./lib/draft-owner.js";import{isAuthScreen as y,loginHashFor as rt}from"./lib/login-arrange.js";import{installHttpInterceptor as lt}from"./http-interceptor.js";import{installResizableSlideovers as ct}from"./lib/slideover-resizable.js";import{installActivityThrobber as mt}from"./lib/activity-throbber.js";import{installUpdateNotice as pt,renderCmsVersion as dt}from"./lib/update-notice.js";import{renderFrameworkVersions as q,wireAccountMenu as ut}from"./lib/topbar-account.js";import{refreshTopbarProject as V}from"./lib/topbar-project.js";import{CONFINED_CLASS as ht,isConfined as wt,isPathAllowed as gt,redirectFor as ft}from"./lib/admin-scope.js";import{deliverDesktop as vt,desktopActive as bt,notificationSettings as St}from"./lib/desktop-notify.js";import{avatarUrl as Ct,installAccountAvatar as Mt}from"./lib/avatar.js";import{installCalculator as Dt}from"./lib/calculator.js";import{installAdminAssistant as yt}from"./lib/admin-assistant.js";import{installAdminLaunchers as Et}from"./lib/admin-launchers.js";import{takeOverviewPass as Nt,withDashboardStrip as z}from"./lib/dashboards-strip.js";import{installHotkeys as Pt}from"./lib/hotkeys-ui.js";import{applyAdminBrand as G}from"./lib/admin-brand.js";import{installRouterCatchUp as At}from"./lib/router-catch-up.js";import{installSidebarDrawer as jt}from"./lib/sidebar-drawer.js";$(()=>{et(document),lt(),Dt(),yt(),Et(),pt(),mt(),ct(),jt(),(async()=>{const{applyAdminTheme:t,refreshAdminTheme:i}=await import("./lib/admin-theme.js");p()?await i(r,{init:!0}):t({dommaTheme:"charcoal-dark"},{init:!0})})();let c=null,f=null,m="/",v=!1,w=null,d=null,u=!0;function N(t){if(j[t])return E.toast(`${j[t]} is switched off on this site.`,{type:"info"}),"/";const[i,e]=t.split("?"),a=new URLSearchParams(e||"").get("tab");if(i==="/settings"&&["favicon","pageNavigation","breadcrumbs","motion","search"].includes(a))return`/appearance?tab=${a}`;if(t.split("?")[0]==="/my-dashboard")return"/dashboards";const o=A[t]||ft(c,t);return o||(!u&&i==="/system/notifications"?c?.home||"/":(t.split("?")[0]||"/")==="/"&&m&&m!=="/"&&!Nt()?A[m]||m:null)}function P(){document.body.classList.toggle(ht,wt(c))}const A={},j={};R.use(async(t,i,e)=>{if(y(t.path))return e();if(!p()){st();return}const a=N(t.path);if(a){R.navigate(a);return}e()});async function b(){try{const t=await r.get("/auth/permissions");c=t.adminScope||null,P(),f=t.adminBrand||null,G(f),m=t.adminHome||"/",q(t.versions||{});const i=t.permissions||[];return v=gt(c,"/settings")&&i.some(e=>e==="settings"||e.startsWith("settings.")),w=i.some(e=>e==="notifications"||e.startsWith("notifications.")),d=t.adminPortal||null,u=t.notificationsScreen!==!1,i}catch{return c=null,P(),m="/",f||G(null),v=!1,w=null,d=null,u=!0,[]}}document.addEventListener("dm:admin-home-changed",()=>{b()});let k=null,I=!1;document.addEventListener("dm:sidebar-rebuild",()=>{if(V(r),k){I=!0;return}k=(async()=>{do{I=!1;try{await T(await b())}catch{}}while(I)})().finally(()=>{k=null})});async function T(t){const{applyAdminPortal:i}=await import("./lib/admin-portal.js");if(await i(d),d)return;const{renderAdminSidebar:e}=await import("./lib/sidebar-renderer.js");await e({mount:"#admin-sidebar",permissions:t,adminScope:c,brand:f,notificationsScreen:u})}M.subscribe("router:afterChange",({to:t})=>{y(t.path)&&(g&&(clearInterval(g),g=null),c=null,P(),m="/",v=!1,w=null,u=!0,d&&(d=null,import("./lib/admin-portal.js").then(i=>i.applyAdminPortal(null))))});const J=[{path:"/",view:"dashboard",title:"Dashboard - Domma CMS"},{path:"/dashboards",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/my-dashboard",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/pages",view:"pages",title:"Pages - Domma CMS"},{path:"/pages/new",view:"pageEditor",title:"New Page - Domma CMS"},{path:"/pages/edit/*",view:"pageEditor",title:"Edit Page - Domma CMS"},{path:"/media",view:"media",title:"Media - Domma CMS"},{path:"/menus",view:"menus",title:"Menus - Domma CMS"},{path:"/context-menus",view:"contextMenus",title:"Context Menus - Domma CMS"},{path:"/context-menus/new",view:"contextMenuEditor",title:"New Context Menu - Domma CMS"},{path:"/context-menus/edit/:slug",view:"contextMenuEditor",title:"Edit Context Menu - Domma CMS"},{path:"/launchers",view:"launchers",title:"Launchers - Domma CMS"},{path:"/menus/new",view:"menuEditor",title:"New Menu - Domma CMS"},{path:"/menus/edit/:slug",view:"menuEditor",title:"Edit Menu - Domma CMS"},{path:"/menu-locations",view:"menuLocations",title:"Menu Locations - Domma CMS"},{path:"/navigation",view:"menusRedirect",title:"Menus - Domma CMS"},{path:"/layouts",view:"layouts",title:"Layouts - Domma CMS"},{path:"/appearance",view:"appearance",title:"Appearance - Domma CMS"},{path:"/footer",view:"footer",title:"Footer - Domma CMS"},{path:"/settings",view:"settings",title:"Settings - Domma CMS"},{path:"/theme",view:"theme",title:"Theme - Domma CMS"},{path:"/users",view:"users",title:"Users - Domma CMS"},{path:"/users/new",view:"userEditor",title:"New User - Domma CMS"},{path:"/users/edit/:id",view:"userEditor",title:"Edit User - Domma CMS"},{path:"/plugins",view:"plugins",title:"Plugins - Domma CMS"},{path:"/plugins/code/:name",view:"pluginCode",title:"Plugin Code - Domma CMS"},{path:"/documentation",view:"documentation",title:"Usage - Domma CMS"},{path:"/tutorials",view:"tutorials",title:"Tutorials - Domma CMS"},{path:"/tutorials/crud",view:"tutorialCrud",title:"Building a CRUD App - Domma CMS"},{path:"/tutorials/editor",view:"tutorialEditor",title:"The Editor - Domma CMS"},{path:"/tutorials/plugin",view:"tutorialPlugin",title:"Writing a Tool - Domma CMS"},{path:"/tutorials/forms",view:"tutorialForms",title:"Form Follow-Up - Domma CMS"},{path:"/docs/components",view:"componentsReference",title:"Components Reference - Domma CMS"},{path:"/docs/components-howto",view:"componentsHowto",title:"Components How-To - Domma CMS"},{path:"/docs/components-walkthrough",view:"componentsWalkthrough",title:"Components Walkthrough - Domma CMS"},{path:"/docs/components-rules",view:"componentsRules",title:"Components Rules - Domma CMS"},{path:"/docs/usage/pages",view:"usagePages",title:"Pages - Usage - Domma CMS"},{path:"/docs/usage/media",view:"usageMedia",title:"Media - Usage - Domma CMS"},{path:"/docs/usage/navigation",view:"usageNavigation",title:"Navigation - Usage - Domma CMS"},{path:"/docs/usage/dconfig",view:"usageDconfig",title:"DConfig - Usage - Domma CMS"},{path:"/docs/usage/shortcodes",view:"usageShortcodes",title:"Shortcodes - Usage - Domma CMS"},{path:"/docs/usage/site-settings",view:"usageSiteSettings",title:"Site Settings - Usage - Domma CMS"},{path:"/docs/usage/plugins",view:"usagePlugins",title:"Plugins - Usage - Domma CMS"},{path:"/docs/usage/users-roles",view:"usageUsersRoles",title:"Users & Roles - Usage - Domma CMS"},{path:"/docs/usage/views",view:"usageViews",title:"Views - Usage - Domma CMS"},{path:"/docs/usage/actions",view:"usageActions",title:"Actions - Usage - Domma CMS"},{path:"/docs/usage/cta-shortcode",view:"usageCtaShortcode",title:"CTA Shortcode - Usage - Domma CMS"},{path:"/docs/usage/editions",view:"usageEditions",title:"Editions & Licences - Usage - Domma CMS"},{path:"/docs/usage/collections",view:"usageCollections",title:"Collections & Forms - Usage - Domma CMS"},{path:"/docs/usage/blocks",view:"usageBlocks",title:"Blocks - Usage - Domma CMS"},{path:"/docs/usage/tools",view:"usageTools",title:"Built-in Tools - Usage - Domma CMS"},{path:"/docs/usage/dashboard",view:"usageDashboard",title:"Dashboard - Usage - Domma CMS"},{path:"/docs/usage/search-engines",view:"usageSearchEngines",title:"Search Engines & AI - Usage - Domma CMS"},{path:"/docs/usage/launchers",view:"usageLaunchers",title:"Launchers - Usage - Domma CMS"},{path:"/docs/usage/chat",view:"usageChat",title:"Chat & Knowledge - Usage - Domma CMS"},{path:"/docs/plugins",view:"pluginGuides",title:"Plugin Guides - Domma CMS"},{path:"/docs/plugins/*",view:"pluginGuide",title:"Plugin Guide - Domma CMS"},{path:"/docs/api/authentication",view:"apiRefAuthentication",title:"Authentication - API - Domma CMS"},{path:"/docs/api/pages",view:"apiRefPages",title:"Pages - API - Domma CMS"},{path:"/docs/api/settings",view:"apiRefSettings",title:"Settings - API - Domma CMS"},{path:"/docs/api/layouts",view:"apiRefLayouts",title:"Layouts - API - Domma CMS"},{path:"/docs/api/navigation",view:"apiRefNavigation",title:"Navigation - API - Domma CMS"},{path:"/docs/api/media",view:"apiRefMedia",title:"Media - API - Domma CMS"},{path:"/docs/api/users",view:"apiRefUsers",title:"Users - API - Domma CMS"},{path:"/docs/api/plugins",view:"apiRefPlugins",title:"Plugins - API - Domma CMS"},{path:"/docs/api/collections",view:"apiRefCollections",title:"Collections - API - Domma CMS"},{path:"/docs/api/views",view:"apiRefViews",title:"Views API - Domma CMS"},{path:"/docs/api/actions",view:"apiRefActions",title:"Actions API - Domma CMS"},{path:"/docs/api/forms",view:"apiRefForms",title:"Forms API - Domma CMS"},{path:"/docs/api/scaffold",view:"apiRefScaffold",title:"Scaffold API - Domma CMS"},{path:"/docs/api/external",view:"apiRefExternal",title:"External API & Tokens - Domma CMS"},{path:"/docs/api/content",view:"apiRefContent",title:"Content API - Domma CMS"},{path:"/docs/api/builder",view:"apiRefBuilder",title:"API Builder - Domma CMS"},{path:"/api-reference",view:"apiReference",title:"API Reference - Domma CMS"},{path:"/collections",view:"collections",title:"Collections - Domma CMS"},{path:"/collections/new",view:"collectionEditor",title:"New Collection - Domma CMS"},{path:"/collections/edit/:slug",view:"collectionEditor",title:"Edit Collection - Domma CMS"},{path:"/collections/:slug/entries",view:"collectionEntries",title:"Entries - Domma CMS"},{path:"/forms",view:"forms",title:"Forms - Domma CMS"},{path:"/forms/new",view:"formEditor",title:"New Form - Domma CMS"},{path:"/forms/edit/:slug",view:"formEditor",title:"Edit Form - Domma CMS"},{path:"/forms/:slug/submissions",view:"formSubmissions",title:"Submissions - Domma CMS"},{path:"/views",view:"viewsList",title:"Views - Domma CMS"},{path:"/views/new",view:"viewEditor",title:"New View - Domma CMS"},{path:"/views/edit/:slug",view:"viewEditor",title:"Edit View - Domma CMS"},{path:"/views/:slug/preview",view:"viewPreview",title:"View Preview - Domma CMS"},{path:"/actions",view:"actionsList",title:"Actions - Domma CMS"},{path:"/actions/new",view:"actionEditor",title:"New Action - Domma CMS"},{path:"/actions/edit/:slug",view:"actionEditor",title:"Edit Action - Domma CMS"},{path:"/pro/docs",view:"proDocs",title:"Pro Documentation - Domma CMS"},{path:"/blocks",view:"blocks",title:"Blocks - Domma CMS"},{path:"/blocks/new",view:"pageEditor",title:"New Block - Domma CMS"},{path:"/blocks/edit/:name",view:"pageEditor",title:"Edit Block - Domma CMS"},{path:"/components",view:"components",title:"Components - Domma CMS"},{path:"/components/new",view:"pageEditor",title:"New Component - Domma CMS"},{path:"/components/edit/:name",view:"pageEditor",title:"Edit Component - Domma CMS"},{path:"/my-profile",view:"myProfile",title:"My Profile - Domma CMS"},{path:"/roles",view:"roles",title:"Roles & Permissions - Domma CMS"},{path:"/roles/edit/:id",view:"roleEditor",title:"Edit Role - Domma CMS"},{path:"/effects",view:"effects",title:"Effects - Domma CMS"},{path:"/search",view:"search",title:"Search - Domma CMS"},{path:"/content-api",view:"contentApi",title:"Content API - Domma CMS"},{path:"/launchers/chats",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/chats/:id",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/knowledge",view:"chatKnowledge",title:"Chat Knowledge - Domma CMS"},{path:"/notes",view:"notes",title:"Notes - Domma CMS"},{path:"/todo",view:"todo",title:"Todo - Domma CMS"},{path:"/calculator",view:"calculator",title:"Calculator - Domma CMS"},{path:"/analytics",view:"analytics",title:"Analytics - Domma CMS"},{path:"/seo",view:"seo",title:"SEO - Domma CMS"},{path:"/seo/:tab",view:"seo",title:"SEO - Domma CMS"},{path:"/wordpress-import",view:"wordpressImport",title:"Import a site - Domma CMS"},{path:"/contacts",view:"contacts",title:"Contacts - Domma CMS"},{path:"/calls/new",view:"callNew",title:"Call now - Domma CMS"},{path:"/system/notifications",view:"notifications",title:"Notifications - Domma CMS"},{path:"/api-tokens",view:"apiTokens",title:"API Tokens - Domma CMS"},{path:"/api-endpoints",view:"apiEndpoints",title:"API Builder - Domma CMS"},{path:"/api-endpoints/new",view:"apiEndpointEditor",title:"New API Endpoint - Domma CMS"},{path:"/api-endpoints/edit/:id",view:"apiEndpointEditor",title:"Edit API Endpoint - Domma CMS"},{path:"/projects",view:"projects",title:"Projects - Domma CMS"},{path:"/projects/new",view:"projects",title:"New Project - Domma CMS"},{path:"/projects/edit/:slug",view:"projects",title:"Edit Project - Domma CMS"},{path:"/projects/:slug/settings",view:"projectSettings",title:"Project settings - Domma CMS"},{path:"/projects/:slug/pages",view:"pages",title:"Project pages - Domma CMS"},{path:"/projects/:slug/collections",view:"collections",title:"Project collections - Domma CMS"},{path:"/projects/:slug/forms",view:"forms",title:"Project forms - Domma CMS"},{path:"/projects/:slug/actions",view:"actionsList",title:"Project actions - Domma CMS"},{path:"/projects/:slug/menus",view:"menus",title:"Project menus - Domma CMS"},{path:"/projects/:slug/blocks",view:"blocks",title:"Project blocks - Domma CMS"},{path:"/projects/:slug/components",view:"components",title:"Project components - Domma CMS"},{path:"/projects/:slug/views",view:"viewsList",title:"Project views - Domma CMS"},{path:"/projects/:slug/roles",view:"roles",title:"Project roles - Domma CMS"},{path:"/projects/:slug/users",view:"users",title:"Project users - Domma CMS"},{path:"/projects/:slug/apis",view:"apiEndpoints",title:"Project APIs - Domma CMS"},{path:"/projects/:slug",view:"projectDetail",title:"Project - Domma CMS"},{path:"/login",view:"login",title:"Sign in - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}},{path:"/reset-password",view:"login",title:"Reset Password - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}}];M.subscribe("router:afterChange",async({to:t,from:i})=>{if(!y(t.path)){if($("#admin-sidebar").show(),$("#admin-topbar").show(),y(i?.path)){$("#topbar-user-name").remove(),import("./lib/admin-theme.js").then(o=>o.refreshAdminTheme(r)),await x();const e=await b(),a=N(t.path);if(a&&R.navigate(a),T(e),St.read().signInToasts)try{const o=await r.system.notifications.list().catch(()=>[]),n=(Array.isArray(o)?o:[]).filter(s=>s.unread&&["warning","critical"].includes(s.data?.severity)).slice(0,3);for(const s of n){const l=h(s.data?.title||""),F=h((s.data?.body||"").slice(0,120));E.toast(`${l} - ${F}`,{type:s.data?.severity==="critical"?"error":"warning",duration:0})}}catch{}}H()}}),M.subscribe("router:afterChange",()=>{setTimeout(()=>{$(".btn-primary, .btn-danger").length&&Domma.effects.reveal(".btn-primary, .btn-danger",{animation:"fade",stagger:40,duration:300})},50)});const Y=["#field-project","#menu-project","#collection-project","#endpoint-project","#action-project","#view-project","#block-project","#component-project","#role-project",'[name="project"]','[name="ownedByProject"]'];function Q(t){return/^\/(pages|menus|context-menus|collections|forms|actions|views|blocks|components|users|roles|api-endpoints)\/(new|edit\/)/.test(t)}M.subscribe("router:afterChange",({to:t})=>{const i=t?String(t.path).split("?")[0]:"";if(!t||!Q(i))return;const a=new URLSearchParams(location.hash.split("?")[1]||"").get("project");if(!a||!/\/new$/.test(i))return;let o=0;const n=60,s=1500,l=()=>{o+=n;for(const F of Y){const D=document.querySelector(F);if(!D)continue;if(Array.from(D.options||[]).find(Z=>Z.value===a)){D.value=a,D.dispatchEvent(new Event("change",{bubbles:!0}));return}}o<s&&setTimeout(l,n)};setTimeout(l,n)});const _="cms_card_states",U=S.get(_)||{};M.subscribe("router:afterChange",()=>{setTimeout(()=>{$("#view-container .card-collapsible").each(function(){const t=$(this).find(".card-header h2, .card-header h3").first().text().trim();t&&U[t]==="collapsed"&&$(this).addClass("card-collapsed")})},200)}),$("#view-container").on("click",".card-collapsible .card-header",function(t){if($(t.target).closest("button, a").length)return;const i=$(this).closest(".card");i.toggleClass("card-collapsed");const e=$(this).find("h2, h3").first().text().trim();e&&(U[e]=i.hasClass("card-collapsed")?"collapsed":"open",S.set(_,U))}),Pt(),document.addEventListener("keydown",t=>{if(!(t.ctrlKey||t.metaKey)||t.key!=="s"||window.location.hash.startsWith("#/login")||window.location.hash.startsWith("#/reset-password"))return;const i=document.querySelector("#view-container .view-header button.btn-primary");i&&(t.preventDefault(),i.click())});const C=it(),W=C.views,X={notes:{displayName:"Notes",icon:"edit-3"},todo:{displayName:"Todo",icon:"check-square"},calculator:{displayName:"Calculator",icon:"calculator"},analytics:{displayName:"Analytics",icon:"chart-bar"},seo:{displayName:"SEO",icon:"search"},wordpressImport:{displayName:"Import a site",icon:"download"},contacts:{displayName:"Contacts",icon:"users"},projects:{displayName:"Projects",icon:"folder"},pages:{displayName:"Pages",icon:"file-text"},media:{displayName:"Media",icon:"image"},menus:{displayName:"Site menus",icon:"menu"},contextMenus:{displayName:"Context Menus",icon:"menu"},launchers:{displayName:"Launchers",icon:"rocket"},theme:{displayName:"Theme",icon:"droplet"},collections:{displayName:"Collections",icon:"database"},forms:{displayName:"Forms",icon:"layout"},viewsList:{displayName:"Views",icon:"eye"},actionsList:{displayName:"Actions",icon:"zap"},apiEndpoints:{displayName:"API Builder",icon:"code"},blocks:{displayName:"Blocks",icon:"box"},components:{displayName:"Components",icon:"component"},notifications:{displayName:"Notifications",icon:"bell"},roles:{displayName:"Roles",icon:"shield"},users:{displayName:"Users",icon:"users"},appearance:{displayName:"Appearance",icon:"layout"},footer:{displayName:"Footer",icon:"panel-bottom"},settings:{displayName:"Site Settings",icon:"settings"},effects:{displayName:"Effects",icon:"sparkles"},layouts:{displayName:"Layouts",icon:"layout"},plugins:{displayName:"Marketplace",icon:"store"},myProfile:{displayName:"My Profile",icon:"user"},apiTokens:{displayName:"API Tokens",icon:"key"},search:{displayName:"Search",icon:"search"},contentApi:{displayName:"Content API",icon:"file-text"},chats:{displayName:"Chats",icon:"message-circle"},dashboard:{displayName:"Dashboard",icon:"home"},dashboards:{displayName:"Dashboards",icon:"home"},pageEditor:{displayName:"Pages",section:"Edit",icon:"file-text"},menuEditor:{displayName:"Site menus",section:"Edit",icon:"menu"},menuLocations:{displayName:"Site menus",section:"Locations",icon:"map-pin"},contextMenuEditor:{displayName:"Context Menus",section:"Edit",icon:"menu"},collectionEditor:{displayName:"Collections",section:"Edit",icon:"database"},collectionEntries:{displayName:"Collections",section:"Entries",icon:"database"},formEditor:{displayName:"Forms",section:"Edit",icon:"layout"},formSubmissions:{displayName:"Forms",section:"Submissions",icon:"inbox"},viewEditor:{displayName:"Views",section:"Edit",icon:"eye"},viewPreview:{displayName:"Views",section:"Preview",icon:"eye"},actionEditor:{displayName:"Actions",section:"Edit",icon:"zap"},apiEndpointEditor:{displayName:"API Builder",section:"Edit",icon:"code"},roleEditor:{displayName:"Roles",section:"Edit",icon:"shield"},userEditor:{displayName:"Users",section:"Edit",icon:"users"},projectDetail:{displayName:"Projects",section:"Overview",icon:"folder"},projectSettings:{displayName:"Projects",section:"Settings",icon:"folder"},pluginCode:{displayName:"Marketplace",section:"Code",icon:"code"},chatKnowledge:{displayName:"Chats",section:"Knowledge",icon:"book-open"}};for(const[t,i]of Object.entries(at))C.register(t,async()=>{let e=await i();const a=X[t];return a&&(e=K(e,{plugin:t,licence:"Built in",...a})),t==="dashboard"?z(e):e});R.use(async(t,i,e)=>{try{await C.load(t.view)}catch(a){console.error("[admin] Screen failed to load",a),W[t.view]={template:'<p role="alert">This screen could not load. Reload the page to try again.</p>'}}e()});const L=[...J];async function x(){if(p())try{const t=await r.plugins.adminConfig(),i=new Set(L.map(e=>e.path));for(const e of t.routes||[])i.has(e.path)||L.push(e);for(const[e,a]of Object.entries(t.views||{})){const o=(t.meta||{})[e];C.register(e,async()=>{const s=(await import(`/plugins/${a.entry}`))[a.exportName];if(!s)throw new Error(`Missing plugin screen: ${e}`);const l=K(s,o);return e==="dashboard"?z(l):l},JSON.stringify([a,o]))}for(const[e,{route:a}]of Object.entries(t.takeovers||{}))a&&(A[`/${e}`]=a);t.mediaPicker&&(globalThis[Symbol.for("domma.media-picker")]=t.mediaPicker);for(const[e,{enabled:a,displayName:o}]of Object.entries(t.tools||{}))a===!1&&(j[`/${e}`]=o);for(const{id:e,href:a}of t.css||[])if(!document.getElementById(e)){const o=document.createElement("link");o.id=e,o.rel="stylesheet",o.href=a,document.head.appendChild(o)}}catch{}}function H(){const t=O();if(!t)return;if($("#topbar-user-name").length){V(r);return}const e={"super-admin":"Super Admin",admin:"Admin",user:"User"}[t.role]||t.role,a=Ct(t);$("#topbar-user").get(0).innerHTML=`
|
|
1
|
+
import{wireNotificationMenu as it}from"./lib/topbar-notifications.js";import{installSmoothCarets as ot}from"./lib/smooth-caret.js";import{viewLoaders as st}from"./views/index.js";import{createLazyViews as nt}from"./lib/lazy-views.js";import{withPluginChrome as q}from"./lib/plugin-chrome.js";import{api as r,getUser as V,isAuthenticated as p,logout as rt,sendToLogin as lt}from"./api.js";import{claimDrafts as ct}from"./lib/draft-owner.js";import{isAuthScreen as y,loginHashFor as mt}from"./lib/login-arrange.js";import{installHttpInterceptor as pt}from"./http-interceptor.js";import{installResizableSlideovers as dt}from"./lib/slideover-resizable.js";import{installActivityThrobber as ut}from"./lib/activity-throbber.js";import{installUpdateNotice as ht,renderCmsVersion as wt}from"./lib/update-notice.js";import{renderFrameworkVersions as z,wireAccountMenu as gt}from"./lib/topbar-account.js";import{refreshTopbarProject as _}from"./lib/topbar-project.js";import{CONFINED_CLASS as ft,isConfined as vt,isPathAllowed as bt,redirectFor as Ct}from"./lib/admin-scope.js";import{deliverDesktop as St,desktopActive as G,notificationSettings as J}from"./lib/desktop-notify.js";import{deliverChatToasts as Mt}from"./lib/chat-toast.js";import{avatarUrl as Dt,installAccountAvatar as yt}from"./lib/avatar.js";import{installCalculator as Et}from"./lib/calculator.js";import{installAdminAssistant as Nt}from"./lib/admin-assistant.js";import{installAdminLaunchers as Pt}from"./lib/admin-launchers.js";import{takeOverviewPass as At,withDashboardStrip as Y}from"./lib/dashboards-strip.js";import{installHotkeys as jt}from"./lib/hotkeys-ui.js";import{applyAdminBrand as Q}from"./lib/admin-brand.js";import{installRouterCatchUp as kt}from"./lib/router-catch-up.js";import{installSidebarDrawer as Rt}from"./lib/sidebar-drawer.js";$(()=>{ot(document),pt(),Et(),Nt(),Pt(),ht(),ut(),dt(),Rt(),(async()=>{const{applyAdminTheme:t,refreshAdminTheme:i}=await import("./lib/admin-theme.js");p()?await i(r,{init:!0}):t({dommaTheme:"charcoal-dark"},{init:!0})})();let c=null,f=null,m="/",v=!1,w=null,d=null,u=!0;function N(t){if(j[t])return E.toast(`${j[t]} is switched off on this site.`,{type:"info"}),"/";const[i,e]=t.split("?"),a=new URLSearchParams(e||"").get("tab");if(i==="/settings"&&["favicon","pageNavigation","breadcrumbs","motion","search"].includes(a))return`/appearance?tab=${a}`;if(t.split("?")[0]==="/my-dashboard")return"/dashboards";const o=A[t]||Ct(c,t);return o||(!u&&i==="/system/notifications"?c?.home||"/":(t.split("?")[0]||"/")==="/"&&m&&m!=="/"&&!At()?A[m]||m:null)}function P(){document.body.classList.toggle(ft,vt(c))}const A={},j={};R.use(async(t,i,e)=>{if(y(t.path))return e();if(!p()){lt();return}const a=N(t.path);if(a){R.navigate(a);return}e()});async function b(){try{const t=await r.get("/auth/permissions");c=t.adminScope||null,P(),f=t.adminBrand||null,Q(f),m=t.adminHome||"/",z(t.versions||{});const i=t.permissions||[];return v=bt(c,"/settings")&&i.some(e=>e==="settings"||e.startsWith("settings.")),w=i.some(e=>e==="notifications"||e.startsWith("notifications.")),d=t.adminPortal||null,u=t.notificationsScreen!==!1,i}catch{return c=null,P(),m="/",f||Q(null),v=!1,w=null,d=null,u=!0,[]}}document.addEventListener("dm:admin-home-changed",()=>{b()});let k=null,I=!1;document.addEventListener("dm:sidebar-rebuild",()=>{if(_(r),k){I=!0;return}k=(async()=>{do{I=!1;try{await T(await b())}catch{}}while(I)})().finally(()=>{k=null})});async function T(t){const{applyAdminPortal:i}=await import("./lib/admin-portal.js");if(await i(d),d)return;const{renderAdminSidebar:e}=await import("./lib/sidebar-renderer.js");await e({mount:"#admin-sidebar",permissions:t,adminScope:c,brand:f,notificationsScreen:u})}M.subscribe("router:afterChange",({to:t})=>{y(t.path)&&(g&&(clearInterval(g),g=null),c=null,P(),m="/",v=!1,w=null,u=!0,d&&(d=null,import("./lib/admin-portal.js").then(i=>i.applyAdminPortal(null))))});const X=[{path:"/",view:"dashboard",title:"Dashboard - Domma CMS"},{path:"/dashboards",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/my-dashboard",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/pages",view:"pages",title:"Pages - Domma CMS"},{path:"/pages/new",view:"pageEditor",title:"New Page - Domma CMS"},{path:"/pages/edit/*",view:"pageEditor",title:"Edit Page - Domma CMS"},{path:"/media",view:"media",title:"Media - Domma CMS"},{path:"/menus",view:"menus",title:"Menus - Domma CMS"},{path:"/context-menus",view:"contextMenus",title:"Context Menus - Domma CMS"},{path:"/context-menus/new",view:"contextMenuEditor",title:"New Context Menu - Domma CMS"},{path:"/context-menus/edit/:slug",view:"contextMenuEditor",title:"Edit Context Menu - Domma CMS"},{path:"/launchers",view:"launchers",title:"Launchers - Domma CMS"},{path:"/menus/new",view:"menuEditor",title:"New Menu - Domma CMS"},{path:"/menus/edit/:slug",view:"menuEditor",title:"Edit Menu - Domma CMS"},{path:"/menu-locations",view:"menuLocations",title:"Menu Locations - Domma CMS"},{path:"/navigation",view:"menusRedirect",title:"Menus - Domma CMS"},{path:"/layouts",view:"layouts",title:"Layouts - Domma CMS"},{path:"/appearance",view:"appearance",title:"Appearance - Domma CMS"},{path:"/footer",view:"footer",title:"Footer - Domma CMS"},{path:"/settings",view:"settings",title:"Settings - Domma CMS"},{path:"/theme",view:"theme",title:"Theme - Domma CMS"},{path:"/users",view:"users",title:"Users - Domma CMS"},{path:"/users/new",view:"userEditor",title:"New User - Domma CMS"},{path:"/users/edit/:id",view:"userEditor",title:"Edit User - Domma CMS"},{path:"/plugins",view:"plugins",title:"Plugins - Domma CMS"},{path:"/plugins/code/:name",view:"pluginCode",title:"Plugin Code - Domma CMS"},{path:"/documentation",view:"documentation",title:"Usage - Domma CMS"},{path:"/tutorials",view:"tutorials",title:"Tutorials - Domma CMS"},{path:"/tutorials/crud",view:"tutorialCrud",title:"Building a CRUD App - Domma CMS"},{path:"/tutorials/editor",view:"tutorialEditor",title:"The Editor - Domma CMS"},{path:"/tutorials/plugin",view:"tutorialPlugin",title:"Writing a Tool - Domma CMS"},{path:"/tutorials/forms",view:"tutorialForms",title:"Form Follow-Up - Domma CMS"},{path:"/docs/components",view:"componentsReference",title:"Components Reference - Domma CMS"},{path:"/docs/components-howto",view:"componentsHowto",title:"Components How-To - Domma CMS"},{path:"/docs/components-walkthrough",view:"componentsWalkthrough",title:"Components Walkthrough - Domma CMS"},{path:"/docs/components-rules",view:"componentsRules",title:"Components Rules - Domma CMS"},{path:"/docs/usage/pages",view:"usagePages",title:"Pages - Usage - Domma CMS"},{path:"/docs/usage/media",view:"usageMedia",title:"Media - Usage - Domma CMS"},{path:"/docs/usage/navigation",view:"usageNavigation",title:"Navigation - Usage - Domma CMS"},{path:"/docs/usage/dconfig",view:"usageDconfig",title:"DConfig - Usage - Domma CMS"},{path:"/docs/usage/shortcodes",view:"usageShortcodes",title:"Shortcodes - Usage - Domma CMS"},{path:"/docs/usage/site-settings",view:"usageSiteSettings",title:"Site Settings - Usage - Domma CMS"},{path:"/docs/usage/plugins",view:"usagePlugins",title:"Plugins - Usage - Domma CMS"},{path:"/docs/usage/users-roles",view:"usageUsersRoles",title:"Users & Roles - Usage - Domma CMS"},{path:"/docs/usage/views",view:"usageViews",title:"Views - Usage - Domma CMS"},{path:"/docs/usage/actions",view:"usageActions",title:"Actions - Usage - Domma CMS"},{path:"/docs/usage/cta-shortcode",view:"usageCtaShortcode",title:"CTA Shortcode - Usage - Domma CMS"},{path:"/docs/usage/editions",view:"usageEditions",title:"Editions & Licences - Usage - Domma CMS"},{path:"/docs/usage/collections",view:"usageCollections",title:"Collections & Forms - Usage - Domma CMS"},{path:"/docs/usage/blocks",view:"usageBlocks",title:"Blocks - Usage - Domma CMS"},{path:"/docs/usage/tools",view:"usageTools",title:"Built-in Tools - Usage - Domma CMS"},{path:"/docs/usage/dashboard",view:"usageDashboard",title:"Dashboard - Usage - Domma CMS"},{path:"/docs/usage/search-engines",view:"usageSearchEngines",title:"Search Engines & AI - Usage - Domma CMS"},{path:"/docs/usage/launchers",view:"usageLaunchers",title:"Launchers - Usage - Domma CMS"},{path:"/docs/usage/chat",view:"usageChat",title:"Chat & Knowledge - Usage - Domma CMS"},{path:"/docs/plugins",view:"pluginGuides",title:"Plugin Guides - Domma CMS"},{path:"/docs/plugins/*",view:"pluginGuide",title:"Plugin Guide - Domma CMS"},{path:"/docs/api/authentication",view:"apiRefAuthentication",title:"Authentication - API - Domma CMS"},{path:"/docs/api/pages",view:"apiRefPages",title:"Pages - API - Domma CMS"},{path:"/docs/api/settings",view:"apiRefSettings",title:"Settings - API - Domma CMS"},{path:"/docs/api/layouts",view:"apiRefLayouts",title:"Layouts - API - Domma CMS"},{path:"/docs/api/navigation",view:"apiRefNavigation",title:"Navigation - API - Domma CMS"},{path:"/docs/api/media",view:"apiRefMedia",title:"Media - API - Domma CMS"},{path:"/docs/api/users",view:"apiRefUsers",title:"Users - API - Domma CMS"},{path:"/docs/api/plugins",view:"apiRefPlugins",title:"Plugins - API - Domma CMS"},{path:"/docs/api/collections",view:"apiRefCollections",title:"Collections - API - Domma CMS"},{path:"/docs/api/views",view:"apiRefViews",title:"Views API - Domma CMS"},{path:"/docs/api/actions",view:"apiRefActions",title:"Actions API - Domma CMS"},{path:"/docs/api/forms",view:"apiRefForms",title:"Forms API - Domma CMS"},{path:"/docs/api/scaffold",view:"apiRefScaffold",title:"Scaffold API - Domma CMS"},{path:"/docs/api/external",view:"apiRefExternal",title:"External API & Tokens - Domma CMS"},{path:"/docs/api/content",view:"apiRefContent",title:"Content API - Domma CMS"},{path:"/docs/api/builder",view:"apiRefBuilder",title:"API Builder - Domma CMS"},{path:"/api-reference",view:"apiReference",title:"API Reference - Domma CMS"},{path:"/collections",view:"collections",title:"Collections - Domma CMS"},{path:"/collections/new",view:"collectionEditor",title:"New Collection - Domma CMS"},{path:"/collections/edit/:slug",view:"collectionEditor",title:"Edit Collection - Domma CMS"},{path:"/collections/:slug/entries",view:"collectionEntries",title:"Entries - Domma CMS"},{path:"/forms",view:"forms",title:"Forms - Domma CMS"},{path:"/forms/new",view:"formEditor",title:"New Form - Domma CMS"},{path:"/forms/edit/:slug",view:"formEditor",title:"Edit Form - Domma CMS"},{path:"/forms/:slug/submissions",view:"formSubmissions",title:"Submissions - Domma CMS"},{path:"/views",view:"viewsList",title:"Views - Domma CMS"},{path:"/views/new",view:"viewEditor",title:"New View - Domma CMS"},{path:"/views/edit/:slug",view:"viewEditor",title:"Edit View - Domma CMS"},{path:"/views/:slug/preview",view:"viewPreview",title:"View Preview - Domma CMS"},{path:"/actions",view:"actionsList",title:"Actions - Domma CMS"},{path:"/actions/new",view:"actionEditor",title:"New Action - Domma CMS"},{path:"/actions/edit/:slug",view:"actionEditor",title:"Edit Action - Domma CMS"},{path:"/pro/docs",view:"proDocs",title:"Pro Documentation - Domma CMS"},{path:"/blocks",view:"blocks",title:"Blocks - Domma CMS"},{path:"/blocks/new",view:"pageEditor",title:"New Block - Domma CMS"},{path:"/blocks/edit/:name",view:"pageEditor",title:"Edit Block - Domma CMS"},{path:"/components",view:"components",title:"Components - Domma CMS"},{path:"/components/new",view:"pageEditor",title:"New Component - Domma CMS"},{path:"/components/edit/:name",view:"pageEditor",title:"Edit Component - Domma CMS"},{path:"/my-profile",view:"myProfile",title:"My Profile - Domma CMS"},{path:"/roles",view:"roles",title:"Roles & Permissions - Domma CMS"},{path:"/roles/edit/:id",view:"roleEditor",title:"Edit Role - Domma CMS"},{path:"/effects",view:"effects",title:"Effects - Domma CMS"},{path:"/search",view:"search",title:"Search - Domma CMS"},{path:"/content-api",view:"contentApi",title:"Content API - Domma CMS"},{path:"/launchers/chats",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/chats/:id",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/knowledge",view:"chatKnowledge",title:"Chat Knowledge - Domma CMS"},{path:"/notes",view:"notes",title:"Notes - Domma CMS"},{path:"/todo",view:"todo",title:"Todo - Domma CMS"},{path:"/calculator",view:"calculator",title:"Calculator - Domma CMS"},{path:"/analytics",view:"analytics",title:"Analytics - Domma CMS"},{path:"/seo",view:"seo",title:"SEO - Domma CMS"},{path:"/seo/:tab",view:"seo",title:"SEO - Domma CMS"},{path:"/wordpress-import",view:"wordpressImport",title:"Import a site - Domma CMS"},{path:"/contacts",view:"contacts",title:"Contacts - Domma CMS"},{path:"/calls/new",view:"callNew",title:"Call now - Domma CMS"},{path:"/system/notifications",view:"notifications",title:"Notifications - Domma CMS"},{path:"/api-tokens",view:"apiTokens",title:"API Tokens - Domma CMS"},{path:"/api-endpoints",view:"apiEndpoints",title:"API Builder - Domma CMS"},{path:"/api-endpoints/new",view:"apiEndpointEditor",title:"New API Endpoint - Domma CMS"},{path:"/api-endpoints/edit/:id",view:"apiEndpointEditor",title:"Edit API Endpoint - Domma CMS"},{path:"/projects",view:"projects",title:"Projects - Domma CMS"},{path:"/projects/new",view:"projects",title:"New Project - Domma CMS"},{path:"/projects/edit/:slug",view:"projects",title:"Edit Project - Domma CMS"},{path:"/projects/:slug/settings",view:"projectSettings",title:"Project settings - Domma CMS"},{path:"/projects/:slug/pages",view:"pages",title:"Project pages - Domma CMS"},{path:"/projects/:slug/collections",view:"collections",title:"Project collections - Domma CMS"},{path:"/projects/:slug/forms",view:"forms",title:"Project forms - Domma CMS"},{path:"/projects/:slug/actions",view:"actionsList",title:"Project actions - Domma CMS"},{path:"/projects/:slug/menus",view:"menus",title:"Project menus - Domma CMS"},{path:"/projects/:slug/blocks",view:"blocks",title:"Project blocks - Domma CMS"},{path:"/projects/:slug/components",view:"components",title:"Project components - Domma CMS"},{path:"/projects/:slug/views",view:"viewsList",title:"Project views - Domma CMS"},{path:"/projects/:slug/roles",view:"roles",title:"Project roles - Domma CMS"},{path:"/projects/:slug/users",view:"users",title:"Project users - Domma CMS"},{path:"/projects/:slug/apis",view:"apiEndpoints",title:"Project APIs - Domma CMS"},{path:"/projects/:slug",view:"projectDetail",title:"Project - Domma CMS"},{path:"/login",view:"login",title:"Sign in - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}},{path:"/reset-password",view:"login",title:"Reset Password - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}}];M.subscribe("router:afterChange",async({to:t,from:i})=>{if(!y(t.path)){if($("#admin-sidebar").show(),$("#admin-topbar").show(),y(i?.path)){$("#topbar-user-name").remove(),import("./lib/admin-theme.js").then(o=>o.refreshAdminTheme(r)),await x();const e=await b(),a=N(t.path);if(a&&R.navigate(a),T(e),J.read().signInToasts)try{const o=await r.system.notifications.list().catch(()=>[]),n=(Array.isArray(o)?o:[]).filter(s=>s.unread&&["warning","critical"].includes(s.data?.severity)).slice(0,3);for(const s of n){const l=h(s.data?.title||""),O=h((s.data?.body||"").slice(0,120));E.toast(`${l} - ${O}`,{type:s.data?.severity==="critical"?"error":"warning",duration:0})}}catch{}}K()}}),M.subscribe("router:afterChange",()=>{setTimeout(()=>{$(".btn-primary, .btn-danger").length&&Domma.effects.reveal(".btn-primary, .btn-danger",{animation:"fade",stagger:40,duration:300})},50)});const Z=["#field-project","#menu-project","#collection-project","#endpoint-project","#action-project","#view-project","#block-project","#component-project","#role-project",'[name="project"]','[name="ownedByProject"]'];function tt(t){return/^\/(pages|menus|context-menus|collections|forms|actions|views|blocks|components|users|roles|api-endpoints)\/(new|edit\/)/.test(t)}M.subscribe("router:afterChange",({to:t})=>{const i=t?String(t.path).split("?")[0]:"";if(!t||!tt(i))return;const a=new URLSearchParams(location.hash.split("?")[1]||"").get("project");if(!a||!/\/new$/.test(i))return;let o=0;const n=60,s=1500,l=()=>{o+=n;for(const O of Z){const D=document.querySelector(O);if(!D)continue;if(Array.from(D.options||[]).find(at=>at.value===a)){D.value=a,D.dispatchEvent(new Event("change",{bubbles:!0}));return}}o<s&&setTimeout(l,n)};setTimeout(l,n)});const W="cms_card_states",U=S.get(W)||{};M.subscribe("router:afterChange",()=>{setTimeout(()=>{$("#view-container .card-collapsible").each(function(){const t=$(this).find(".card-header h2, .card-header h3").first().text().trim();t&&U[t]==="collapsed"&&$(this).addClass("card-collapsed")})},200)}),$("#view-container").on("click",".card-collapsible .card-header",function(t){if($(t.target).closest("button, a").length)return;const i=$(this).closest(".card");i.toggleClass("card-collapsed");const e=$(this).find("h2, h3").first().text().trim();e&&(U[e]=i.hasClass("card-collapsed")?"collapsed":"open",S.set(W,U))}),jt(),document.addEventListener("keydown",t=>{if(!(t.ctrlKey||t.metaKey)||t.key!=="s"||window.location.hash.startsWith("#/login")||window.location.hash.startsWith("#/reset-password"))return;const i=document.querySelector("#view-container .view-header button.btn-primary");i&&(t.preventDefault(),i.click())});const C=nt(),H=C.views,et={notes:{displayName:"Notes",icon:"edit-3"},todo:{displayName:"Todo",icon:"check-square"},calculator:{displayName:"Calculator",icon:"calculator"},analytics:{displayName:"Analytics",icon:"chart-bar"},seo:{displayName:"SEO",icon:"search"},wordpressImport:{displayName:"Import a site",icon:"download"},contacts:{displayName:"Contacts",icon:"users"},projects:{displayName:"Projects",icon:"folder"},pages:{displayName:"Pages",icon:"file-text"},media:{displayName:"Media",icon:"image"},menus:{displayName:"Site menus",icon:"menu"},contextMenus:{displayName:"Context Menus",icon:"menu"},launchers:{displayName:"Launchers",icon:"rocket"},theme:{displayName:"Theme",icon:"droplet"},collections:{displayName:"Collections",icon:"database"},forms:{displayName:"Forms",icon:"layout"},viewsList:{displayName:"Views",icon:"eye"},actionsList:{displayName:"Actions",icon:"zap"},apiEndpoints:{displayName:"API Builder",icon:"code"},blocks:{displayName:"Blocks",icon:"box"},components:{displayName:"Components",icon:"component"},notifications:{displayName:"Notifications",icon:"bell"},roles:{displayName:"Roles",icon:"shield"},users:{displayName:"Users",icon:"users"},appearance:{displayName:"Appearance",icon:"layout"},footer:{displayName:"Footer",icon:"panel-bottom"},settings:{displayName:"Site Settings",icon:"settings"},effects:{displayName:"Effects",icon:"sparkles"},layouts:{displayName:"Layouts",icon:"layout"},plugins:{displayName:"Marketplace",icon:"store"},myProfile:{displayName:"My Profile",icon:"user"},apiTokens:{displayName:"API Tokens",icon:"key"},search:{displayName:"Search",icon:"search"},contentApi:{displayName:"Content API",icon:"file-text"},chats:{displayName:"Chats",icon:"message-circle"},dashboard:{displayName:"Dashboard",icon:"home"},dashboards:{displayName:"Dashboards",icon:"home"},pageEditor:{displayName:"Pages",section:"Edit",icon:"file-text"},menuEditor:{displayName:"Site menus",section:"Edit",icon:"menu"},menuLocations:{displayName:"Site menus",section:"Locations",icon:"map-pin"},contextMenuEditor:{displayName:"Context Menus",section:"Edit",icon:"menu"},collectionEditor:{displayName:"Collections",section:"Edit",icon:"database"},collectionEntries:{displayName:"Collections",section:"Entries",icon:"database"},formEditor:{displayName:"Forms",section:"Edit",icon:"layout"},formSubmissions:{displayName:"Forms",section:"Submissions",icon:"inbox"},viewEditor:{displayName:"Views",section:"Edit",icon:"eye"},viewPreview:{displayName:"Views",section:"Preview",icon:"eye"},actionEditor:{displayName:"Actions",section:"Edit",icon:"zap"},apiEndpointEditor:{displayName:"API Builder",section:"Edit",icon:"code"},roleEditor:{displayName:"Roles",section:"Edit",icon:"shield"},userEditor:{displayName:"Users",section:"Edit",icon:"users"},projectDetail:{displayName:"Projects",section:"Overview",icon:"folder"},projectSettings:{displayName:"Projects",section:"Settings",icon:"folder"},pluginCode:{displayName:"Marketplace",section:"Code",icon:"code"},chatKnowledge:{displayName:"Chats",section:"Knowledge",icon:"book-open"}};for(const[t,i]of Object.entries(st))C.register(t,async()=>{let e=await i();const a=et[t];return a&&(e=q(e,{plugin:t,licence:"Built in",...a})),t==="dashboard"?Y(e):e});R.use(async(t,i,e)=>{try{await C.load(t.view)}catch(a){console.error("[admin] Screen failed to load",a),H[t.view]={template:'<p role="alert">This screen could not load. Reload the page to try again.</p>'}}e()});const L=[...X];async function x(){if(p())try{const t=await r.plugins.adminConfig(),i=new Set(L.map(e=>e.path));for(const e of t.routes||[])i.has(e.path)||L.push(e);for(const[e,a]of Object.entries(t.views||{})){const o=(t.meta||{})[e];C.register(e,async()=>{const s=(await import(`/plugins/${a.entry}`))[a.exportName];if(!s)throw new Error(`Missing plugin screen: ${e}`);const l=q(s,o);return e==="dashboard"?Y(l):l},JSON.stringify([a,o]))}for(const[e,{route:a}]of Object.entries(t.takeovers||{}))a&&(A[`/${e}`]=a);t.mediaPicker&&(globalThis[Symbol.for("domma.media-picker")]=t.mediaPicker);for(const[e,{enabled:a,displayName:o}]of Object.entries(t.tools||{}))a===!1&&(j[`/${e}`]=o);for(const{id:e,href:a}of t.css||[])if(!document.getElementById(e)){const o=document.createElement("link");o.id=e,o.rel="stylesheet",o.href=a,document.head.appendChild(o)}}catch{}}function K(){const t=V();if(!t)return;if($("#topbar-user-name").length){_(r);return}const e={"super-admin":"Super Admin",admin:"Admin",user:"User"}[t.role]||t.role,a=Dt(t);$("#topbar-user").get(0).innerHTML=`
|
|
2
2
|
<a id="topbar-project" class="topbar-action-link topbar-project" hidden>
|
|
3
3
|
<span data-icon="folder"></span>
|
|
4
4
|
<span id="topbar-project-name" class="topbar-project-name"></span>
|
|
@@ -51,4 +51,4 @@ import{wireNotificationMenu as tt}from"./lib/topbar-notifications.js";import{ins
|
|
|
51
51
|
</a>
|
|
52
52
|
</div>
|
|
53
53
|
</div>
|
|
54
|
-
`;const o=$("#topbar-settings").get(0);o&&(o.hidden=!v),$("#topbar-logout-btn").on("click",n=>{n.preventDefault(),
|
|
54
|
+
`;const o=$("#topbar-settings").get(0);o&&(o.hidden=!v),$("#topbar-logout-btn").on("click",n=>{n.preventDefault(),rt()}),Domma.icons.scan("#admin-topbar"),E.tooltip("#topbar-actions [data-tooltip]",{placement:"bottom"}),gt(t),it({refreshBadge:F,canRead:()=>w!==!1,own:()=>!u}),yt(t),z(),wt(),_(r),F(),g||(g=setInterval(F,3e4))}function h(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}let g=null,B=null;async function F(){if(!(!p()||w===!1))try{const{count:t}=await r.system.notifications.unreadCount(),i=$("#topbar-bell-badge");t>0?i.text(t>99?"99+":String(t)).removeAttr("hidden"):i.attr("hidden","").text("");const e=J.read().chatToasts&&t>0&&(B===null||t>B);if(B=t,t>0&&(G()||e)){const a=await r.system.notifications.list().catch(()=>[]);G()&&St(a),e&&Mt(a)}}catch{}}(async()=>{if(!p()&&!window.location.hash.startsWith("#/reset-password"))window.location.hash.startsWith("#/login")||(window.location.hash=mt(window.location.hash));else{ct(V()?.id);const a=V(),[o]=await Promise.all([a?b():Promise.resolve([]),x()]);if(a){const n=(window.location.hash||"#/").slice(1)||"/",s=N(n);s&&(window.location.hash=`#${s}`),T(o).catch(l=>console.error("[admin] Sidebar failed to load",l)),K()}}const t=R._extractParams.bind(R);R._extractParams=function(a,o){const n=o.indexOf("?");if(n!==-1&&(o=o.slice(0,n)),a.endsWith("/*")){const s=a.slice(0,-2);return o.startsWith(s+"/")?{}:null}return t(a,o)};const i=R._renderNotFound.bind(R);let e="";R._renderNotFound=async function(a){return p()&&e!==a&&(e=a,await x(),R._matchRoute(a).route)?(e="",R._handleRouteChange()):(e="",p()&&$("#admin-sidebar").get(0)?.style.display==="none"?(E.toast("That link goes nowhere - here is your home page.",{type:"warning"}),R.navigate("/")):i(a))},kt(R),R.init({container:"#view-container",routes:L,views:H,default:"/",transitions:{enter:"fadeIn",leave:"fadeOut",duration:150}})})()});
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{chatToastsDue as u,rememberSeen as h}from"./notifications-arrange.js";const c="notifications.chatToastSeen",d="#/launchers/chats";function f(){try{const t=S.get(c);return Array.isArray(t)?t:null}catch{return null}}function y(t){try{S.set(c,t)}catch{}}export function deliverChatToasts(t,{enabled:s=!0}={}){const r=f(),o=s?u(t,{seen:r}):[];for(const e of o){const n=e.data||{},a=n.source==="core:chat"&&n.severity==="warning",l=String(n.body||"").split(`
|
|
2
|
+
`).filter(Boolean)[0]||"";E.toast(l.slice(0,200),{title:String(n.title||"Visitor chat"),type:a?"warning":"info",duration:a?0:15e3,closable:!0,actions:[{label:"Open Chats",primary:!0,closeOnClick:!0,onClick:()=>{location.hash=d}}]})}const i=(t||[]).filter(e=>e?.unread&&String(e.data?.source||"").startsWith("core:chat")).map(e=>e.id);return y(h(r||[],i)),o.length}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fmtDate as s}from"./dates.js";export const SEVERITIES=["critical","warning","info","success"],FILTERS=["all","new",...SEVERITIES],SEVERITY_TONE={critical:"danger",warning:"warn",success:"ok",info:"info"};const
|
|
1
|
+
import{fmtDate as s}from"./dates.js";export const SEVERITIES=["critical","warning","info","success"],FILTERS=["all","new",...SEVERITIES],SEVERITY_TONE={critical:"danger",warning:"warn",success:"ok",info:"info"};const c=(t,e,n=`${e}s`)=>`${t} ${t===1?e:n}`;export function severityOf(t){const e=t?.data?.severity;return SEVERITIES.includes(e)?e:"info"}export function ago(t,e=Date.now()){const n=new Date(t).getTime();if(!Number.isFinite(n))return"";const r=Math.max(0,Math.round((e-n)/1e3));return r<60?"just now":r<3600?`${Math.round(r/60)} min ago`:r<86400?`${c(Math.round(r/3600),"hour")} ago`:r<86400*14?`${c(Math.round(r/86400),"day")} ago`:s(n)}export function arrangeNotifications(t,{filter:e="all",query:n=""}={}){const r=String(n).trim().toLowerCase();return[...t||[]].filter(i=>e==="all"?!0:e==="new"?i.isNew:severityOf(i)===e).filter(i=>!r||[i.data?.title,i.data?.body,i.data?.link].some(o=>String(o||"").toLowerCase().includes(r))).sort((i,o)=>String(o.data?.createdAt||"").localeCompare(String(i.data?.createdAt||"")))}export function filterCounts(t){const e={all:0,new:0,critical:0,warning:0,info:0,success:0};for(const n of t||[])e.all++,n.isNew&&e.new++,e[severityOf(n)]++;return e}export function safeLink(t){const e=String(t||"").trim();return/^https?:\/\/\S+$/i.test(e)||/^#\/\S*$/.test(e)?e:""}export function sourceLabel(t={}){return t.source==="manager"?"from the manager":t.source==="sample"?"sample":t.sourceLabel?String(t.sourceLabel):t.source?String(t.source).startsWith("core:")?"System":String(t.source).split(":")[0]:""}export function notificationRow(t,{now:e=Date.now(),expanded:n=""}={}){const r=t?.data||{},i=severityOf(t),o=String(r.body||""),a=o.replace(/\s+/g," ").trim();return{id:String(t.id),title:String(r.title||"(no title)"),severity:i,severityLabel:i[0].toUpperCase()+i.slice(1),tone:SEVERITY_TONE[i],meta:[r.createdAt?ago(r.createdAt,e):"",sourceLabel(r),/^https?:\/\//i.test(String(r.link||""))?"has a link":"",r.expiresAt&&Date.parse(r.expiresAt)>e?`until ${s(r.expiresAt)}`:""].filter(Boolean).join(" \xB7 "),preview:a.length>140?`${a.slice(0,139)}\u2026`:a,body:o,link:safeLink(r.link),linkTarget:/^#\//.test(safeLink(r.link))?"_self":"_blank",linkText:/^#\//.test(safeLink(r.link))?"Go there \u2192":"Open link \u2197",isNew:!!t.isNew,unread:!!t.unread,open:n===String(t.id),rowCls:[t.unread?"is-unread":"",n===String(t.id)?"is-open":"",`is-${i}`].filter(Boolean).join(" ")}}const l={boot:"at start-up","15m":"every 15 minutes",hourly:"hourly",daily:"daily at 08:00"};export function sourceRow(t,e=Date.now()){const n=t.every?`${l[t.every]||t.every}${t.atBoot&&t.every!=="boot"?" and at start-up":""}`:"as it happens";return{id:String(t.id),label:String(t.label||t.id),description:String(t.description||""),meta:[t.ownerLabel||t.owner,n,t.lastRun?`last run ${ago(t.lastRun,e)}`:""].filter(Boolean).join(" \xB7 "),enabled:!!t.enabled,audience:t.audience||"super-admin",every:t.every||"",lastError:t.lastError?`Last run failed: ${t.lastError}`:""}}export const DESKTOP_LEVELS=["all","warning","critical"],DEFAULT_SETTINGS=Object.freeze({desktop:!1,desktopLevel:"all",signInToasts:!0,chatToasts:!0});export function normaliseSettings(t){const e=t&&typeof t=="object"?t:{},n=DEFAULT_SETTINGS;return{desktop:typeof e.desktop=="boolean"?e.desktop:n.desktop,desktopLevel:DESKTOP_LEVELS.includes(e.desktopLevel)?e.desktopLevel:n.desktopLevel,signInToasts:typeof e.signInToasts=="boolean"?e.signInToasts:n.signInToasts,chatToasts:typeof e.chatToasts=="boolean"?e.chatToasts:n.chatToasts}}export function meetsLevel(t,e="all"){return e==="critical"?t==="critical":e==="warning"?t==="critical"||t==="warning":!0}export function desktopWorthy(t,{seen:e=[],level:n="all",max:r=3}={}){const i=new Set((e||[]).map(String));return[...t||[]].filter(o=>o&&o.unread&&!i.has(String(o.id))&&meetsLevel(severityOf(o),n)).sort((o,a)=>String(o.data?.createdAt||"").localeCompare(String(a.data?.createdAt||""))).slice(-r)}export const CHAT_SOURCES=Object.freeze(["core:chat","core:chat-started","core:chat-declined"]),CHAT_TOAST_RECENT_MS=10*6e4;export function chatToastsDue(t,{seen:e=null,now:n=Date.now(),max:r=3}={}){const i=new Set((e||[]).map(String));return[...t||[]].filter(o=>o&&o.unread&&CHAT_SOURCES.includes(o.data?.source)&&!i.has(String(o.id))).filter(o=>e||n-Date.parse(o.data?.createdAt||0)<CHAT_TOAST_RECENT_MS).sort((o,a)=>String(o.data?.createdAt||"").localeCompare(String(a.data?.createdAt||""))).slice(-r)}export function rememberSeen(t,e,n=200){const r=[...(t||[]).map(String)];for(const i of e||[])r.includes(String(i))||r.push(String(i));return r.slice(-n)}export function desktopPayload(t){const e=t?.data||{},n=severityOf(t),r=String(e.body||"").replace(/\s+/g," ").trim();return{title:String(e.title||"Notification").slice(0,120),options:{body:r.length>240?`${r.slice(0,239)}\u2026`:r,tag:`dcms-notification-${t?.id}`,requireInteraction:n==="critical"}}}
|
|
@@ -76,7 +76,11 @@
|
|
|
76
76
|
<ul>
|
|
77
77
|
<li><strong>Available for chats</strong> - on while this screen is open. That is what tells the bot someone can
|
|
78
78
|
take a chat. Leave the screen or switch it off and, when nobody else is available, visitors are asked for
|
|
79
|
-
their details instead.
|
|
79
|
+
their details instead. Admins get a notification when a visitor starts a chat, asks for a person or leaves a
|
|
80
|
+
message, and when the AI turns a question down. Each can be switched off, or sent to other people, in
|
|
81
|
+
<strong>Notifications</strong> settings (Visitor chat started, Visitor chat, Chat question turned down).
|
|
82
|
+
While the admin is open, each also pops up as a message with an <strong>Open Chats</strong> button, within
|
|
83
|
+
30 seconds; turn <strong>Chat pop-ups</strong> off in the Notifications settings cog for this browser.</li>
|
|
80
84
|
<li>Click a chat to read it; type a reply and press <kbd>Ctrl</kbd>+<kbd>Enter</kbd> (or Send). Once you reply,
|
|
81
85
|
the bot stays quiet in that chat. You can also reply to a chat the bot is handling.</li>
|
|
82
86
|
<li>Right-click a chat (or its ⋮) to <strong>email the visitor</strong>, copy their address, open the page they
|
|
@@ -107,7 +111,9 @@
|
|
|
107
111
|
</ul>
|
|
108
112
|
<p>Switch it off per launcher with <strong>AI answers what the Knowledge does not</strong>. Questions the AI answered
|
|
109
113
|
still go on the Unanswered list, so you can turn the common ones into Knowledge; in the inbox an AI answer is
|
|
110
|
-
marked "Answered by AI".
|
|
114
|
+
marked "Answered by AI". When the AI turns a question down (off-topic, or something your rules forbid, such as
|
|
115
|
+
medical advice), the visitor gets a polite reply and admins get a <strong>Chat question turned down</strong>
|
|
116
|
+
notification with the question. Visitors see a line under the chat saying Della is an AI assistant. What you write in the
|
|
111
117
|
context and rules is sent to Claude with each question, so leave out anything private. Each site has 2,000 AI
|
|
112
118
|
answers a month; past that the bot answers from the Knowledge alone until the next month.</p>
|
|
113
119
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from"../lib/plugin-chrome.js";import{SHAPES as $e,whileLoading as
|
|
1
|
+
import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from"../lib/plugin-chrome.js";import{SHAPES as $e,whileLoading as Ie}from"../lib/loading.js";import{helpPopovers as oe}from"../lib/help-popover.js";import{onceClosed as Pe,openMenuAt as ie,sidebarCount as Oe,viewLifetime as qe}from"../lib/tool-kit.js";import{DEFAULT_SETTINGS as re,FILTERS as L,arrangeNotifications as Ue,filterCounts as _e,normaliseSettings as Be,notificationRow as le,sourceRow as We}from"../lib/notifications-arrange.js";import{desktopPermission as ce,notificationSettings as de,primeSeen as Fe,requestDesktopPermission as He,showTestNotification as je}from"../lib/desktop-notify.js";const pe=/^#\/system\/notifications\/?(\?.*)?$/,Ge="#/system/notifications",W="notifications.filter",Ke=`
|
|
2
2
|
<div class="ntx-row" data-id="{{id}}" tabindex="0" data-bind-class="rowCls" data-bind-aria-expanded="open ? 'true' : 'false'">
|
|
3
3
|
<span class="ntx-dot" aria-hidden="true"></span>
|
|
4
4
|
<span class="ntx-main">
|
|
@@ -29,9 +29,9 @@ import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from
|
|
|
29
29
|
<button type="button" class="btn btn-sm btn-ghost ntx-src-run" data-bind-hidden="!every">Run now</button>
|
|
30
30
|
</div>
|
|
31
31
|
<small class="ntx-src-err" data-bind-hidden="!lastError">{{lastError}}</small>
|
|
32
|
-
</div>`,R={granted:"Allowed in this browser.",default:"Your browser will ask for permission when you turn this on.",denied:"Blocked in this browser. Allow notifications for this site in the browser's site settings (the icon by the address), then turn this on.",unsupported:"This browser cannot show desktop notifications here - they need a current browser and an https address."};function Je(r){const
|
|
32
|
+
</div>`,R={granted:"Allowed in this browser.",default:"Your browser will ask for permission when you turn this on.",denied:"Blocked in this browser. Allow notifications for this site in the browser's site settings (the icon by the address), then turn this on.",unsupported:"This browser cannot show desktop notifications here - they need a current browser and an https address."};function Je(r){const l=document.createElement("template");return l.innerHTML=r.trim(),l.content.firstElementChild}const d=qe(pe);async function b(){Oe(Ge);try{const{count:r}=await k.system.notifications.unreadCount(),l=$("#topbar-bell-badge");r>0?l.text(r>99?"99+":String(r)).removeAttr("hidden"):l.attr("hidden","").text("")}catch{}}export const notificationsView={templateUrl:"/admin/js/templates/notifications.html",async onMount(r){d.reset();const l=r.get(0).querySelector(".ntx")||r.get(0),y=()=>pe.test(location.hash)&&l.isConnected,i=M.observable([]),T=M.observable(!0),N=M.observable("");let F="all";try{F=L.includes(S.get(W))?S.get(W):"all"}catch{}const C=()=>new URLSearchParams(location.hash.split("?")[1]||"").get("type"),h=M.observable(L.includes(C())?C():F),H=()=>{y()&&L.includes(C())&&(h.value=C())},j=e=>{y()&&L.includes(e.detail?.type)&&(h.value=e.detail.type)};document.addEventListener("dm:notifications-filter",j),d.add(()=>document.removeEventListener("dm:notifications-filter",j)),window.addEventListener("hashchange",H),d.add(()=>window.removeEventListener("hashchange",H));const G=()=>{y()&&x({markRead:!1})};document.addEventListener("dm:notifications-changed",G),d.add(()=>document.removeEventListener("dm:notifications-changed",G));const K=M.observable(""),A=M.observable("");d.add(M.effect(()=>{const e=h.value;try{S.set(W,e)}catch{}}));const Y=M.computed(()=>_e(i.value));d.add(M.effect(()=>{const e=Y.value;!T.value&&h.peek()==="new"&&!e.new&&(h.value="all")}));const z=M.observable([]);d.add(M.effect(()=>{const e=Date.now(),t=A.value;z.value=Ue(i.value,{filter:h.value,query:K.value}).map(n=>le(n,{now:e,expanded:t}))}));const ue=M.computed(()=>i.value.length?"No notifications match.":"No notifications - you're all caught up."),p=M.observable(de.read());d.add(M.effect(()=>de.write(p.value)));const D=(e,t)=>{p.value=Be({...p.peek(),[e]:t})},J=e=>i.peek().find(t=>String(t.id)===String(e)),he=(e,t)=>{i.value=i.peek().map(n=>String(n.id)===String(e)?t(n):n)},V=e=>{i.value=i.peek().filter(t=>String(t.id)!==String(e))};async function x({markRead:e=!0}={}){try{const t=i.peek().length?null:l.querySelector(".dm-loading-slot"),n=await Ie(t,k.system.notifications.list(),$e.iconRows);if(!y())return;const u=Array.isArray(n)?n:[];if(i.value=u.map(c=>({...c,isNew:!!c.unread})),N.value="",e&&u.some(c=>c.unread)){if(await f("/system/notifications/read-all",{method:"POST"}).catch(()=>{}),!y())return;i.value=i.peek().map(c=>({...c,unread:!1})),b()}}catch(t){N.value=`Could not load notifications: ${t.message||t}`}finally{T.value=!1}}async function X(e,t){try{t?await k.system.notifications.markRead(e.id):await f(`/system/notifications/${encodeURIComponent(e.id)}/unread`,{method:"POST"}),he(e.id,n=>({...n,unread:!t})),b()}catch(n){E.toast(`Not changed: ${n.message||n}`,{type:"error"})}}async function Q(e){try{await k.system.notifications.dismiss(e.id),V(e.id),b()}catch(t){E.toast(`Could not dismiss it: ${t.message||t}`,{type:"error"})}}async function me(e){if(await E.confirm(`Delete "${Ye(e.data?.title||"this notification")}" for everyone? Dismissing hides it for you only.`))try{await k.system.notifications.remove(e.id),V(e.id),E.toast("Notification deleted.",{type:"success"}),b()}catch(t){E.toast(/403|forbidden|permission/i.test(String(t.message||t))?"Deleting needs the Notifications delete permission - Dismiss hides it for you.":`Could not delete it: ${t.message||t}`,{type:"error"})}}async function fe(){const e=i.peek().length;if(!e){E.toast("Nothing to dismiss.",{type:"info"});return}if(await E.confirm(`Dismiss all ${e} notification${e===1?"":"s"}? They are hidden for you only.`))try{await f("/system/notifications/dismiss-all",{method:"POST"}),i.value=[],b()}catch(t){E.toast(`Could not dismiss them: ${t.message||t}`,{type:"error"})}}async function be(e){const t=e.data||{},n=[t.title,t.body,t.link].filter(Boolean).join(`
|
|
33
33
|
|
|
34
|
-
`);try{await navigator.clipboard.writeText(n),E.toast("Copied.",{type:"success"})}catch{E.toast("Copying is blocked here - select the text instead.",{type:"warning"})}}const P=e=>{
|
|
34
|
+
`);try{await navigator.clipboard.writeText(n),E.toast("Copied.",{type:"success"})}catch{E.toast("Copying is blocked here - select the text instead.",{type:"warning"})}}const P=e=>{A.value=A.peek()===String(e)?"":String(e)};function ye(e){const t=J(e);if(!t)return[];const n=le(t);return[{header:n.title},{label:n.open||A.peek()===n.id?"Close":"Read it",icon:"eye",action:()=>P(e)},...n.link?[n.linkTarget==="_self"?{label:"Go there",icon:"arrow-right",action:()=>{location.hash=n.link}}:{label:"Open link",icon:"external-link",action:()=>window.open(n.link,"_blank","noopener")}]:[],{label:"Copy text",icon:"copy",action:()=>be(t)},t.unread?{label:"Mark as read",icon:"check",action:()=>X(t,!0)}:{label:"Mark as unread",icon:"mail",action:()=>X(t,!1)},{type:"divider"},{label:"Dismiss",icon:"x",action:()=>Q(t)},{label:"Delete for everyone\u2026",icon:"trash",danger:!0,action:()=>me(t)}]}const v=l.querySelector(".ntx-list");v.innerHTML=Ke;const g=e=>()=>{h.value=e},ve=M.applyBindings({items:i,loading:T,loadError:N,filter:h,query:K,rows:z,counts:Y,emptyText:ue},l,{methods:{showAll:g("all"),showNew:g("new"),showCritical:g("critical"),showWarning:g("warning"),showInfo:g("info"),showSuccess:g("success")}});d.add(()=>ve.dispose()),d.add(oe(l,{position:"bottom"}));const ge=E.contextMenu(v,{cursor:"glyph",match:".ntx-row",inherit:!1,density:"compact",items:e=>ye(e.dataset.id)});d.add(()=>ge?.destroy?.());const Z=e=>{const t=e.target.closest(".ntx-row");if(!t)return;const n=e.target.closest(".ntx-kebab");if(n){ie(n);return}e.target.closest("a")||P(t.dataset.id)},ee=e=>{const t=e.target.closest(".ntx-row");if(t){if(e.key==="F10"&&e.shiftKey)e.preventDefault(),ie(t);else if(e.key==="Enter"&&e.target===t)P(t.dataset.id);else if(e.key==="Delete"&&e.target===t){const n=J(t.dataset.id);n&&Q(n)}}};v.addEventListener("click",Z),v.addEventListener("keydown",ee),d.add(()=>{v.removeEventListener("click",Z),v.removeEventListener("keydown",ee)});async function we(){try{const{added:e}=await f("/system/notifications/samples",{method:"POST"});await x({markRead:!1}),b(),E.toast(`${e} sample notifications added.${p.peek().desktop?" They pop up on the desktop within a minute.":""}`,{type:"success"})}catch(e){E.toast(/403|forbidden|permission/i.test(String(e.message||e))?"Adding samples needs the Notifications delete permission.":`Could not add samples: ${e.message||e}`,{type:"error"})}}function ke(){const e=E.slideover({title:"Notifications settings",size:"md",position:"right"}),t=Je(`
|
|
35
35
|
<div class="ntx-panel">
|
|
36
36
|
<div class="ntx-setting-row">
|
|
37
37
|
<label class="form-label" for="ntx-set-desktop" style="margin:0">Desktop notifications
|
|
@@ -59,6 +59,12 @@ import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from
|
|
|
59
59
|
</label>
|
|
60
60
|
<input id="ntx-set-toasts" type="checkbox" class="form-switch" data-model="signInToasts.value">
|
|
61
61
|
</div>
|
|
62
|
+
<div class="ntx-setting-row">
|
|
63
|
+
<label class="form-label" for="ntx-set-chat-toasts" style="margin:0">Chat pop-ups
|
|
64
|
+
<span data-help="While the admin is open, a message pops up when a visitor starts a chat, asks for a person or leaves a message, or when the AI turns a question down - with a button to open Chats. Checked every 30 seconds. Asking for a person stays until you close it."></span>
|
|
65
|
+
</label>
|
|
66
|
+
<input id="ntx-set-chat-toasts" type="checkbox" class="form-switch" data-model="chatToasts.value">
|
|
67
|
+
</div>
|
|
62
68
|
<small class="ntx-panel-meta">Saved in this browser as you change them.</small>
|
|
63
69
|
<div class="ntx-setting-row">
|
|
64
70
|
<label class="form-label" style="margin:0">Sample notifications
|
|
@@ -78,4 +84,4 @@ import{api as k,apiRequest as f}from"../api.js";import{addBannerAction as B}from
|
|
|
78
84
|
<span class="spacer"></span>
|
|
79
85
|
<button type="button" class="btn btn-sm btn-primary" data-on-click="done">Done</button>
|
|
80
86
|
</div>
|
|
81
|
-
</div>`),n=t.querySelector("#ntx-set-desktop"),
|
|
87
|
+
</div>`),n=t.querySelector("#ntx-set-desktop"),u=t.querySelector(".ntx-src-list");u.innerHTML=ze;const c=M.observable([]),O=M.observable([]),q=M.observable(!1),xe=M.effect(()=>{O.value=c.value.map(s=>We(s))}),Se=M.effect(()=>{const s=O.value;setTimeout(()=>s.forEach(a=>{const o=u.querySelector(`.ntx-src[data-id="${CSS.escape(a.id)}"] .ntx-src-aud`);o&&(o.value=a.audience)}),0)}),U=s=>{c.value=c.peek().map(a=>a.id===s.id?s:a)},te=s=>`/system/notifications/sources/${encodeURIComponent(s)}`;f("/system/notifications/sources",{method:"GET"}).then(s=>{c.value=s.sources||[],q.value=!0}).catch(()=>{q.value=!1});async function se(s,a){const o=c.peek().find(w=>w.id===s);try{const{setting:w}=await f(te(s),{method:"PUT",body:JSON.stringify(a)});U({...o,...w})}catch(w){U({...o}),E.toast(`Not saved: ${w.message||w}`,{type:"error"})}}async function Ee(s,a){a.disabled=!0;try{const o=await f(`${te(s)}/run`,{method:"POST"});o.source&&U(o.source),E.toast(o.ok?"Done - anything it found is in the list.":`It failed: ${o.error}`,{type:o.ok?"success":"error"}),await x({markRead:!1}),b()}catch(o){E.toast(`Could not run it: ${o.message||o}`,{type:"error"})}finally{a.disabled=!1}}const ne=s=>{const a=s.target.closest(".ntx-src");a&&(s.target.matches(".ntx-src-on")?se(a.dataset.id,{enabled:s.target.checked}):s.target.matches(".ntx-src-aud")&&se(a.dataset.id,{audience:s.target.value}))},ae=s=>{const a=s.target.closest(".ntx-src-run");a&&Ee(a.closest(".ntx-src").dataset.id,a)};u.addEventListener("change",ne),u.addEventListener("click",ae);const m=M.observable(ce()),Te=M.computed(()=>p.value.desktop&&m.value!=="granted"?`On, but not showing: ${R[m.value]}`:R[m.value]),Ce=M.computed(()=>m.value==="denied"||m.value==="unsupported"?"is-bad":""),Me=M.computed(()=>p.value.desktop&&m.value==="granted"),_=()=>{n.checked=p.peek().desktop};function Ae(){const s=ce();if(s==="unsupported"||s==="denied"){m.value=s,E.toast(R[s],{type:"warning"}),_();return}(s==="granted"?Promise.resolve("granted"):He()).then(async o=>{m.value=o,o==="granted"?(Fe(await k.system.notifications.list().catch(()=>[])),D("desktop",!0),E.toast("Desktop notifications are on for this browser.",{type:"success"})):E.toast(o==="denied"?R.denied:"Not turned on - the browser was not given permission.",{type:"warning"}),_()})}const Le=s=>M.computed({read:()=>p.value[s],write:a=>D(s,a)}),Re={...Object.fromEntries(Object.keys(re).map(s=>[s,Le(s)])),desktop:M.computed({read:()=>p.value.desktop,write:s=>s?Ae():D("desktop",!1)}),permText:Te,permTone:Ce,canTest:Me,sourceRows:O,sourcesShown:q};e.element.appendChild(t);const Ne=oe(t),De=M.applyBindings(Re,t,{methods:{done:()=>e.close(),reset:()=>{p.value={...re},_()},samples:()=>{we()},test:()=>{je()||E.toast("The browser would not show it - check its notification settings.",{type:"warning"})}}});Pe(e,()=>{De.dispose(),Ne(),xe(),Se(),u.removeEventListener("change",ne),u.removeEventListener("click",ae)}),e.open()}B(r,{id:"notifications-settings",icon:"settings",title:"Notifications settings",onClick:ke}),B(r,{id:"notifications-dismiss-all",icon:"check-circle",title:"Dismiss all",onClick:()=>fe()}),B(r,{id:"notifications-refresh",icon:"refresh-cw",title:"Refresh",onClick:()=>{T.value=!0,x()}}),I.scan(l),await x(),y()&&I.scan(l)}};
|
package/docs/DommaFeatures.md
CHANGED
|
@@ -1237,7 +1237,7 @@ The four Tools below were plugins until 0.67.0 and are now part of the CMS. They
|
|
|
1237
1237
|
- The bot (`server/services/chat/matcher.js`, pure): normalises text (accents, contractions, punctuation), drops stop words, stems lightly (bookings/booked/booking -> book), folds synonym groups onto one word (cost/fee/charge -> price, open/hours/close, delivery/shipping/postage, ...), forgives a one-edit typo in words of five letters or more, and weights words by rarity across the Knowledge. A phrasing's score blends how much of the question it covers with how much of the phrasing the question covers, plus a bonus when one contains the other and a nudge per keyword. `answer` (one clear winner over a margin), `suggest` (top three "Did you mean", plus None of these), or `none` (logged as unanswered; after two misses in a row it offers a person). Handover phrases ("talk to a person", "real human", "customer service"), greetings and thanks are recognised first. Confidence Strict / Balanced / Relaxed in the settings cog.
|
|
1238
1238
|
- Storage: four presets - `chat-knowledge`, `chat-sessions`, `chat-messages`, `chat-unanswered` (`CHAT_PRESET_SLUGS`) - declared MongoDB and resolved like the user-data presets (`MONGO_ELIGIBLE_PRESET_SLUGS`, adapterRegistry `resolveUserDataPreset`): MongoDB where the site has a working connection and the files hold none of their rows, files otherwise; the storage block survives the reseed. Through the generic collections API, views, forms and endpoints they need `chats.manage` (collectionAccess `CORE_TOOL_COLLECTIONS`). Four example Knowledge entries (marked `sample`, removable in one click) are added once per site (`config/chat.json` `examplesSeeded`).
|
|
1239
1239
|
- Visitor API `/api/chat/*` (`config`, `state` poll, `send`, `pick`, `person`, `details`, `end`): 404 unless `launcher` names an enabled chat launcher (`services/chat/launcher-bridge.js` asks `services/launchers.js` `chatLaunchers()`; the launcher's chat settings are always read server-side). The chat is the visitor's by a random 256-bit token in the `X-Chat-Token` header (only its SHA-256 is stored; kept in the browser as `chat:<launcherId>`); resumable for a day, two weeks after leaving a message. Plain text, 1000 characters, 300 messages a chat; per-route rate limits; per address 6 new chats and 120 messages an hour, and `maxNewChatsPerHour` (300) new chats for the whole site; a honeypot, a missing `_t` or a first message within 1.5s is dropped quietly; details only where the launcher asks and the chat was offered the form (else 403); a bot answer is stored as its Knowledge id plus a 200-character snapshot; messages are numbered within the chat and choices offered by position, so no internal id reaches the browser. Answers render through a strict sanitiser (paragraphs, lists, emphasis, code, http(s)/mailto/tel/site-path links).
|
|
1240
|
-
- Hand-over: with staff available (the Chats screen open and Available on - memory presence, 75s) the chat goes to `waiting` and staff are notified (source `core:chat`, admins); with nobody available the visitor leaves name and email (`message`) unless the launcher says never; `askDetails: always` asks before putting them through. A staff reply makes it `open` and the bot stays quiet. Hourly tidy-up closes quiet chats (bot 2h, waiting/open 24h) and deletes ended ones after `retentionDays` (90) - bot-only chats with no details after 7 days - with their messages and any orphan messages, one write per collection (adapters' `removeMany`). Chats in memory are an LRU of 2000; unknown tokens are remembered for a minute. A Launchers module that is missing refuses every chat.
|
|
1240
|
+
- Hand-over: with staff available (the Chats screen open and Available on - memory presence, 75s) the chat goes to `waiting` and staff are notified (source `core:chat`, admins); a visitor's first message notifies admins too (`core:chat-started`, one per chat), and so does a question the AI turned down (`core:chat-declined`, one per chat, said again in place: the Manager's launcher-chat answer carries `declined: true` when Claude's reply starts `DECLINED:`, which it strips); open admins get these as toasts with an Open Chats button (lib/chat-toast.js: the bell's poll, now every 30s, fetches the list when the unread count rises; per-browser "Chat pop-ups" setting, on by default; "wants a person" stays until closed); with nobody available the visitor leaves name and email (`message`) unless the launcher says never; `askDetails: always` asks before putting them through. A staff reply makes it `open` and the bot stays quiet. Hourly tidy-up closes quiet chats (bot 2h, waiting/open 24h) and deletes ended ones after `retentionDays` (90) - bot-only chats with no details after 7 days - with their messages and any orphan messages, one write per collection (adapters' `removeMany`). Chats in memory are an LRU of 2000; unknown tokens are remembered for a minute. A Launchers module that is missing refuses every chat.
|
|
1241
1241
|
- Admin: **Content > Chats** (`#/launchers/chats`, `#/launchers/chats/:id`) - the inbox, waiting first, the live thread (3s poll), replies with per-chat drafts, end/delete/email in a context menu, Available switch, settings cog; sidebar badge `/api/chats/_count` (live while someone waits, red after 5 minutes). **Chats > Knowledge** (`#/launchers/knowledge`) - entries with an editor slideover (question, other ways of asking, keywords, Markdown answer, up to five buttons, on/off), Try the bot with scores, and the Unanswered list (Make an entry, add to the closest entry, dismiss). Visitor panel `public/js/launcher-chat.mjs` `mountChat(container, {launcherId, title, chat})` + `public/css/launcher-chat.css`, domma-reactive.
|
|
1242
1242
|
- Permission `chats` (`read`, `reply`, `manage`) in the Tools group; Admin is granted it once. All of it is behind the Launchers switch.
|
|
1243
1243
|
- AI Assist (unreleased): the paid `ai-assist` Tool (Pro plan) calls `hooks.enableAiAssist()` (`services/aiAssist.js`, paid + closedSource only, off when the Tool is disabled). Without it `aiAvailable()` is false (chat config says `ai: false`, nothing is asked) and the admin assistant is unavailable (`requestAdminAnswer` 403). `GET /api/launchers/items` says `aiAssist`, and the launcher editor notes under AI answers when it is off. The Manager checks the `ai-assist` licence (no longer the Site Builder's).
|
package/package.json
CHANGED
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
* That asymmetry is preserved rather than tidied - changing who can see a group
|
|
12
12
|
* is a behaviour change, and this was a relocation. A test pins it so the next
|
|
13
13
|
* reader finds it stated rather than inferred.
|
|
14
|
+
* The one exception is a `contacts-restricted` person (RESTRICTED below), who
|
|
15
|
+
* sees and uses only the groups they created.
|
|
14
16
|
*
|
|
15
17
|
* Because a group is shared, renaming or deleting one rewrites every user's
|
|
16
18
|
* contacts. So only the group's creator (`meta.createdBy`, recorded on new
|
|
@@ -33,7 +35,7 @@ import {registerToolTrash, trashToolEntry} from '../../services/tool-trash.js';
|
|
|
33
35
|
import {authenticate as defaultAuthenticate, requirePermission as defaultRequirePermission} from '../../middleware/auth.js';
|
|
34
36
|
import {createEntry, deleteEntry, getEntry, listEntries, updateEntry} from '../../services/collections.js';
|
|
35
37
|
import {hooks} from '../../services/hooks.js';
|
|
36
|
-
import {getPermissionsFor} from '../../services/roles.js';
|
|
38
|
+
import {getPermissionsFor, getPermissionsForRole, getRoleLevel} from '../../services/roles.js';
|
|
37
39
|
import {getEffectiveRoles} from '../../services/userRoles.js';
|
|
38
40
|
import {ago, clip, plural} from '../../services/sidebarBadges.js';
|
|
39
41
|
|
|
@@ -59,6 +61,44 @@ function defaultHoldsManageGroups(request) {
|
|
|
59
61
|
return getEffectiveRoles(request.user).some(r => allowed.includes(r));
|
|
60
62
|
}
|
|
61
63
|
|
|
64
|
+
/**
|
|
65
|
+
* `contacts-restricted`: Contacts for a person's own address book and nothing
|
|
66
|
+
* more - for outside accounts such as a Job Board candidate or hiring company.
|
|
67
|
+
* Groups are shared on the site, so a restricted person sees, uses and counts
|
|
68
|
+
* only the groups they created themselves, and can put a contact only in one
|
|
69
|
+
* of those. Someone else's group is "not found" to them. Contacts Pro reads
|
|
70
|
+
* the same permission for its own surfaces (people list, sharing, fields).
|
|
71
|
+
*/
|
|
72
|
+
export const RESTRICTED = 'contacts-restricted';
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The rule, pure (the lookups are passed in) - the same as Docs' docs-restricted:
|
|
76
|
+
* restricted when a role held carries the mark and no role held opens Contacts
|
|
77
|
+
* without it. A level-0 role is never restricted.
|
|
78
|
+
*
|
|
79
|
+
* @param {string[]} roles - every role the person holds
|
|
80
|
+
* @param {{isRoot: Function, marked: Function, givesContacts: Function}} look
|
|
81
|
+
* @returns {boolean}
|
|
82
|
+
*/
|
|
83
|
+
export function contactsRestricted(roles, {isRoot, marked, givesContacts}) {
|
|
84
|
+
const list = (Array.isArray(roles) ? roles : []).filter(r => typeof r === 'string' && r);
|
|
85
|
+
if (!list.length || list.some(isRoot)) return false;
|
|
86
|
+
if (!list.some(marked)) return false;
|
|
87
|
+
return !list.some(r => givesContacts(r) && !marked(r));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Is the caller restricted? A lookup that throws restricts (fail closed). */
|
|
91
|
+
function defaultIsRestricted(request) {
|
|
92
|
+
if (!request.user) return false;
|
|
93
|
+
try {
|
|
94
|
+
return contactsRestricted(getEffectiveRoles(request.user), {
|
|
95
|
+
isRoot: (r) => getRoleLevel(r) === 0,
|
|
96
|
+
marked: (r) => getPermissionsForRole(r).some(p => p === RESTRICTED || String(p).startsWith(`${RESTRICTED}.`)),
|
|
97
|
+
givesContacts: (r) => getPermissionsFor('contacts', 'read').includes(r)
|
|
98
|
+
});
|
|
99
|
+
} catch { return true; }
|
|
100
|
+
}
|
|
101
|
+
|
|
62
102
|
const CONTACTS_SLUG = 'contacts-contacts';
|
|
63
103
|
const GROUPS_SLUG = 'contacts-groups';
|
|
64
104
|
|
|
@@ -114,6 +154,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
114
154
|
const authenticate = opts.authenticate || defaultAuthenticate;
|
|
115
155
|
const requirePermission = opts.requirePermission || defaultRequirePermission;
|
|
116
156
|
const holdsManageGroups = opts.holdsManageGroups || defaultHoldsManageGroups;
|
|
157
|
+
const isRestricted = opts.isRestricted || defaultIsRestricted;
|
|
117
158
|
|
|
118
159
|
registerToolTrash(fastify, {slug: CONTACTS_SLUG, resource: 'contacts', itemPath: '/contacts', authenticate, requirePermission, project: toContact, onPurge: entry => hooks.emit('contact:deleted', {id: entry.id, userId: entry.data.userId})});
|
|
119
160
|
|
|
@@ -133,6 +174,21 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
133
174
|
return entries.map(e => ({id: e.id, name: toGroupName(e), createdBy: e.meta?.createdBy ?? null}));
|
|
134
175
|
}
|
|
135
176
|
|
|
177
|
+
/** The groups this caller sees: every group, or a restricted person's own. */
|
|
178
|
+
async function visibleGroups(request) {
|
|
179
|
+
const groups = await loadGroups();
|
|
180
|
+
if (!isRestricted(request)) return groups;
|
|
181
|
+
const uid = userId(request);
|
|
182
|
+
return groups.filter(g => uid && g.createdBy === uid);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A contact's `groups` as this caller may set them: a restricted person's own groups only. */
|
|
186
|
+
async function allowedGroups(request, contact) {
|
|
187
|
+
if (!Array.isArray(contact.groups) || !contact.groups.length || !isRestricted(request)) return contact;
|
|
188
|
+
const mine = new Set((await visibleGroups(request)).map(g => g.name));
|
|
189
|
+
return {...contact, groups: contact.groups.filter(g => mine.has(g))};
|
|
190
|
+
}
|
|
191
|
+
|
|
136
192
|
/**
|
|
137
193
|
* May this caller rename or delete this group? Its creator may; so may
|
|
138
194
|
* anyone holding contacts.manageGroups. A group from before creators were
|
|
@@ -141,7 +197,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
141
197
|
function canManageGroup(request, group) {
|
|
142
198
|
const uid = userId(request);
|
|
143
199
|
if (uid && group.createdBy && group.createdBy === uid) return true;
|
|
144
|
-
return holdsManageGroups(request) === true;
|
|
200
|
+
return !isRestricted(request) && holdsManageGroups(request) === true;
|
|
145
201
|
}
|
|
146
202
|
|
|
147
203
|
const NOT_YOURS = 'Only the person who created this group, or someone allowed to manage every group, can rename or delete it.';
|
|
@@ -152,7 +208,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
152
208
|
|
|
153
209
|
/** GET /api/contacts/count - the sidebar badge (contactsBadge). */
|
|
154
210
|
fastify.get('/count', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request) => {
|
|
155
|
-
const [contacts, groups] = await Promise.all([loadContacts(userId(request)),
|
|
211
|
+
const [contacts, groups] = await Promise.all([loadContacts(userId(request)), visibleGroups(request)]);
|
|
156
212
|
return contactsBadge(contacts, groups.length);
|
|
157
213
|
});
|
|
158
214
|
|
|
@@ -191,7 +247,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
191
247
|
return reply.code(400).send({ error: 'name is required' });
|
|
192
248
|
}
|
|
193
249
|
|
|
194
|
-
const entry = await createEntry(CONTACTS_SLUG, buildContact(body, uid),
|
|
250
|
+
const entry = await createEntry(CONTACTS_SLUG, await allowedGroups(request, buildContact(body, uid)),
|
|
195
251
|
{createdBy: uid, source: 'admin'});
|
|
196
252
|
|
|
197
253
|
return reply.code(201).send(toContact(entry));
|
|
@@ -210,7 +266,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
210
266
|
// Coerced exactly as create (buildContact) does: the editor sends
|
|
211
267
|
// payment terms as the input's string and a PUT used to store "30"
|
|
212
268
|
// where a POST stores 30 - and a bare `favourite: "false"` was truthy.
|
|
213
|
-
const shaped = buildContact({...entry.data, ...updates}, entry.data.userId ?? null);
|
|
269
|
+
const shaped = await allowedGroups(request, buildContact({...entry.data, ...updates}, entry.data.userId ?? null));
|
|
214
270
|
const merged = {...entry.data};
|
|
215
271
|
for (const key of TEXT_FIELDS) {
|
|
216
272
|
if (key in updates) merged[key] = shaped[key];
|
|
@@ -280,7 +336,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
280
336
|
|
|
281
337
|
/** GET /api/contacts/groups */
|
|
282
338
|
fastify.get('/groups', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request, reply) => {
|
|
283
|
-
const groups = await
|
|
339
|
+
const groups = await visibleGroups(request);
|
|
284
340
|
return reply.send(groups.map(g => g.name));
|
|
285
341
|
});
|
|
286
342
|
|
|
@@ -291,8 +347,8 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
291
347
|
*/
|
|
292
348
|
fastify.get('/groups/access', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request, reply) => {
|
|
293
349
|
const uid = userId(request);
|
|
294
|
-
const manageAll = holdsManageGroups(request) === true;
|
|
295
|
-
const groups = await
|
|
350
|
+
const manageAll = !isRestricted(request) && holdsManageGroups(request) === true;
|
|
351
|
+
const groups = await visibleGroups(request);
|
|
296
352
|
return reply.send({
|
|
297
353
|
manageAll,
|
|
298
354
|
groups: groups.map(g => {
|
|
@@ -331,7 +387,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
331
387
|
}
|
|
332
388
|
|
|
333
389
|
const groups = await loadGroups();
|
|
334
|
-
const grpEntry =
|
|
390
|
+
const grpEntry = (await visibleGroups(request)).find(g => g.name === oldName);
|
|
335
391
|
if (!grpEntry) return reply.code(404).send({error: 'Group not found'});
|
|
336
392
|
if (!canManageGroup(request, grpEntry)) return reply.code(403).send({error: NOT_YOURS});
|
|
337
393
|
|
|
@@ -362,8 +418,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
362
418
|
fastify.delete('/groups/:name', {preHandler: [authenticate, requirePermission('contacts', 'delete')]}, async (request, reply) => {
|
|
363
419
|
const name = decodeURIComponent(request.params.name);
|
|
364
420
|
|
|
365
|
-
const
|
|
366
|
-
const grpEntry = groups.find(g => g.name === name);
|
|
421
|
+
const grpEntry = (await visibleGroups(request)).find(g => g.name === name);
|
|
367
422
|
if (!grpEntry) return reply.code(404).send({error: 'Group not found'});
|
|
368
423
|
if (!canManageGroup(request, grpEntry)) return reply.code(403).send({error: NOT_YOURS});
|
|
369
424
|
|
|
@@ -410,7 +465,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
410
465
|
let imported = 0;
|
|
411
466
|
for (const raw of incoming) {
|
|
412
467
|
if (!raw || typeof raw.name !== 'string') continue;
|
|
413
|
-
await createEntry(CONTACTS_SLUG, buildContact(raw, uid), {source: 'import'});
|
|
468
|
+
await createEntry(CONTACTS_SLUG, await allowedGroups(request, buildContact(raw, uid)), {source: 'import'});
|
|
414
469
|
imported++;
|
|
415
470
|
}
|
|
416
471
|
|
|
@@ -82,8 +82,19 @@ async function ask(payload, {env, fetchFn}) {
|
|
|
82
82
|
* @param {{botName: string, aiContext?: string, aiRules?: string, useKnowledge?: boolean}} chat - the launcher's chat block
|
|
83
83
|
* @returns {Promise<string>} the answer, or '' (no answer: carry on without)
|
|
84
84
|
*/
|
|
85
|
-
export async function aiAnswer(id, question, chat,
|
|
86
|
-
|
|
85
|
+
export async function aiAnswer(id, question, chat, opts = {}) {
|
|
86
|
+
return (await aiReply(id, question, chat, opts)).text;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* As aiAnswer, and whether the AI turned the question down (off-topic, or the rules forbid it): its polite
|
|
91
|
+
* reply, if any, is still the text. The site tells its admins (conversation.js).
|
|
92
|
+
*
|
|
93
|
+
* @returns {Promise<{text: string, declined: boolean}>}
|
|
94
|
+
*/
|
|
95
|
+
export async function aiReply(id, question, chat, {env = process.env, fetchFn = fetch, log = console} = {}) {
|
|
96
|
+
const none = {text: '', declined: false};
|
|
97
|
+
if (!aiAvailable(env)) return none;
|
|
87
98
|
try {
|
|
88
99
|
const brief = assistantBrief(chat);
|
|
89
100
|
const {byId} = chat.useKnowledge === false ? {byId: new Map()} : await knowledgeIndex();
|
|
@@ -98,13 +109,13 @@ export async function aiAnswer(id, question, chat, {env = process.env, fetchFn =
|
|
|
98
109
|
question
|
|
99
110
|
};
|
|
100
111
|
const {status, body} = await ask(payload, {env, fetchFn});
|
|
101
|
-
if (status === 200) return typeof body?.answer === 'string' ? body.answer.trim() : '';
|
|
112
|
+
if (status === 200) return {text: typeof body?.answer === 'string' ? body.answer.trim() : '', declined: body?.declined === true};
|
|
102
113
|
restUntil = Date.now() + (BACKOFF_MS[status] || BACKOFF_MS.other);
|
|
103
114
|
if (status !== 429) log.warn?.(`[chat] AI answers unavailable (${status}): ${String(body?.error || '').slice(0, 120)}`);
|
|
104
|
-
return
|
|
115
|
+
return none;
|
|
105
116
|
} catch (err) {
|
|
106
117
|
restUntil = Date.now() + BACKOFF_MS.other;
|
|
107
118
|
log.warn?.(`[chat] AI answer failed: ${err.message}`);
|
|
108
|
-
return
|
|
119
|
+
return none;
|
|
109
120
|
}
|
|
110
121
|
}
|
|
@@ -27,9 +27,13 @@ import {
|
|
|
27
27
|
patchSession, removeSession, removeSessionsAndOrphans, renderAnswer, staffAvailable, withChat
|
|
28
28
|
} from './store.js';
|
|
29
29
|
import {readChatSettings, staffDisplayName} from './settings.js';
|
|
30
|
-
import {
|
|
30
|
+
import {aiReply} from './ai.js';
|
|
31
31
|
|
|
32
32
|
export const SOURCE = 'core:chat';
|
|
33
|
+
/** A visitor started a chat (their first message). */
|
|
34
|
+
export const STARTED_SOURCE = 'core:chat-started';
|
|
35
|
+
/** The AI turned a visitor's question down (off-topic, or the launcher's rules forbid it). */
|
|
36
|
+
export const DECLINED_SOURCE = 'core:chat-declined';
|
|
33
37
|
const int = (v) => (Number.isFinite(Number(v)) ? Math.trunc(Number(v)) : 0);
|
|
34
38
|
const ACTIVE = ['waiting', 'open', 'message'];
|
|
35
39
|
|
|
@@ -60,6 +64,16 @@ export function registerChatSource() {
|
|
|
60
64
|
description: 'A visitor asked to talk to a person, or left a message for the team because nobody was available.',
|
|
61
65
|
severity: 'info', audience: 'admins'
|
|
62
66
|
});
|
|
67
|
+
registerNotificationSource({
|
|
68
|
+
id: STARTED_SOURCE, owner: 'core', label: 'Visitor chat started',
|
|
69
|
+
description: 'A visitor started a chat, whether the bot or a person answers it.',
|
|
70
|
+
severity: 'info', audience: 'admins'
|
|
71
|
+
});
|
|
72
|
+
registerNotificationSource({
|
|
73
|
+
id: DECLINED_SOURCE, owner: 'core', label: 'Chat question turned down',
|
|
74
|
+
description: 'The AI turned down a visitor\'s question in chat: off-topic, or something the launcher\'s rules forbid.',
|
|
75
|
+
severity: 'info', audience: 'admins'
|
|
76
|
+
});
|
|
63
77
|
}
|
|
64
78
|
|
|
65
79
|
const noticeKey = (id) => `chat:${id}`;
|
|
@@ -77,6 +91,27 @@ function raise(session, kind) {
|
|
|
77
91
|
|
|
78
92
|
const settle = (id) => resolveNotification(noticeKey(id), SOURCE).catch(() => 0);
|
|
79
93
|
|
|
94
|
+
/** What the admins are told about the chat: the visitor's words (as the Chats screen shows them) and the page. */
|
|
95
|
+
const quoted = (text) => `"${cleanText(text, 200).replace(/\n/g, ' ')}"`;
|
|
96
|
+
|
|
97
|
+
/** A visitor's first message: the chat has started. */
|
|
98
|
+
function raiseStarted(session, text, chat) {
|
|
99
|
+
const d = session.data;
|
|
100
|
+
const where = d.page ? `\nPage: ${d.page}` : '';
|
|
101
|
+
const who = chat.bot ? `${chat.botName || 'The bot'} is answering.` : 'It is waiting for a person.';
|
|
102
|
+
return notify({severity: 'info', title: `${d.visitorName || 'A visitor'} started a chat`, body: `${quoted(text)}\n\n${who}${where}`,
|
|
103
|
+
source: STARTED_SOURCE, dedupeKey: `chat-started:${session.id}`, link: '#/launchers/chats'}).catch(() => null);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The AI turned a question down. One notice per chat, said again in place for the next. */
|
|
107
|
+
function raiseDeclined(session, text, chat) {
|
|
108
|
+
const d = session.data;
|
|
109
|
+
const where = d.page ? `\nPage: ${d.page}` : '';
|
|
110
|
+
return notify({severity: 'info', title: `${chat.botName || 'The bot'} turned down a question in chat`,
|
|
111
|
+
body: `${d.visitorName || 'A visitor'} asked: ${quoted(text)}\n\nIt is off-topic or against the launcher's rules, so it was not answered.${where}`,
|
|
112
|
+
source: DECLINED_SOURCE, dedupeKey: `chat-declined:${session.id}`, link: '#/launchers/chats'}).catch(() => null);
|
|
113
|
+
}
|
|
114
|
+
|
|
80
115
|
// ---------------------------------------------------------------------------
|
|
81
116
|
// What visitors and staff see
|
|
82
117
|
// ---------------------------------------------------------------------------
|
|
@@ -168,7 +203,8 @@ async function aiTurn(id, text, chat, session) {
|
|
|
168
203
|
if (!chat.ai) return null;
|
|
169
204
|
const used = int(session?.data.aiCount);
|
|
170
205
|
if (used >= int(chat.aiMaxPerChat ?? 20)) return null;
|
|
171
|
-
const said = await
|
|
206
|
+
const {text: said, declined} = await aiReply(id, text, chat);
|
|
207
|
+
if (declined && session) raiseDeclined(session, text, chat);
|
|
172
208
|
return said ? addMessage(id, {from: 'bot', text: said, ai: true}, {misses: 0, aiCount: used + 1}) : null;
|
|
173
209
|
}
|
|
174
210
|
|
|
@@ -251,6 +287,8 @@ export function visitorSays(id, text, chat) {
|
|
|
251
287
|
if (full(session)) return {error: SAY.full, code: 409};
|
|
252
288
|
const staffSide = ACTIVE.includes(session.data.status);
|
|
253
289
|
const wrote = await addMessage(id, {from: 'visitor', text: clean}, staffSide ? {unread: int(session.data.unread) + 1} : {});
|
|
290
|
+
// The first thing the visitor says starts the chat (the summary is set from it).
|
|
291
|
+
if (!session.data.summary && wrote?.session) raiseStarted(wrote.session, clean, chat);
|
|
254
292
|
if (!staffSide) {
|
|
255
293
|
if (chat.bot) await botReply(id, clean, chat, readChatSettings());
|
|
256
294
|
else await handoverNow(id, chat);
|
|
@@ -216,6 +216,17 @@ export const REGISTRY = [
|
|
|
216
216
|
{key: 'manageGroups', label: 'Manage groups', description: 'Rename or delete any group, not only the ones they created - groups are shared, so this changes everyone\'s contacts'}
|
|
217
217
|
]
|
|
218
218
|
},
|
|
219
|
+
{
|
|
220
|
+
// routes/api/contacts.js RESTRICTED; Contacts Pro reads it too. For outside accounts (a Job Board's).
|
|
221
|
+
key: 'contacts-restricted',
|
|
222
|
+
label: 'Contacts: own address book only',
|
|
223
|
+
description: 'A role with this uses Contacts for its own address book and nothing more: only the groups it made, no list of people, no sharing, no shared fields. It changes nothing for a person who also holds a role that gives Contacts without it, and nothing for the top (level-0) role.',
|
|
224
|
+
icon: 'lock',
|
|
225
|
+
group: 'Tools',
|
|
226
|
+
actions: [
|
|
227
|
+
{key: 'on', label: 'Restricted', description: 'Own contacts and own groups only'}
|
|
228
|
+
]
|
|
229
|
+
},
|
|
219
230
|
{
|
|
220
231
|
// Instant calls (services/instantCalls.js). Only in use while a Pro Tool with calls
|
|
221
232
|
// (Booking Pro, Contacts Pro, Calendar) is running; admins are granted it then, once.
|