Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fae25c11a6 | ||
|
|
b55b8d2d86 | ||
|
|
dbb58e6e94 | ||
|
|
3d89eb3118 | ||
|
|
e70051f912 | ||
|
|
0073b41333 | ||
|
|
d4a2646786 | ||
|
|
48896d1958 | ||
|
|
417af36227 | ||
|
|
55ae666f01 | ||
|
|
ff39d3f452 | ||
|
|
c17d2f4bf3 | ||
|
|
12babb9b88 | ||
|
|
c7bc7a8dcb | ||
|
|
a0da31f0da | ||
|
|
e3d7b7ec4c | ||
|
|
be74080492 | ||
|
|
c346f43f0e | ||
|
|
7cd2972a70 |
No files matched your search
@@ -47,6 +47,13 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check the Kubernetes manifests
|
||||
# Proves each manifest rule still fires, then checks the prod overlay (openspec spec cluster-deployment).
|
||||
# Cluster-fact placeholders are allowed here; deploy/check.sh --release refuses them before a real apply.
|
||||
run: |
|
||||
sh deploy/check.sh --self-test
|
||||
sh deploy/check.sh
|
||||
|
||||
- name: Build and test the services
|
||||
run: |
|
||||
mvn -T 1C -B -Dmaven.repo.local=/root/.m2/repository-co-lite verify \
|
||||
|
||||
@@ -20,3 +20,6 @@ solvway-admin-portal/.impeccable/
|
||||
|
||||
# Build output
|
||||
target/
|
||||
|
||||
# Filled-in Kubernetes secrets (templates: deploy/k8s/secrets.example)
|
||||
deploy/k8s/secrets/
|
||||
@@ -0,0 +1,35 @@
|
||||
# expect: replicas must be 1
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 2
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
@@ -0,0 +1,18 @@
|
||||
# expect: strategy must be Recreate
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
@@ -0,0 +1,18 @@
|
||||
# expect: not 'latest'
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:latest
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
@@ -0,0 +1,90 @@
|
||||
# expect: env JWT_SECRET holds a literal value
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: mobile-api}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: mobile-api}}
|
||||
template:
|
||||
metadata: {labels: {app: mobile-api}}
|
||||
spec:
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: admin-portal, port: 3000}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: whatsapp-webhook}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-log}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: service-log}}
|
||||
template:
|
||||
metadata: {labels: {app: service-log}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-log
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-log:abc1234
|
||||
env:
|
||||
- {name: JWT_SECRET, value: x}
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
@@ -0,0 +1,89 @@
|
||||
# expect: different tags
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: mobile-api}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: mobile-api}}
|
||||
template:
|
||||
metadata: {labels: {app: mobile-api}}
|
||||
spec:
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: admin-portal, port: 3000}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: whatsapp-webhook}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-log}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: service-log}}
|
||||
template:
|
||||
metadata: {labels: {app: service-log}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-log
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-log:def5678
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
@@ -0,0 +1,77 @@
|
||||
# expect: Service type NodePort
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: mobile-api}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: mobile-api}}
|
||||
template:
|
||||
metadata: {labels: {app: mobile-api}}
|
||||
spec:
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: admin-portal, port: 3000}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: whatsapp-webhook}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata: {name: api-gateway}
|
||||
spec: {type: NodePort, ports: [{port: 80}]}
|
||||
@@ -0,0 +1,18 @@
|
||||
# expect: not 'no tag'
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
@@ -0,0 +1,78 @@
|
||||
# expect: still a placeholder: <mysql host>
|
||||
# flags: --release
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: mobile-api}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: mobile-api}}
|
||||
template:
|
||||
metadata: {labels: {app: mobile-api}}
|
||||
spec:
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: admin-portal, port: 3000}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: whatsapp-webhook}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata: {name: co-lite-settings}
|
||||
data: {MYSQLHOST: <mysql host>}
|
||||
@@ -0,0 +1,82 @@
|
||||
# expect: reaches 'api-gateway'
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: mobile-api}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: mobile-api}}
|
||||
template:
|
||||
metadata: {labels: {app: mobile-api}}
|
||||
spec:
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: admin-portal, port: 3000}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: whatsapp-webhook}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: gw}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: api-gateway, port: 80}]
|
||||
@@ -0,0 +1,82 @@
|
||||
# expect: reaches 'mobile-api'
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: mobile-api}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: mobile-api}}
|
||||
template:
|
||||
metadata: {labels: {app: mobile-api}}
|
||||
spec:
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: admin-portal, port: 3000}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: whatsapp-webhook}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: api}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && PathPrefix(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
@@ -0,0 +1,77 @@
|
||||
# expect: Secret with data
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: mobile-api}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: mobile-api}}
|
||||
template:
|
||||
metadata: {labels: {app: mobile-api}}
|
||||
spec:
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: admin-portal, port: 3000}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: whatsapp-webhook}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata: {name: co-lite-shared}
|
||||
data: {JWT_TOKEN: eA==}
|
||||
@@ -0,0 +1,72 @@
|
||||
# expect: pass
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: admin-portal}}
|
||||
template:
|
||||
metadata: {labels: {app: admin-portal}}
|
||||
spec:
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: mobile-api}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: RollingUpdate}
|
||||
selector: {matchLabels: {app: mobile-api}}
|
||||
template:
|
||||
metadata: {labels: {app: mobile-api}}
|
||||
spec:
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: service-counter}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector: {matchLabels: {app: service-counter}}
|
||||
template:
|
||||
metadata: {labels: {app: service-counter}}
|
||||
spec:
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter:abc1234
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: admin-portal}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`)
|
||||
kind: Rule
|
||||
services: [{name: admin-portal, port: 3000}]
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata: {name: whatsapp-webhook}
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.example`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services: [{name: mobile-api, port: 80}]
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/bin/sh
|
||||
# Checks the production manifests (openspec spec cluster-deployment): renders deploy/k8s/overlays/prod, validates it
|
||||
# against the Kubernetes schemas, then applies check_rules.py (public routes, pinned images, no secret data,
|
||||
# one service-counter, all ten services present). Needs only Docker. The deploy folder goes to the container through stdin, so this also works
|
||||
# against a remote Docker daemon (CI's DOCKER_HOST).
|
||||
# deploy/check.sh check the prod overlay
|
||||
# deploy/check.sh --self-test prove every rule fires on its fixture in deploy/check-fixtures
|
||||
# deploy/check.sh --release also refuse any <…> placeholder; run it before every real apply
|
||||
# deploy/check.sh --render print the rendered prod manifests
|
||||
set -eu
|
||||
IMAGE=alpine/k8s:1.33.4@sha256:b0523f0a244ddc4c8e055aa335c040d3d78b3ead5528f4544395f7f9f69c7b68
|
||||
# Traefik's IngressRoute schema comes from the CRDs catalog; Kubernetes' own from kubeconform's default location.
|
||||
CRDS='https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json'
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
in_container() {
|
||||
tar -cf - deploy | docker run --rm -i "$IMAGE" sh -c "set -e; mkdir -p /w && tar -xf - -C /w && cd /w && $1"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
--render)
|
||||
in_container 'kubectl kustomize deploy/k8s/overlays/prod'
|
||||
;;
|
||||
--self-test)
|
||||
in_container '
|
||||
fail=0
|
||||
for f in deploy/check-fixtures/*.yaml; do
|
||||
expect=$(sed -n "1s/^# expect: //p" "$f")
|
||||
flags=$(sed -n "2s/^# flags: //p" "$f")
|
||||
if out=$(python3 -I deploy/check_rules.py $flags < "$f"); then got=pass; else got=$out; fi
|
||||
case "$got" in
|
||||
*"$expect"*) echo "ok $f" ;;
|
||||
*) echo "FAIL $f: expected \"$expect\", got: $got"; fail=1 ;;
|
||||
esac
|
||||
done
|
||||
exit $fail'
|
||||
;;
|
||||
""|--release)
|
||||
in_container "
|
||||
kubectl kustomize deploy/k8s/overlays/prod > /tmp/prod.yaml
|
||||
kubeconform -strict -summary -schema-location default -schema-location '$CRDS' /tmp/prod.yaml
|
||||
python3 -I deploy/check_rules.py --full ${1:-} < /tmp/prod.yaml && echo 'prod manifests: rules passed'"
|
||||
;;
|
||||
*)
|
||||
echo "usage: $0 [--release|--self-test|--render]" >&2; exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Production manifest rules (openspec spec cluster-deployment). Reads rendered multi-document YAML on stdin,
|
||||
prints one line per violation and exits 1 if there is any. Runs inside the pinned alpine/k8s image (deploy/check.sh)."""
|
||||
import re
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
WEBHOOK = "/api/public/whatsapp/webhook"
|
||||
PUBLIC = {"admin-portal"}
|
||||
SECRETISH = re.compile(r"(SECRET|TOKEN|PASSWORD|PWD|KEY|KEYS)$")
|
||||
WORKLOADS = {"Deployment", "StatefulSet", "DaemonSet", "Job", "CronJob"}
|
||||
# The ten images of docs/deployment.md section 1; their Service names are fixed in the gateway's and mobile-api's config.
|
||||
SYSTEM = {"admin-portal", "mobile-api", "api-gateway", "service-auth", "service-system", "service-counter",
|
||||
"service-member", "service-log", "service-email", "service-whatsapp"}
|
||||
|
||||
|
||||
def name(doc):
|
||||
return f"{doc.get('kind')}/{(doc.get('metadata') or {}).get('name')}"
|
||||
|
||||
|
||||
def pod_spec(doc):
|
||||
spec = doc.get("spec") or {}
|
||||
if doc.get("kind") == "CronJob":
|
||||
spec = ((spec.get("jobTemplate") or {}).get("spec") or {})
|
||||
return ((spec.get("template") or {}).get("spec") or {})
|
||||
|
||||
|
||||
def check_route(doc, out):
|
||||
for route in (doc.get("spec") or {}).get("routes") or []:
|
||||
match = route.get("match", "")
|
||||
for svc in route.get("services") or []:
|
||||
target = svc.get("name")
|
||||
if target in PUBLIC:
|
||||
continue
|
||||
exact = f"Path(`{WEBHOOK}`)" in match and "PathPrefix" not in match and "||" not in match
|
||||
if target == "mobile-api" and exact:
|
||||
continue
|
||||
out.append(f"{name(doc)}: route '{match}' reaches '{target}'; only admin-portal and mobile-api's exact {WEBHOOK} may be public")
|
||||
|
||||
|
||||
def check_images(doc, out):
|
||||
spec = pod_spec(doc)
|
||||
for c in (spec.get("containers") or []) + (spec.get("initContainers") or []):
|
||||
image = c.get("image", "")
|
||||
if "@sha256:" in image:
|
||||
continue
|
||||
last = image.rsplit("/", 1)[-1]
|
||||
tag = last.split(":", 1)[1] if ":" in last else ""
|
||||
if tag in ("", "latest"):
|
||||
out.append(f"{name(doc)}: image '{image}' must be pinned to a commit SHA, not '{tag or 'no tag'}'")
|
||||
elif "co-lite-" in last and not re.fullmatch(r"[0-9a-f]{7,40}", tag):
|
||||
out.append(f"{name(doc)}: image '{image}' tag must be a commit SHA")
|
||||
|
||||
|
||||
def check_env(doc, out):
|
||||
spec = pod_spec(doc)
|
||||
for c in (spec.get("containers") or []) + (spec.get("initContainers") or []):
|
||||
for env in c.get("env") or []:
|
||||
if SECRETISH.search(env.get("name", "")) and "value" in env:
|
||||
out.append(f"{name(doc)}: env {env['name']} holds a literal value; take it from a Secret")
|
||||
|
||||
|
||||
def complete(docs):
|
||||
out = []
|
||||
for kind in ("Deployment", "Service"):
|
||||
have = {(d.get("metadata") or {}).get("name") for d in docs if d.get("kind") == kind}
|
||||
out += [f"{kind}/{n}: missing from the manifests" for n in sorted(SYSTEM - have)]
|
||||
return out
|
||||
|
||||
|
||||
def placeholders(docs):
|
||||
"""Before a real apply every <…> cluster fact must be filled in (deploy/check.sh --release)."""
|
||||
out = []
|
||||
|
||||
def walk(doc, value, path):
|
||||
if isinstance(value, dict):
|
||||
for k, v in value.items():
|
||||
walk(doc, v, f"{path}.{k}")
|
||||
elif isinstance(value, list):
|
||||
for i, v in enumerate(value):
|
||||
walk(doc, v, f"{path}[{i}]")
|
||||
elif isinstance(value, str) and re.search(r"<[^<>]+>", value):
|
||||
out.append(f"{name(doc)}: {path.lstrip('.')} is still a placeholder: {value}")
|
||||
|
||||
for doc in docs:
|
||||
walk(doc, doc, "")
|
||||
return out
|
||||
|
||||
|
||||
def rules(docs):
|
||||
out = []
|
||||
shas = {}
|
||||
for doc in docs:
|
||||
kind = doc.get("kind")
|
||||
if kind == "Secret" and (doc.get("data") or doc.get("stringData")):
|
||||
out.append(f"{name(doc)}: Secret with data in the manifests; create it with deploy/create-secrets.sh")
|
||||
if kind in ("Ingress", "IngressRouteTCP", "IngressRouteUDP"):
|
||||
out.append(f"{name(doc)}: {kind} is not allowed; public routes are Traefik IngressRoutes")
|
||||
if kind == "Service" and (doc.get("spec") or {}).get("type", "ClusterIP") != "ClusterIP":
|
||||
out.append(f"{name(doc)}: Service type {doc['spec']['type']} exposes it outside the cluster")
|
||||
if kind == "IngressRoute":
|
||||
check_route(doc, out)
|
||||
if kind in WORKLOADS:
|
||||
check_images(doc, out)
|
||||
check_env(doc, out)
|
||||
for c in pod_spec(doc).get("containers") or []:
|
||||
last = c.get("image", "").rsplit("/", 1)[-1]
|
||||
if last.startswith("co-lite-") and ":" in last:
|
||||
shas.setdefault(last.split(":", 1)[1].split("@")[0], []).append(name(doc))
|
||||
if kind == "Deployment" and doc["metadata"]["name"] == "service-counter":
|
||||
spec = doc.get("spec") or {}
|
||||
if spec.get("replicas", 1) != 1:
|
||||
out.append(f"{name(doc)}: replicas must be 1 (the daily follow-up summary would be sent once per replica)")
|
||||
if (spec.get("strategy") or {}).get("type") != "Recreate":
|
||||
out.append(f"{name(doc)}: strategy must be Recreate so a rollout never runs two copies")
|
||||
if len(shas) > 1:
|
||||
out.append(f"images: co-lite images use different tags {sorted(shas)}; one release is one commit SHA")
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
docs = [d for d in yaml.safe_load_all(sys.stdin) if d]
|
||||
found = rules(docs) + (complete(docs) if "--full" in sys.argv else []) \
|
||||
+ (placeholders(docs) if "--release" in sys.argv else [])
|
||||
for line in found:
|
||||
print(line)
|
||||
sys.exit(1 if found else 0)
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
#!/bin/sh
|
||||
# Creates or updates Co-Lite's Kubernetes Secrets from the filled-in copy of deploy/k8s/secrets.example
|
||||
# (openspec spec cluster-deployment: secrets never enter the repository). Never prints a value.
|
||||
# deploy/create-secrets.sh [--dry-run] [folder] folder defaults to deploy/k8s/secrets
|
||||
# --dry-run checks the folder and lists the Secrets and key names without kubectl.
|
||||
# NAMESPACE (default co-lite) picks the namespace.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
dry=
|
||||
[ "${1:-}" = "--dry-run" ] && { dry=1; shift; }
|
||||
src=${1:-deploy/k8s/secrets}
|
||||
tpl=deploy/k8s/secrets.example
|
||||
ns=${NAMESPACE:-co-lite}
|
||||
optional="co-lite-whatsapp.env"
|
||||
fail() { echo "create-secrets: $*" >&2; exit 1; }
|
||||
[ -d "$src" ] || fail "no folder $src; copy $tpl there and fill it in"
|
||||
|
||||
keys() { sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' "$1"; }
|
||||
value_of() { sed -n "s/^$2=//p" "$1" | head -n 1; }
|
||||
|
||||
# Check everything before creating anything, so a half-filled folder changes nothing.
|
||||
for t in "$tpl"/*.env "$tpl"/*/; do
|
||||
base=$(basename "$t")
|
||||
f="$src/$base"
|
||||
if [ ! -e "$f" ]; then
|
||||
case " $optional " in *" $base "*) continue ;; esac
|
||||
fail "missing $f"
|
||||
fi
|
||||
if [ -d "$t" ]; then
|
||||
for k in "$t"*; do
|
||||
kf="$f/$(basename "$k")"
|
||||
[ -s "$kf" ] || fail "missing or empty $kf"
|
||||
! grep -q '<[^<>]*>' "$kf" || fail "$kf still holds a <…> placeholder"
|
||||
done
|
||||
else
|
||||
for k in $(keys "$t"); do
|
||||
v=$(value_of "$f" "$k")
|
||||
[ -n "$v" ] || fail "$f: $k is missing or empty"
|
||||
case "$v" in *"<"*">"*) fail "$f: $k is still a placeholder" ;; esac
|
||||
done
|
||||
fi
|
||||
done
|
||||
|
||||
apply() { # name, then kubectl create arguments
|
||||
name=$1; shift
|
||||
kubectl create secret "$@" "$name" -n "$ns" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
|
||||
echo "applied Secret $name"
|
||||
}
|
||||
|
||||
if [ -z "$dry" ]; then
|
||||
# The first run comes before the first apply, which is what would otherwise create the namespace.
|
||||
kubectl create namespace "$ns" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
|
||||
fi
|
||||
for f in "$src"/*.env "$src"/*/; do
|
||||
[ -e "$f" ] || continue
|
||||
name=$(basename "$f" .env); name=${name%/}
|
||||
[ -e "$tpl/$(basename "$f")" ] || fail "$f has no template in $tpl"
|
||||
if [ "$name" = co-lite-registry ]; then
|
||||
echo "Secret $name (image pull secret for gitea.containerverse.dev)"
|
||||
[ -n "$dry" ] && continue
|
||||
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
|
||||
auth=$(printf '%s:%s' "$(value_of "$f" REGISTRY_USER)" "$(value_of "$f" REGISTRY_PASSWORD)" | base64 | tr -d '\n')
|
||||
(umask 077; printf '{"auths":{"gitea.containerverse.dev":{"auth":"%s"}}}' "$auth" > "$tmp/config.json")
|
||||
apply "$name" generic --type=kubernetes.io/dockerconfigjson --from-file=.dockerconfigjson="$tmp/config.json"
|
||||
elif [ -d "$f" ]; then
|
||||
echo "Secret $name: $(ls "$f" | tr '\n' ' ')"
|
||||
[ -n "$dry" ] && continue
|
||||
apply "$name" generic --from-file="$f"
|
||||
else
|
||||
echo "Secret $name: $(keys "$f" | tr '\n' ' ')"
|
||||
[ -n "$dry" ] && continue
|
||||
apply "$name" generic --from-env-file="$f"
|
||||
fi
|
||||
done
|
||||
@@ -0,0 +1,41 @@
|
||||
# The only Service routed to as a whole (overlays/prod/routes.yaml). No health endpoint: GET /login answers 200 without a session.
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: admin-portal
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: admin-portal}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: admin-portal}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: admin-portal
|
||||
image: gitea.containerverse.dev/solvway/co-lite-admin-portal
|
||||
ports:
|
||||
- {name: http, containerPort: 3000}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-portal}}
|
||||
- {secretRef: {name: co-lite-admin-portal}}
|
||||
livenessProbe:
|
||||
tcpSocket: {port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /login, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 256Mi}
|
||||
limits: {memory: 512Mi}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: admin-portal
|
||||
spec:
|
||||
selector: {app: admin-portal}
|
||||
ports:
|
||||
- {name: http, port: 3000, targetPort: http}
|
||||
@@ -0,0 +1,51 @@
|
||||
# Routes to http://service-* on port 80; needs only JWT_TOKEN and the mounted appkeys.json (docs/deployment.md 6, 7).
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: api-gateway
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: api-gateway}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: api-gateway}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: api-gateway
|
||||
image: gitea.containerverse.dev/solvway/co-lite-api-gateway
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
env:
|
||||
- name: JWT_TOKEN
|
||||
valueFrom: {secretKeyRef: {name: co-lite-shared, key: JWT_TOKEN}}
|
||||
- name: JAVA_OPTS
|
||||
valueFrom: {configMapKeyRef: {name: co-lite-settings, key: JAVA_OPTS}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 512Mi}
|
||||
limits: {memory: 1Gi}
|
||||
volumeMounts:
|
||||
- {name: appkeys, mountPath: /deployments/appkeys, readOnly: true}
|
||||
volumes:
|
||||
- {name: appkeys, secret: {secretName: co-lite-gateway-appkeys}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: api-gateway
|
||||
spec:
|
||||
selector: {app: api-gateway}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,18 @@
|
||||
# Co-Lite on Kubernetes: one Deployment and one Service per image (docs/deployment.md section 1).
|
||||
# Settings and Secrets are referenced by name only; the prod overlay generates the settings and
|
||||
# deploy/create-secrets.sh creates the Secrets. Images carry no tag here: the overlay pins one commit SHA.
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
labels:
|
||||
- pairs: {app.kubernetes.io/part-of: co-lite}
|
||||
resources:
|
||||
- admin-portal.yaml
|
||||
- api-gateway.yaml
|
||||
- mobile-api.yaml
|
||||
- service-auth.yaml
|
||||
- service-counter.yaml
|
||||
- service-email.yaml
|
||||
- service-log.yaml
|
||||
- service-member.yaml
|
||||
- service-system.yaml
|
||||
- service-whatsapp.yaml
|
||||
@@ -0,0 +1,53 @@
|
||||
# Internal; only its WhatsApp webhook path is public (overlays/prod/routes.yaml).
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: mobile-api
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: mobile-api}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: mobile-api}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: mobile-api
|
||||
image: gitea.containerverse.dev/solvway/co-lite-mobile-api
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-settings}}
|
||||
- {secretRef: {name: co-lite-shared}}
|
||||
- {configMapRef: {name: co-lite-gcp}}
|
||||
- {secretRef: {name: co-lite-mobile-api}}
|
||||
- {configMapRef: {name: co-lite-whatsapp}}
|
||||
- {secretRef: {name: co-lite-whatsapp, optional: true}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 512Mi}
|
||||
limits: {memory: 1Gi}
|
||||
volumeMounts:
|
||||
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
|
||||
volumes:
|
||||
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: mobile-api
|
||||
spec:
|
||||
selector: {app: mobile-api}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,50 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: service-auth
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: service-auth}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: service-auth}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: service-auth
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-auth
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-settings}}
|
||||
- {secretRef: {name: co-lite-shared}}
|
||||
- {configMapRef: {name: co-lite-gcp}}
|
||||
- {secretRef: {name: co-lite-service-auth}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 512Mi}
|
||||
limits: {memory: 1Gi}
|
||||
volumeMounts:
|
||||
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
|
||||
volumes:
|
||||
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: service-auth
|
||||
spec:
|
||||
selector: {app: service-auth}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,51 @@
|
||||
# Exactly one replica, replaced not rolled: it sends the daily follow-up summary (deploy/check_rules.py).
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: service-counter
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector:
|
||||
matchLabels: {app: service-counter}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: service-counter}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: service-counter
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-counter
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-settings}}
|
||||
- {secretRef: {name: co-lite-shared}}
|
||||
- {configMapRef: {name: co-lite-gcp}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 768Mi}
|
||||
limits: {memory: 1Gi}
|
||||
volumeMounts:
|
||||
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
|
||||
volumes:
|
||||
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: service-counter
|
||||
spec:
|
||||
selector: {app: service-counter}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,49 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: service-email
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: service-email}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: service-email}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: service-email
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-email
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-settings}}
|
||||
- {secretRef: {name: co-lite-shared}}
|
||||
- {configMapRef: {name: co-lite-gcp}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 512Mi}
|
||||
limits: {memory: 1Gi}
|
||||
volumeMounts:
|
||||
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
|
||||
volumes:
|
||||
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: service-email
|
||||
spec:
|
||||
selector: {app: service-email}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,49 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: service-log
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: service-log}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: service-log}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: service-log
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-log
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-settings}}
|
||||
- {secretRef: {name: co-lite-shared}}
|
||||
- {configMapRef: {name: co-lite-gcp}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 512Mi}
|
||||
limits: {memory: 1Gi}
|
||||
volumeMounts:
|
||||
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
|
||||
volumes:
|
||||
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: service-log
|
||||
spec:
|
||||
selector: {app: service-log}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,49 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: service-member
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: service-member}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: service-member}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: service-member
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-member
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-settings}}
|
||||
- {secretRef: {name: co-lite-shared}}
|
||||
- {configMapRef: {name: co-lite-gcp}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 512Mi}
|
||||
limits: {memory: 1Gi}
|
||||
volumeMounts:
|
||||
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
|
||||
volumes:
|
||||
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: service-member
|
||||
spec:
|
||||
selector: {app: service-member}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,49 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: service-system
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: service-system}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: service-system}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: service-system
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-system
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-settings}}
|
||||
- {secretRef: {name: co-lite-shared}}
|
||||
- {configMapRef: {name: co-lite-gcp}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 512Mi}
|
||||
limits: {memory: 1Gi}
|
||||
volumeMounts:
|
||||
- {name: gcp-key, mountPath: /var/secrets/gcp, readOnly: true}
|
||||
volumes:
|
||||
- {name: gcp-key, secret: {secretName: co-lite-gcp-key}}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: service-system
|
||||
spec:
|
||||
selector: {app: service-system}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,47 @@
|
||||
# No Pub/Sub, Redis or key.json; reads the WhatsApp settings at startup.
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: service-whatsapp
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels: {app: service-whatsapp}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: service-whatsapp}
|
||||
spec:
|
||||
imagePullSecrets:
|
||||
- {name: co-lite-registry}
|
||||
containers:
|
||||
- name: service-whatsapp
|
||||
image: gitea.containerverse.dev/solvway/co-lite-service-whatsapp
|
||||
ports:
|
||||
- {name: http, containerPort: 80}
|
||||
envFrom:
|
||||
- {configMapRef: {name: co-lite-settings}}
|
||||
- {secretRef: {name: co-lite-shared}}
|
||||
- {configMapRef: {name: co-lite-whatsapp}}
|
||||
- {secretRef: {name: co-lite-whatsapp, optional: true}}
|
||||
startupProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 10
|
||||
failureThreshold: 30
|
||||
livenessProbe:
|
||||
httpGet: {path: /actuator/health/liveness, port: http}
|
||||
periodSeconds: 20
|
||||
readinessProbe:
|
||||
httpGet: {path: /actuator/health/readiness, port: http}
|
||||
periodSeconds: 10
|
||||
resources:
|
||||
requests: {cpu: 100m, memory: 512Mi}
|
||||
limits: {memory: 1Gi}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: service-whatsapp
|
||||
spec:
|
||||
selector: {app: service-whatsapp}
|
||||
ports:
|
||||
- {name: http, port: 80, targetPort: http}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Pub/Sub (docs/deployment.md section 5). The key itself is the co-lite-gcp-key Secret, mounted at /var/secrets/gcp.
|
||||
GCP_PROJECT=<google cloud project id>
|
||||
GCP_CREDENTIAL_FILE=file:/var/secrets/gcp/key.json
|
||||
@@ -0,0 +1,43 @@
|
||||
# Production: the team's cluster. Apply with `kubectl apply -k deploy/k8s/overlays/prod` after
|
||||
# deploy/create-secrets.sh and deploy/check.sh --release (docs/deployment.md section 2).
|
||||
# Every <…> value is a cluster fact still to be filled in; deploy/check.sh --release refuses them.
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: co-lite
|
||||
resources:
|
||||
- namespace.yaml
|
||||
- ../../base
|
||||
- routes.yaml
|
||||
# Plain settings (docs/deployment.md section 6). Secrets are not here: deploy/create-secrets.sh makes them.
|
||||
# A changed value gets a new ConfigMap name, so the pods that read it restart on the next apply.
|
||||
configMapGenerator:
|
||||
- name: co-lite-settings
|
||||
envs: [settings.env]
|
||||
- name: co-lite-gcp
|
||||
envs: [gcp.env]
|
||||
- name: co-lite-whatsapp
|
||||
envs: [whatsapp.env]
|
||||
- name: co-lite-portal
|
||||
envs: [portal.env]
|
||||
# One release is one commit SHA on main; change it with deploy/set-release.sh <sha>, roll back the same way.
|
||||
images:
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-admin-portal
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-api-gateway
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-mobile-api
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-service-auth
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-service-counter
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-service-email
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-service-log
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-service-member
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-service-system
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
- name: gitea.containerverse.dev/solvway/co-lite-service-whatsapp
|
||||
newTag: "a0da31f0da71bb8b4276774c6a79dcdd672cac2b"
|
||||
@@ -0,0 +1,4 @@
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: co-lite
|
||||
@@ -0,0 +1 @@
|
||||
MOBILE_API_BASE_URL=http://mobile-api
|
||||
@@ -0,0 +1,31 @@
|
||||
# The only public entry points (openspec spec cluster-deployment; deploy/check_rules.py enforces them):
|
||||
# the admin portal, and exactly mobile-api's WhatsApp webhook path. Never route api-gateway or a service-*.
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: admin-portal
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.containerverse.dev`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: admin-portal
|
||||
port: 3000
|
||||
tls:
|
||||
certResolver: <traefik cert resolver>
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: IngressRoute
|
||||
metadata:
|
||||
name: whatsapp-webhook
|
||||
spec:
|
||||
entryPoints: [websecure]
|
||||
routes:
|
||||
- match: Host(`co-lite.containerverse.dev`) && Path(`/api/public/whatsapp/webhook`)
|
||||
kind: Rule
|
||||
services:
|
||||
- name: mobile-api
|
||||
port: 80
|
||||
tls:
|
||||
certResolver: <traefik cert resolver>
|
||||
@@ -0,0 +1,9 @@
|
||||
# Read by every Java service except api-gateway (which takes only JAVA_OPTS from here).
|
||||
MYSQLHOST=<mysql host from the DBA>
|
||||
MYSQLPORT=3306
|
||||
REDISHOST=<host of the existing Redis>
|
||||
APIGATEWAYURL=http://api-gateway
|
||||
ADMIN_PORTAL_BASE_URL=https://co-lite.containerverse.dev
|
||||
JAVA_OPTS=-Xmx384m
|
||||
# mobile-api does not switch its liveness and readiness endpoints on by itself.
|
||||
MANAGEMENT_HEALTH_PROBES_ENABLED=true
|
||||
@@ -0,0 +1,7 @@
|
||||
# WhatsApp stays off until WHATSAPP_COMPANIES is set (docs/deployment.md sections 6 and 11).
|
||||
# To switch it on, uncomment and fill in; the tokens and app secrets go in the co-lite-whatsapp Secret.
|
||||
# WHATSAPP_COMPANIES=INS,CV
|
||||
# WHATSAPP_INS_PHONE_NUMBER_ID=
|
||||
# WHATSAPP_INS_WABA_ID=
|
||||
# WHATSAPP_CV_PHONE_NUMBER_ID=
|
||||
# WHATSAPP_CV_WABA_ID=
|
||||
@@ -0,0 +1,11 @@
|
||||
# Secret templates
|
||||
|
||||
Placeholders only. Copy this folder to `deploy/k8s/secrets/` (git ignores it), fill in every `<…>`, then run
|
||||
`deploy/create-secrets.sh`. Never commit the filled-in copy.
|
||||
|
||||
- `<name>.env` becomes the Secret `<name>`, one key per line.
|
||||
- `<name>/` becomes the Secret `<name>`, one key per file (the file name is the key).
|
||||
- `co-lite-registry.env` becomes the image pull secret for `gitea.containerverse.dev`.
|
||||
- `co-lite-whatsapp.env` is optional: leave it out of `secrets/` while WhatsApp is off.
|
||||
|
||||
Make each random value separately, for example with `openssl rand -base64 48`. What each value is: `docs/deployment.md` sections 6 and 7.
|
||||
@@ -0,0 +1,2 @@
|
||||
MOBILE_API_KEY=<the portal key from AUTH_API_KEYS, without :APP>
|
||||
SESSION_SECRET=<random, at least 32 characters>
|
||||
@@ -0,0 +1,10 @@
|
||||
[
|
||||
{
|
||||
"key": "<the APIKEY value given to mobile-api>",
|
||||
"name": "Co-Lite mobile-api",
|
||||
"desc": "mobile-api calls to the gateway",
|
||||
"type": "BO",
|
||||
"allowList": ["/"],
|
||||
"ipList": ["<pod CIDR of the cluster>"]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1 @@
|
||||
<the Pub/Sub service-account JSON key file, docs/deployment.md section 5>
|
||||
@@ -0,0 +1,4 @@
|
||||
# APIKEY: the key in appkeys.json. AUTH_API_KEYS: <key>:APP entries, comma-separated; one is the portal's MOBILE_API_KEY.
|
||||
APIKEY=<random, the same as the key in co-lite-gateway-appkeys/appkeys.json>
|
||||
AUTH_API_KEYS=<portal key>:APP
|
||||
JWT_SECRET=<the same value as JWT_TOKEN>
|
||||
@@ -0,0 +1,3 @@
|
||||
# A read-only package token for gitea.containerverse.dev, so the cluster can pull the images.
|
||||
REGISTRY_USER=<gitea user>
|
||||
REGISTRY_PASSWORD=<read-only package token>
|
||||
@@ -0,0 +1,2 @@
|
||||
AES_SECRET_KEY=<random, exactly 32 characters>
|
||||
USER_AUTH_API_SECRET=<random, at least 32 characters>
|
||||
@@ -0,0 +1,4 @@
|
||||
# Every Java service. JWT_TOKEN: HS512 key, at least 32 characters; mobile-api's JWT_SECRET must be the same value.
|
||||
JWT_TOKEN=<random, at least 32 characters>
|
||||
MYSQLUSER=<database user from the DBA>
|
||||
MYSQLPWD=<its password>
|
||||
@@ -0,0 +1,6 @@
|
||||
# Optional while WhatsApp is off. One ACCESS_TOKEN and APP_SECRET per company code in WHATSAPP_COMPANIES.
|
||||
WHATSAPP_VERIFY_TOKEN=<random, at least 32 characters>
|
||||
WHATSAPP_INS_ACCESS_TOKEN=<permanent system user token>
|
||||
WHATSAPP_INS_APP_SECRET=<meta app secret>
|
||||
WHATSAPP_CV_ACCESS_TOKEN=<permanent system user token>
|
||||
WHATSAPP_CV_APP_SECRET=<meta app secret>
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# Pins every Co-Lite image in the prod overlay to one commit SHA of main (openspec spec cluster-deployment).
|
||||
# Roll back by running it with the previous SHA and applying again.
|
||||
# deploy/set-release.sh <40-character commit sha>
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
sha=${1:-}
|
||||
printf '%s' "$sha" | grep -Eq '^[0-9a-f]{40}$' || { echo "usage: $0 <40-character commit sha of main>" >&2; exit 2; }
|
||||
k=deploy/k8s/overlays/prod/kustomization.yaml
|
||||
sed -i -E "s/^( newTag: )\"[0-9a-f]+\"$/\1\"$sha\"/" "$k"
|
||||
n=$(grep -c "^ newTag: \"$sha\"$" "$k")
|
||||
[ "$n" -eq 10 ] || { echo "set-release: expected 10 images at $sha, found $n" >&2; exit 1; }
|
||||
echo "prod overlay now pins all 10 images to $sha"
|
||||
+71
-78
@@ -1,6 +1,6 @@
|
||||
# Co-Lite Deployment Handover
|
||||
|
||||
This is for whoever deploys Co-Lite to the Kubernetes cluster. CI builds and publishes the images. The deployer writes the manifests and rolls them out. The database package goes to the DBA.
|
||||
This is for whoever deploys Co-Lite to the Kubernetes cluster. CI builds and publishes the images. The manifests are in `deploy/k8s/` (Kustomize: a `base` and a `prod` overlay); the deployer fills in the cluster facts and Secrets and applies them. The database package goes to the DBA.
|
||||
|
||||
Spec: `openspec/specs/release-packaging/spec.md`. Local stack for comparison: `local/README.md`.
|
||||
|
||||
@@ -26,7 +26,7 @@ The Service names matter:
|
||||
- mobile-api and the portal find the gateway and mobile-api through `APIGATEWAYURL` and `MOBILE_API_BASE_URL`.
|
||||
|
||||
**Health probes:**
|
||||
- **Java services:** liveness `GET /actuator/health/liveness`, readiness `GET /actuator/health/readiness`. Spring Boot turns these on by itself on Kubernetes. `GET /actuator/health` also works everywhere.
|
||||
- **Java services:** liveness `GET /actuator/health/liveness`, readiness `GET /actuator/health/readiness`. mobile-api does not switch these on by itself (measured: 404 without the setting), so the prod settings set `MANAGEMENT_HEALTH_PROBES_ENABLED=true` for every Java pod. Use the liveness path for the startup probe too: `GET /actuator/health` is 503 on service-email while no mail server is set.
|
||||
- **Admin portal:** it has no health endpoint. Use a TCP probe on port 3000, or `GET /login`, which returns 200 without a session.
|
||||
|
||||
**The Java images run as root and listen on port 80** (the base image sets no user). A cluster that enforces `runAsNonRoot` or the restricted Pod Security level must allow them.
|
||||
@@ -35,17 +35,60 @@ The Service names matter:
|
||||
|
||||
## 2. Order of setup
|
||||
|
||||
Everything below runs from the repository root, on `main`, with `kubectl` pointed at the cluster. The checks need only Docker.
|
||||
|
||||
1. The DBA prepares MySQL (section 3).
|
||||
2. Create the Pub/Sub topics and the service-account key (section 5).
|
||||
3. Create the Secrets and mounted files (sections 6 and 7).
|
||||
4. Deploy, in this order:
|
||||
3. **Fill in the cluster facts.** Replace every `<…>` in `deploy/k8s/overlays/prod/`:
|
||||
- `settings.env`: `MYSQLHOST` (from the DBA) and `REDISHOST` (the existing Redis);
|
||||
- `gcp.env`: `GCP_PROJECT`;
|
||||
- `routes.yaml`: the Traefik cert resolver, in both routes.
|
||||
|
||||
The namespace is `co-lite` (`kustomization.yaml` and `namespace.yaml`). Commit these files: they hold no secrets.
|
||||
4. **Create the Secrets.** Copy `deploy/k8s/secrets.example/` to `deploy/k8s/secrets/`. Git ignores that folder, so never commit it. Fill in every `<…>` (sections 6 and 7 say what each value is). Then:
|
||||
```sh
|
||||
deploy/create-secrets.sh --dry-run # checks every key is filled in; prints names, never values
|
||||
deploy/create-secrets.sh # creates or updates the Secrets in the co-lite namespace
|
||||
```
|
||||
The script creates the `co-lite` namespace if it is missing. Leave `co-lite-whatsapp.env` out until WhatsApp is connected (step 9).
|
||||
5. **Pick the release.** Choose a commit on `main` whose CI run pushed the images, and pin it:
|
||||
```sh
|
||||
deploy/set-release.sh <40-character commit sha>
|
||||
deploy/check.sh --release # refuses any <…> left, a public route to an internal service, latest, or a second service-counter
|
||||
```
|
||||
6. **Apply:**
|
||||
```sh
|
||||
kubectl apply -k deploy/k8s/overlays/prod
|
||||
kubectl -n co-lite rollout status deploy --timeout=10m
|
||||
```
|
||||
All ten Deployments start together; each Java pod gets up to 5 minutes to start. Starting them together has not been tried on the cluster yet. If a pod keeps restarting, apply in the old order instead and wait for each step to be ready:
|
||||
1. `service-system`, `service-auth`, `service-counter`, `service-member`, `service-log`, `service-email`, `service-whatsapp`;
|
||||
2. `api-gateway`;
|
||||
3. `mobile-api`;
|
||||
4. `admin-portal`.
|
||||
5. Add the Traefik routes (section 8).
|
||||
6. Connect WhatsApp in Meta (section 11). This can wait: until it is done, the inbox says "WhatsApp is not configured".
|
||||
7. Sign in as the first admin at `https://co-lite.containerverse.dev` and set the real password. Then create the staff users under Users. The admin types each user's first password and passes it on in person. Each user must choose their own password at first sign-in. No email is needed.
|
||||
|
||||
Use `kubectl -n co-lite rollout restart deploy/<name>` once the services it calls are ready.
|
||||
7. Commit the overlay with the new SHA, so `main` records what runs.
|
||||
8. Check the Custom HTML frame header (section 8).
|
||||
9. Connect WhatsApp in Meta (section 11) whenever you are ready. Until then the inbox says "WhatsApp is not configured". To switch it on: fill in `whatsapp.env` in the overlay and `co-lite-whatsapp.env` in `secrets/`, then run `create-secrets.sh` and apply again.
|
||||
10. Sign in as the first admin at `https://co-lite.containerverse.dev` and set the real password. Then create the staff users under Users. The admin types each user's first password and passes it on in person. Each user must choose their own password at first sign-in. No email is needed.
|
||||
|
||||
**Rollback.** Run `deploy/set-release.sh <the previous sha>`, then `deploy/check.sh --release`, then apply again and wait for the rollout. The SHA history of `deploy/k8s/overlays/prod/kustomization.yaml` on `main` lists the releases. Database changes only go forward: roll back only to a SHA that works with the schema now in place. Each change's SQL in section 3 says whether older code still runs on it.
|
||||
|
||||
**Changing a setting.** Edit the `.env` file in the overlay and apply again. The settings ConfigMaps get a new name for each new content, so the pods that read them restart by themselves. **Changing a secret:** edit `deploy/k8s/secrets/`, run `create-secrets.sh`, then `kubectl -n co-lite rollout restart deploy/<name>` for the pods that read it. mobile-api needs no restart for the WhatsApp secrets (section 6).
|
||||
|
||||
**Left unset on purpose.** These settings keep their built-in defaults:
|
||||
- the email provider keys (section 10);
|
||||
- `SMSS360_EMAIL` and `CUSTOMER_PORTAL_BASE_URL`, which still point at Tastefully (section 10);
|
||||
- `JUMIO_TOKEN` and `JUMIO_SECRET`;
|
||||
- `XXL_JOB_TOKEN`.
|
||||
|
||||
**Cluster facts still to confirm before the first apply:**
|
||||
- the Traefik cert resolver name;
|
||||
- the Redis host and the MySQL host;
|
||||
- the Pub/Sub project;
|
||||
- whether the pull secret can be `co-lite-registry`, or the cluster already has one;
|
||||
- whether the separate public-pages hostname (section 8) is wanted at go-live (it would be a third route in `routes.yaml`).
|
||||
|
||||
## 3. Database (for the DBA)
|
||||
|
||||
@@ -309,6 +352,8 @@ Generate each random value separately, for example with `openssl rand -base64 48
|
||||
|
||||
## 8. Traefik
|
||||
|
||||
The routes below are in `deploy/k8s/overlays/prod/routes.yaml`; `deploy/check.sh` fails if a route reaches anything else.
|
||||
|
||||
Route `co-lite.containerverse.dev` to the `admin-portal` Service on port 3000, with TLS. Only the admin portal is public: the browser talks to the portal, and the portal talks to `mobile-api` inside the cluster. Do not expose `mobile-api`, `api-gateway` or the services.
|
||||
|
||||
**WhatsApp webhook.** Meta must reach exactly one mobile-api path from the internet. Add a second route on the same host, for the path `/api/public/whatsapp/webhook` only (Traefik rule `Host(\`co-lite.containerverse.dev\`) && Path(\`/api/public/whatsapp/webhook\`)`), to the `mobile-api` Service on port 80. Expose no other mobile-api path. Every call on it is checked: a GET needs the verify token, and a POST needs Meta's signature under one of the configured app secrets (mobile-api checks it, and `service-whatsapp` checks it again).
|
||||
@@ -323,76 +368,20 @@ QR registration pages (`/r/<code>`) are served by the admin portal on the same h
|
||||
|
||||
## 9. Secret templates
|
||||
|
||||
There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files.
|
||||
The templates are in `deploy/k8s/secrets.example/`, one file per Secret, with placeholders only:
|
||||
|
||||
```yaml
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: co-lite-shared
|
||||
type: Opaque
|
||||
data:
|
||||
JWT_TOKEN: <base64>
|
||||
MYSQLUSER: <base64>
|
||||
MYSQLPWD: <base64>
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: co-lite-service-auth
|
||||
type: Opaque
|
||||
data:
|
||||
AES_SECRET_KEY: <base64>
|
||||
USER_AUTH_API_SECRET: <base64>
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: co-lite-mobile-api
|
||||
type: Opaque
|
||||
data:
|
||||
APIKEY: <base64>
|
||||
AUTH_API_KEYS: <base64>
|
||||
JWT_SECRET: <base64, same value as JWT_TOKEN>
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: co-lite-admin-portal
|
||||
type: Opaque
|
||||
data:
|
||||
MOBILE_API_KEY: <base64>
|
||||
SESSION_SECRET: <base64>
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: co-lite-whatsapp
|
||||
type: Opaque
|
||||
data:
|
||||
# mounted into both mobile-api and service-whatsapp; one ACCESS_TOKEN and APP_SECRET pair per company code
|
||||
WHATSAPP_INS_ACCESS_TOKEN: <base64>
|
||||
WHATSAPP_INS_APP_SECRET: <base64>
|
||||
WHATSAPP_CV_ACCESS_TOKEN: <base64>
|
||||
WHATSAPP_CV_APP_SECRET: <base64>
|
||||
WHATSAPP_VERIFY_TOKEN: <base64>
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: co-lite-gateway-appkeys
|
||||
type: Opaque
|
||||
data:
|
||||
appkeys.json: <base64 of the whole appkeys.json file>
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: co-lite-gcp-key
|
||||
type: Opaque
|
||||
data:
|
||||
key.json: <base64 of the service-account JSON key>
|
||||
```
|
||||
| Template | Secret | Read by |
|
||||
|---|---|---|
|
||||
| `co-lite-shared.env` | `co-lite-shared`: `JWT_TOKEN`, `MYSQLUSER`, `MYSQLPWD` | every Java service (api-gateway only `JWT_TOKEN`) |
|
||||
| `co-lite-service-auth.env` | `co-lite-service-auth` | service-auth |
|
||||
| `co-lite-mobile-api.env` | `co-lite-mobile-api` | mobile-api |
|
||||
| `co-lite-admin-portal.env` | `co-lite-admin-portal` | admin-portal |
|
||||
| `co-lite-whatsapp.env` | `co-lite-whatsapp` (optional) | mobile-api and service-whatsapp |
|
||||
| `co-lite-registry.env` | `co-lite-registry`, the image pull secret | every pod |
|
||||
| `co-lite-gateway-appkeys/appkeys.json` | `co-lite-gateway-appkeys` | api-gateway (section 7) |
|
||||
| `co-lite-gcp-key/key.json` | `co-lite-gcp-key` | every Java service except api-gateway and service-whatsapp |
|
||||
|
||||
`deploy/create-secrets.sh` turns the filled-in copy into Secrets (section 2, step 4). It refuses to change anything while any key is missing, empty or still a placeholder. There is still no template for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset).
|
||||
|
||||
## 10. Known gaps at go-live
|
||||
|
||||
@@ -409,7 +398,7 @@ data:
|
||||
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
|
||||
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
|
||||
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
|
||||
- **Deploy by SHA, not `latest`.** CI pushes the images one by one, so if a push fails halfway, `latest` can differ between images.
|
||||
- **Deploy by SHA, not `latest`.** CI pushes the images one by one, so if a push fails halfway, `latest` can differ between images. `deploy/check.sh` refuses `latest`.
|
||||
- **Chinese labels.** Staff switch the back office to 简体中文 with the language switcher, including on the sign-in page. The Chinese is a first pass, not checked by a native speaker. Grant `BO_MESSAGES` to the reviewer's role: under **Translations**, the **Missing Chinese** filter lists labels with no Chinese or with English copied in, and a saved change shows on the next page load. The list also holds about 3,400 labels inherited from Tastefully that Co-Lite never shows; the **Co-Lite labels only** box, ticked by default, hides them, and unticking it lists every label. Export and Import move all labels through a JSON file for review offline; import matches labels by code and never adds or removes languages. Grant `BO_LOCALES` only to whoever decides which languages staff can pick: English cannot be switched off. Only the back office is translated; visitor pages and emails keep their own wording.
|
||||
- **Gateway paths for labels.** The gateway used to let every `/message/` path through without a user token. It now lets through only the label reads (`/message/catalogVersion`, `/message/getAllMessages/<area>`, `/message/getMessageJsonByAreaAndLocale/<area>/<locale>`, `/message/getMessageJsonForMobile/...`, the code lookups) and `GET /locale/findAllEnabled`. Saving, searching and the language writes need the user token mobile-api forwards. The gateway also gains a `/locale/**` route to services-system.
|
||||
- **WhatsApp roles.** Staff need `BO_WHATSAPP` to see the inbox and their own chats. A WhatsApp admin needs both `BO_WHATSAPP` and `BO_WHATSAPP_ADMIN`: the menu entry and the page need the first, and the second adds every chat of the company, owner changes and template sync. A chat's owner is set automatically to the salesperson of the newest lead with that mobile number; an admin can set an owner by hand, which sticks until "Automatic" is chosen again. A user who is disabled or loses `BO_WHATSAPP` loses their chats to Unassigned.
|
||||
@@ -422,7 +411,7 @@ data:
|
||||
- A send that Meta accepts without a message id is stored as failed. A send that never gets an answer stays "Sending"; nothing sweeps it.
|
||||
- Media is streamed with `;charset=UTF-8` added to its content type; browsers ignore it.
|
||||
- Meta's media download address is not checked to be a Meta host before the access token is sent with it.
|
||||
- **WhatsApp webhook and outages.** If `service-whatsapp` is down or answers with an error, the webhook answers 503 and Meta sends the event again, for up to 7 days; a message is never stored twice. The same happens right after `service-whatsapp` starts while `service-system` is unreachable. Keep `service-system` up before `service-whatsapp` (section 2).
|
||||
- **WhatsApp webhook and outages.** If `service-whatsapp` is down or answers with an error, the webhook answers 503 and Meta sends the event again, for up to 7 days; a message is never stored twice. The same happens right after `service-whatsapp` starts while `service-system` is unreachable. So on the first apply, check that `service-system` is ready before Meta starts sending (section 2, step 6).
|
||||
- **Client addresses for rate limits.** mobile-api takes a caller's address for its rate limits from the first entry of `X-Forwarded-For` when the header is present (`HttpReqRespUtils` in core-libs). On the webhook route, a caller can set that header itself and so pick its own limit bucket. The webhook still rejects anything Meta did not sign, so this only weakens the flood limit (6000 calls per 10 minutes per address). Check that Traefik replaces an `X-Forwarded-For` sent by an untrusted caller instead of passing it on (`forwardedHeaders.insecure` off, `trustedIPs` limited to real proxies).
|
||||
|
||||
- **Landing pages.**
|
||||
@@ -475,4 +464,8 @@ A form stops taking sign-ups when its event is disabled, its end date has passed
|
||||
|
||||
**Release add-page-visual-editor (SQL, in its OpenSpec change folder):** portal only. Deploy the portal, then run `sql/01-visual-editor-labels.sql`. Rollback: the previous portal image, then `sql/99-rollback.sql` (labels only). No data changes.
|
||||
|
||||
**Release add-hero-signup-form (SQL, in its OpenSpec change folder):** deploy services-counter, mobile-api and the portal (any order), then run `sql/01-hero-form-labels.sql` (labels only). A hero section can now carry the sign-up form for an event, beside its text. Rollback: the previous images. A hero saved with an event keeps it in its JSON. The old code ignores it and shows the hero without a form, so add a Sign-up form section to those pages if you roll back.
|
||||
|
||||
**Release add-hero-full-width (SQL, in its OpenSpec change folder):** deploy services-counter, then the portal, then run `sql/01-hero-full-width-labels.sql` (labels only). Deploy services-counter first, because the portal's editor saves the new hero fields. A hero can now run full width, carry bullet points, and give its form card a heading. Custom HTML frames now shrink to fit short content and no longer leave a gap next to a full-width hero. Rollback: the previous images. Saved heroes keep the new fields in their JSON; the old code ignores them and shows the boxed hero. The old services-counter refuses to save a hero that has points or a form heading, so remove them before saving such a page.
|
||||
|
||||
**New portal dependencies:** `@tiptap/react`, `@tiptap/pm`, `@tiptap/starter-kit` and `@tiptap/extension-text-align` (the editor, loaded only on the editor screens), and `sanitize-html` (cleans page text on the server before it reaches a visitor). The image build installs them from `package-lock.json`; nothing to do by hand.
|
||||
@@ -1713,6 +1713,20 @@ INSERT INTO message (code, content, area) SELECT 'PagesFormClosed', JSON_OBJECT(
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名已截止。') WHERE LOWER(code) = LOWER('PagesFormClosed') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesFormPreview', JSON_OBJECT('en_US', 'The sign-up form shows here on the published page.', 'zh_CN', '发布后的网页会在此显示报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormPreview') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '发布后的网页会在此显示报名表。') WHERE LOWER(code) = LOWER('PagesFormPreview') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHeroForm', JSON_OBJECT('en_US', 'Sign-up form', 'zh_CN', '报名表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表单') WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesNoForm', JSON_OBJECT('en_US', 'No form', 'zh_CN', '不显示表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不显示表单') WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesFullWidth', JSON_OBJECT('en_US', 'Full width', 'zh_CN', '全宽'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全宽') WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPointN', JSON_OBJECT('en_US', 'Point {number}', 'zh_CN', '要点 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '要点 {number}') WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesAddPoint', JSON_OBJECT('en_US', 'Add point', 'zh_CN', '添加要点'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加要点') WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesFormHeading', JSON_OBJECT('en_US', 'Form heading', 'zh_CN', '表单标题'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单标题') WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesFormText', JSON_OBJECT('en_US', 'Form text', 'zh_CN', '表单说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单说明') WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesToolbar', JSON_OBJECT('en_US', 'Formatting', 'zh_CN', '格式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesToolbar') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '格式') WHERE LOWER(code) = LOWER('PagesToolbar') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTextStyle', JSON_OBJECT('en_US', 'Text style', 'zh_CN', '文字样式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTextStyle') AND area = 'A');
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-04
|
||||
@@ -0,0 +1,25 @@
|
||||
# Design
|
||||
|
||||
## Context
|
||||
|
||||
The HERO block renders inside `Section`, which wraps every non-HTML block in the page width (`max-w-5xl px-4`). The page's block list is `space-y-10`. Custom HTML blocks already render outside `Section`, so they run full width. The hero-with-form layout comes from add-hero-signup-form.
|
||||
|
||||
## Approaches
|
||||
|
||||
1. **A `fullWidth` option on HERO (chosen).** Explicit and opt-in, so existing heroes and templates do not change. It costs one boolean and one switch in the editor.
|
||||
2. **Make every hero with a form full width.** This needs no new field, but it silently changes existing pages and ties two unrelated choices together.
|
||||
3. **Build the hero in Custom HTML.** This cannot work: a sealed frame cannot hold the real sign-up form (see add-hero-signup-form).
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Points reuse `cards`.** They use title-only cards, as the trust strip does. The DTO does not change, and the editor reuses the trust strip's item list (`PagesItemN`, `PagesAddItem`). On a HERO the validator allows 0 to 6 cards. FEATURES, STEPS and TRUST keep their 2 to 6 rule.
|
||||
- **Joins.** A block counts as "bleed" when it is HTML, or when it is a full-width HERO. When a block and the block before it are both bleed, the block gets no top margin. Two Custom HTML blocks next to each other therefore join as well. That changes current pages, but only toward what Custom HTML sections expect: built sections are designed to stack.
|
||||
- **A full-width hero is not wrapped in `Section`.** It renders outside the page width, in the same way as `HtmlSpot`. Its inner content uses a wider container (`max-w-6xl px-4`).
|
||||
- **Font.** The headline uses Tailwind's `font-serif`, the system serif. No web font is added, so there is no new dependency and no third-party request.
|
||||
- **Shade.** The full-width shade is a left-to-right gradient, from `black/75` through `black/45` to `black/10`. It stays black-based, because the design-token test refuses raw colours, and the white text sits on the dark side. On phones the layout stacks and the form card is solid, so contrast holds.
|
||||
- **Form heading and text.** These are plain text fields edited with `Text` in place, in the same way as the hero heading. They are refused on a hero without an event, so they cannot hide in saved data.
|
||||
|
||||
## Risks
|
||||
|
||||
- **Contrast with a light photo on the right.** The text sits on the left, over the darkest part of the shade, and the right side holds the solid form card. This is acceptable.
|
||||
- **Editor controls on the edge.** On the full-width canvas, the image button and the toolbar sit at the window's edge. They are already positioned inside the section by the PR #66 fix.
|
||||
@@ -0,0 +1,59 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
The INS Hotel technology page is being rebuilt in Co-Lite to match INS's standalone landing page (`~/Projects/ins-landing-page`). Since add-hero-signup-form, the form sits beside the hero text, but the hero still looks unlike the original in five ways:
|
||||
|
||||
- it is a rounded box inside the page width, with grey space around it, where the original runs edge to edge directly under the top bar;
|
||||
- its shade is near-black over the whole photo, where the original fades from dark on the left to a clear photo on the right;
|
||||
- its headline is small and pinned to the top, where the original's is large, serif and vertically centred;
|
||||
- it has no bullet points under the text;
|
||||
- the form card has no title or subtitle ("Get a free consultation" / "Tell us about your property…").
|
||||
|
||||
Marketing staff cannot fix any of these from the editor.
|
||||
|
||||
## What Changes
|
||||
|
||||
- A HERO block gains a **Full width** option (`fullWidth`). A full-width hero:
|
||||
- spans the whole window, with square corners and no page margin;
|
||||
- is taller, with a larger serif headline, vertically centred;
|
||||
- uses a lighter shade that runs from dark on the left to almost clear on the right.
|
||||
- Full-width heroes and Custom HTML blocks that sit next to each other join with no gap, so a Custom HTML top bar runs straight into the hero.
|
||||
- Custom HTML frames (found in the live check):
|
||||
- they may shrink to 20 px instead of 100 px, so a 68 px top bar leaves no blank band;
|
||||
- the page asks each frame for its height once it listens and when the frame loads, because the frame's first report could arrive before the page was ready, leaving it at 600 px.
|
||||
- A HERO block may carry up to 6 **points**, short title-only lines (`cards`, 80 characters each) shown as a bullet list under its text. The editor reuses the trust strip's item list.
|
||||
- A HERO with an event may carry a **form heading** (`formHeading`, 80 characters) and **form text** (`formText`, 200 characters), shown at the top of the form card. Both can be typed in place on the canvas.
|
||||
- The server validates the new fields:
|
||||
- `fullWidth` is a boolean;
|
||||
- the hero takes 0 to 6 points, each a non-empty title of at most 80 characters, with no icon or text;
|
||||
- the form heading and form text are refused on a hero without an event.
|
||||
- New editor labels in English and Chinese, with an SQL label file for real environments.
|
||||
|
||||
Not changing:
|
||||
- The heroes that exist today. Without the option they look as they do now.
|
||||
- The sign-up form's fields, the privacy notice and the consent box. They are shared with QR sign-up, and the notice and consent are required by the data-protection rules.
|
||||
- Field labels and the interests checkboxes.
|
||||
- The submit button colour, which follows the company's accent colour. For INS's gold button, set INS's accent colour in Companies; that is a setting, not code.
|
||||
- The red wave decoration at the bottom of the INS hero, which is left out.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `landing-pages`: adds "Full-Width Hero", "Hero Points" and "Hero Form Heading".
|
||||
|
||||
## Impact
|
||||
|
||||
- services-counter: `CmsBlock` gains `fullWidth`, `formHeading` and `formText`. `CmsBlockValidator` lets a HERO carry `cards` as points and checks the new fields.
|
||||
- mobile-api: none. Public blocks pass through as maps.
|
||||
- Portal:
|
||||
- `CmsBlocks.tsx` renders the hero layout and the joins between full-width blocks;
|
||||
- `BlockFields.tsx` gets the Full width switch, the points list and the form heading and text;
|
||||
- `cmsPages.ts` gets the types;
|
||||
- new labels in `defaultMessages.ts` and `zh_CN.seed.json`.
|
||||
- Data: no schema change, because the blocks are JSON. The new labels need a SQL label file in this change folder for real environments.
|
||||
@@ -0,0 +1,86 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Full-Width Hero
|
||||
|
||||
A HERO block MAY be marked full width. A full-width hero SHALL span the whole window with square corners, show its heading larger and centred top to bottom in the hero's opening height (not beside a long form), and use a shade that is darker on the text side than on the far side. A hero that is not marked full width SHALL look as it did before. The server SHALL refuse a `fullWidth` value that is not true or false.
|
||||
|
||||
#### Scenario: Hero runs edge to edge under a Custom HTML top bar
|
||||
|
||||
- **GIVEN** page `/p/INS/hotel-technology` with a Custom HTML top bar followed by a full-width HERO with an image and an event
|
||||
- **WHEN** a visitor opens the page in a 1280 px window
|
||||
- **THEN** the hero spans the full window width
|
||||
- **AND** the form card sits beside the heading
|
||||
|
||||
#### Scenario: Existing hero unchanged
|
||||
|
||||
- **WHEN** a visitor opens a page whose HERO block is not marked full width
|
||||
- **THEN** the hero sits inside the page width with rounded corners, as before
|
||||
|
||||
#### Scenario: Turn on full width in the editor
|
||||
|
||||
- **GIVEN** staff editing a page with a HERO block
|
||||
- **WHEN** they switch on "Full width" in the hero's settings
|
||||
- **THEN** the canvas shows the hero across the full width
|
||||
|
||||
### Requirement: Full-Width Blocks Join Without Gaps
|
||||
|
||||
A full-width HERO and a Custom HTML block next to each other SHALL join with no gap between them, and so SHALL two Custom HTML blocks next to each other. Other blocks SHALL keep their usual spacing.
|
||||
|
||||
#### Scenario: Top bar runs straight into the hero
|
||||
|
||||
- **GIVEN** a Custom HTML top bar followed by a full-width HERO
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the hero starts directly under the top bar, with no gap
|
||||
|
||||
### Requirement: Hero Points
|
||||
|
||||
A HERO block MAY carry up to 6 points, each a non-empty title of at most 80 characters, with no icon and no text. The hero SHALL show its points as a bulleted list under its text. The server SHALL refuse more than 6 points, an empty or over-long point, and a point with an icon or text, naming the field.
|
||||
|
||||
#### Scenario: Points under the hero text
|
||||
|
||||
- **GIVEN** a HERO block with points "One accountable partner instead of five vendors" and "Local support team in Malaysia"
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** both points show as a bulleted list under the hero text
|
||||
|
||||
#### Scenario: Too many points refused
|
||||
|
||||
- **WHEN** staff save a HERO block with 7 points
|
||||
- **THEN** the save is refused at `blocks[n].cards`
|
||||
|
||||
### Requirement: Hero Form Heading
|
||||
|
||||
A HERO block with an event MAY carry a form heading of at most 80 characters and a form text of at most 200 characters. The hero SHALL show them at the top of its form card, above the form. The server SHALL refuse either on a hero without an event. On the canvas, staff SHALL be able to type both in place.
|
||||
|
||||
#### Scenario: Card shows its heading
|
||||
|
||||
- **GIVEN** a HERO block with an event, form heading "Get a free consultation" and form text "Tell us about your property. It takes under a minute."
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the form card starts with that heading and text, followed by the form
|
||||
|
||||
#### Scenario: Form heading without a form refused
|
||||
|
||||
- **WHEN** staff save a HERO block with a form heading and no event
|
||||
- **THEN** the save is refused at `blocks[n].formHeading`
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Custom HTML Frame Height
|
||||
|
||||
The frame SHALL grow or shrink to fit its content, between 20 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall. The frame SHALL report the height of its content, not of its own window, and SHALL report again whenever the page asks, which the page SHALL do once it listens and when the frame loads.
|
||||
|
||||
#### Scenario: A tall paste grows the frame
|
||||
|
||||
- **GIVEN** a published HTML block whose content is 3000 pixels tall
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the frame is 3000 pixels tall and shows no inner scroll bar
|
||||
|
||||
#### Scenario: A short top bar shrinks the frame
|
||||
|
||||
- **GIVEN** a published HTML block holding only a 68 pixel top bar
|
||||
- **WHEN** a visitor opens the page, even if the frame loaded before the page was ready
|
||||
- **THEN** the frame is 68 pixels tall, with no blank space below the bar
|
||||
|
||||
#### Scenario: Another frame cannot resize it
|
||||
|
||||
- **WHEN** a different window posts a height report to the page
|
||||
- **THEN** the frame's height does not change
|
||||
@@ -0,0 +1,13 @@
|
||||
-- The labels added by add-hero-full-width, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
|
||||
SET NAMES utf8mb4;
|
||||
USE `service-system`;
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesFullWidth', JSON_OBJECT('en_US', 'Full width', 'zh_CN', '全宽'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全宽') WHERE LOWER(code) = LOWER('PagesFullWidth') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPointN', JSON_OBJECT('en_US', 'Point {number}', 'zh_CN', '要点 {number}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '要点 {number}') WHERE LOWER(code) = LOWER('PagesPointN') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesAddPoint', JSON_OBJECT('en_US', 'Add point', 'zh_CN', '添加要点'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '添加要点') WHERE LOWER(code) = LOWER('PagesAddPoint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesFormHeading', JSON_OBJECT('en_US', 'Form heading', 'zh_CN', '表单标题'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单标题') WHERE LOWER(code) = LOWER('PagesFormHeading') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesFormText', JSON_OBJECT('en_US', 'Form text', 'zh_CN', '表单说明'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '表单说明') WHERE LOWER(code) = LOWER('PagesFormText') AND area = 'A';
|
||||
@@ -0,0 +1,69 @@
|
||||
# Tasks
|
||||
|
||||
## 1. Server
|
||||
|
||||
- [x] 1.1 services-counter `CmsBlock`: add `fullWidth` (Boolean), `formHeading` and `formText`. `CmsBlockValidator` HERO rules:
|
||||
- allow `cards` on a HERO, 0 to 6 of them, each with a title that is required and at most 80 characters, and no icon or text;
|
||||
- `formHeading` at most 80 characters and `formText` at most 200;
|
||||
- refuse `formHeading` or `formText` without `eventUuid` (`PagesUnusedField`).
|
||||
|
||||
Verify: new validator tests fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
|
||||
|
||||
## 2. Portal
|
||||
|
||||
- [x] 2.1 `cmsPages.ts` types. In `CmsBlocks.tsx`:
|
||||
- the HERO shows its points as a bulleted list;
|
||||
- the form card shows `formHeading` and `formText`, editable in place;
|
||||
- a full-width HERO renders outside the page width, with a larger serif heading, vertical centring and the lighter left-to-right shade;
|
||||
- adjacent bleed blocks (HTML, or a full-width HERO) get no gap between them.
|
||||
|
||||
Verify: render tests fail first, then pass; vitest exit 0.
|
||||
- [x] 2.2 `BlockFields.tsx`:
|
||||
- the Hero gets a "Full width" switch, the points list (reusing the trust strip's item list), and the form heading and text fields, shown only when an event is picked;
|
||||
- `INLINE.HERO` includes `formHeading`, `formText` and the points;
|
||||
- add the labels to `defaultMessages.ts`, `zh_CN.seed.json` and `sql/01-hero-full-width-labels.sql`, and regenerate `local/seed/04-zh-cn-messages.sql`.
|
||||
|
||||
Verify: editor tests fail first, then pass; tsc and lint clean.
|
||||
|
||||
## 3. Verification
|
||||
|
||||
- [x] 3.1 Rebuild services-counter. Use Playwright on port 3001 to edit `/p/INS/hotel-technology` through the editor:
|
||||
- turn on Full width;
|
||||
- add the three INS points;
|
||||
- set the form heading and text;
|
||||
- publish the page.
|
||||
|
||||
Then check the published page at 1280 px and 390 px against the INS page, and check a save with 7 points shows the refusal on the canvas.
|
||||
- [x] 3.2 Run the full portal vitest (exit 0), tsc, lint, Maven verify for services-counter, and `openspec validate add-hero-full-width --strict`.
|
||||
- [x] 3.3 Add a release note to `docs/deployment.md` (label SQL).
|
||||
|
||||
## Notes (2026-12-04)
|
||||
|
||||
- **Red first:**
|
||||
- the validator tests failed on points and the form heading;
|
||||
- the render tests failed on full width, points, the card heading and the joins;
|
||||
- the editor and company-switch tests failed;
|
||||
- the frame floor, ask and answer tests failed.
|
||||
- **Changed existing tests:**
|
||||
- `CmsBlocks.html.test.tsx` "starts a header-less page flush at the top" now checks that the first block row has no top margin. It used to check for a `space-y` class, which is no longer how spacing works. It still asserts that the hidden title is outside the spacing.
|
||||
- `frameHtml.test.ts` clamp test: the floor is now 20 px, per the modified "Custom HTML Frame Height" requirement. It also checks that 68 stays 68.
|
||||
- **Live check** (port 3001, rebuilt counter), on `/p/INS/hotel-technology` through the editor:
|
||||
- Full width switched on;
|
||||
- three points and the form heading and text typed on the canvas;
|
||||
- saved and published.
|
||||
- **Published result at 1280 px:**
|
||||
- the hero runs flush under the top bar and into the rest of the page;
|
||||
- the serif headline is centred in the first screen;
|
||||
- the points show in the accent colour, and the card has its heading.
|
||||
- **Published result at 390 px:** the layout stacks, with the card below the text.
|
||||
- **Fixes from the live check:**
|
||||
- the text is centred in the opening height, not beside the long form;
|
||||
- the frame floor is 20 px;
|
||||
- the page asks frames for their height (both added to the spec).
|
||||
- **Not reachable in the UI, covered by the validator tests:**
|
||||
- 7 points, because Add point stops at 6;
|
||||
- a form heading without a form, because No form clears it.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Open a PR to `main` and merge it. Archive the change on its own branch, with its own PR.
|
||||
File renamed without changes.
@@ -0,0 +1,43 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Event pages convert best when the sign-up form is visible as soon as the page opens. INS's standalone landing page (`~/Projects/ins-landing-page`) puts the form in a card beside the hero text. In Co-Lite the form is always its own section, so on a page built from Custom HTML it lands below the hero, and the hero tells visitors to "scroll down to the form". Custom HTML cannot hold the real form: it runs in a sealed frame that cannot send leads into Co-Lite.
|
||||
|
||||
## What Changes
|
||||
|
||||
- A HERO block gains an optional event (`eventUuid`). When it is set, the hero shows Co-Lite's sign-up form for that event in a card beside the heading, text and button on wide screens, and below them on phones.
|
||||
- The hero form behaves exactly like the FORM block:
|
||||
- the same fields, interests and privacy notice;
|
||||
- the same submit rules and limits;
|
||||
- the same lead source, UTM values and closing rules.
|
||||
- The server checks a hero's event like a FORM block's: it must be an event of the page's company.
|
||||
- In the editor, the Hero's settings gain the same event picker as the Sign-up form, with "No form" as the default. The canvas shows the form card in place.
|
||||
- Switching company in the editor clears a hero's event, as it already clears a FORM block's.
|
||||
|
||||
Not changing:
|
||||
- The FORM block stays as it is.
|
||||
- A page may have a hero form and a FORM block together, and each registers for its own event.
|
||||
- The form card has no heading of its own; the hero's heading and text introduce it.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `landing-pages`: hero blocks may carry the sign-up form, and the event-reference rule covers them.
|
||||
|
||||
## Impact
|
||||
|
||||
- **services-counter:** `CmsBlockValidator`, which now checks a HERO's optional `eventUuid`.
|
||||
- **mobile-api:** `PublicPageService`, which attaches form info to, and accepts submits for, any block with an event (FORM or a HERO that has one).
|
||||
- **admin-portal:**
|
||||
- the `HERO` rendering in `CmsBlocks.tsx`;
|
||||
- the Hero fields in `BlockFields.tsx`;
|
||||
- the company-switch reset in `usePageDraft.ts`;
|
||||
- two labels, in English and Chinese.
|
||||
- **No schema change:** blocks are JSON.
|
||||
- **No new dependency.**
|
||||
@@ -0,0 +1,48 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Hero With A Sign-Up Form
|
||||
|
||||
A HERO block MAY name an event. When it does, the hero SHALL show Co-Lite's sign-up form for that event in a card beside its heading, text and button on wide screens, and below them on narrow screens. The hero's form SHALL follow every rule of the FORM block (see "The Form Block Registers For An Event" and "The Form Block Closes With Its Event"). A HERO block without an event SHALL show no form.
|
||||
|
||||
#### Scenario: Sign up from the hero
|
||||
|
||||
- **GIVEN** page `/p/INS/hotel-technology` has a HERO block whose event is `INS website enquiries`
|
||||
- **WHEN** a new visitor submits the form in the hero from a URL with `utm_source=facebook`
|
||||
- **THEN** a new lead and an event lead with source Web page, no salesperson and UTM source `facebook` are created
|
||||
|
||||
#### Scenario: Hero form closes with its event
|
||||
|
||||
- **GIVEN** the HERO block's event ended yesterday
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the hero still shows its heading and text, and its form area says sign-up is closed
|
||||
|
||||
#### Scenario: Hero without an event
|
||||
|
||||
- **WHEN** a visitor opens a page whose HERO block names no event
|
||||
- **THEN** the hero shows no form
|
||||
- **AND** a submit addressed to that block is refused as not found
|
||||
|
||||
#### Scenario: Pick the hero's event in the editor
|
||||
|
||||
- **GIVEN** staff editing a page with a HERO block
|
||||
- **WHEN** they pick `INS website enquiries` under the hero's sign-up form setting
|
||||
- **THEN** the canvas shows the form card beside the hero text
|
||||
- **AND** choosing "No form" removes it
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Block References Stay Inside The Company
|
||||
|
||||
A block's image SHALL be an image of the page's company, and the event of a FORM block or of a HERO block that names one SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
|
||||
|
||||
#### Scenario: Another company's event
|
||||
|
||||
- **GIVEN** event `CV Roadshow` belongs to CV
|
||||
- **WHEN** INS staff save a FORM block pointing at `CV Roadshow`
|
||||
- **THEN** the save is refused on that block's event field
|
||||
|
||||
#### Scenario: Another company's event in a hero
|
||||
|
||||
- **GIVEN** event `CV Roadshow` belongs to CV
|
||||
- **WHEN** INS staff save a HERO block whose event is `CV Roadshow`
|
||||
- **THEN** the save is refused on that block's event field
|
||||
@@ -0,0 +1,7 @@
|
||||
-- The labels added by add-hero-signup-form, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
|
||||
SET NAMES utf8mb4;
|
||||
USE `service-system`;
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHeroForm', JSON_OBJECT('en_US', 'Sign-up form', 'zh_CN', '报名表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表单') WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesNoForm', JSON_OBJECT('en_US', 'No form', 'zh_CN', '不显示表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不显示表单') WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A';
|
||||
@@ -0,0 +1,39 @@
|
||||
# Tasks
|
||||
|
||||
## 1. Server
|
||||
|
||||
- [x] 1.1 services-counter `CmsBlockValidator`: a HERO's optional `eventUuid` must be an event of the page's company, refused at `blocks[n].eventUuid` with `PagesBadEvent`. Verify: new validator tests (own event saves, other company's event refused, no event saves) fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
|
||||
- [x] 1.2 mobile-api `PublicPageService`: `page()` attaches `form`/`closed` to every block with an event that is FORM or HERO; `submit()` accepts a HERO with an event and refuses a HERO without one as not found. Verify: new service tests fail first, then pass; `mvn -T 1C -pl solvway-mobile-api verify`.
|
||||
|
||||
## 2. Portal
|
||||
|
||||
- [x] 2.1 `CmsBlocks.tsx` HERO: with `form` or `closed`, two columns from `md` (text left, form card right; stacked on phones), image and shade kept; the card is `LandingForm` with the hero's block index. Verify: render tests for with/without event, closed, and the edit canvas; vitest exit 0.
|
||||
- [x] 2.2 `BlockFields.tsx`: the Hero gets the event picker ("No form" default, same hint and unavailable-event option as FORM; `eventUuid` shown inline); `usePageDraft` clears a HERO's event on company switch like a FORM's; labels `PagesHeroForm` and `PagesNoForm` in `defaultMessages.ts`, `zh_CN.seed.json` and an SQL label file in this change folder. Verify: editor tests fail first, then pass; tsc and lint clean.
|
||||
|
||||
## 3. Verification
|
||||
|
||||
- [x] 3.1 Rebuild services-counter and mobile-api locally; Playwright on port 3001: give a page's hero an event, see the card beside the text at 1280 px and below it at 390 px, submit as a visitor on the published page and see the lead under Event leads with source Web page; pick another company's event is impossible in the picker, and an ended event shows "closed". Use a disposable test page and the existing "LP Enquiries" test event; delete the test page after.
|
||||
- [x] 3.2 Full portal vitest (exit 0), tsc, lint, both Maven modules, `openspec validate add-hero-signup-form --strict`.
|
||||
|
||||
## Notes (2026-12-03)
|
||||
|
||||
- **Red first:** each new test failed before its code existed. The validator test failed on the foreign event; the service tests found no form on the hero; the render tests, the editor picker test and the company-switch test failed too.
|
||||
- **Existing editor test:** one query was scoped to the FORM block's picker, because "Website enquiries" is now an option in two pickers. Its assertions are unchanged.
|
||||
- **Live check** (port 3001, rebuilt counter and mobile-api), on the throwaway page "Live check hero form":
|
||||
- the hero picker defaults to "No form";
|
||||
- the canvas shows the card beside the text;
|
||||
- published at 1280 px, the form sits beside the text, and at 390 px below it;
|
||||
- the visitor "Hero Check Visitor" registered from the hero and appears under INS website enquiries with "Web page: /p/INS/live-check-hero-form";
|
||||
- the page was deleted afterwards. The test lead stays in the local database.
|
||||
- **Fixes from the live check:**
|
||||
- the hero text is top-aligned, because a long form left it below the fold;
|
||||
- the top padding is larger, so the editor's image button clears the heading;
|
||||
- the shade is a gradient, because the design-token test refuses flat `bg-black/*`.
|
||||
- **Not checked live:**
|
||||
- the closed state, which the picker cannot reach because it offers no ended events (covered by the service and render tests);
|
||||
- the other-company refusal, which the picker cannot reach either (covered by the validator test).
|
||||
- **Results:** Maven verify passed for services-counter and mobile-api; vitest 1985 passed (exit 0); tsc clean; lint 0 errors.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- PR to `main` and merge; archive on its own branch with its own PR.
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-03
|
||||
@@ -0,0 +1,124 @@
|
||||
# Design
|
||||
|
||||
## Context
|
||||
|
||||
- **Images:** CI publishes ten images to `gitea.containerverse.dev/solvway/`, each tagged with the commit SHA and with `latest`.
|
||||
- **What `docs/deployment.md` already fixes:**
|
||||
- the Service names and ports;
|
||||
- the probes;
|
||||
- every environment variable, and whether it is secret or plain;
|
||||
- the two mounted files (`appkeys.json` for the gateway, the Pub/Sub `key.json` for the other Java images);
|
||||
- the setup order;
|
||||
- the Traefik routes (portal on `co-lite.containerverse.dev`, plus the webhook path).
|
||||
- **Outside the cluster manifests:**
|
||||
- MySQL, prepared by the DBA;
|
||||
- Redis ("use the existing Redis");
|
||||
- Google Pub/Sub.
|
||||
- **Tools:** the repository has no Kubernetes files, and this machine has Docker but no kubectl.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- One `kubectl apply -k deploy/k8s/overlays/prod` deploys the whole system once the Secrets exist.
|
||||
- A check that fails on the mistakes that would hurt in production:
|
||||
- a public route to an internal service;
|
||||
- an image on `latest`;
|
||||
- secret data in git;
|
||||
- two service-counter replicas.
|
||||
|
||||
**Non-Goals:**
|
||||
- Helm charts, GitOps tooling (Argo CD or Flux), or automatic deploys from CI. A person applies each release.
|
||||
- Running MySQL, Redis or a Pub/Sub emulator in the cluster.
|
||||
- A local Kubernetes preview. The owner previews the system with the docker-compose stack.
|
||||
- Autoscaling, resource tuning beyond sensible requests, and NetworkPolicies. These can follow once the cluster's policy is known.
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1. Kustomize, with a base and a `prod` overlay
|
||||
|
||||
- **Choice:** plain YAML under `deploy/k8s/base/`, plus `deploy/k8s/overlays/prod/` for the image SHA, the plain settings, the namespace and the routes.
|
||||
- **Why:**
|
||||
- Kustomize is built into kubectl, so the deployer installs nothing.
|
||||
- The YAML reads like the handover doc.
|
||||
- **Rejected:**
|
||||
- Helm: templating for one environment adds code, and Helm would need installing.
|
||||
- Raw YAML without overlays: the SHA would then be edited in ten files.
|
||||
|
||||
### 2. The image SHA is set in one place
|
||||
|
||||
- **How:** the overlay's `images:` list sets `newTag` for all ten images. A small `deploy/set-release.sh <sha>` rewrites those ten lines.
|
||||
- **Rollback:** run `set-release.sh <previous sha>` and apply again. Every release is a commit on `main`, so the SHA in git history is the record of what ran.
|
||||
|
||||
### 3. Secrets are created by a script from git-ignored files, not stored as manifests
|
||||
|
||||
- **Templates:** `deploy/k8s/secrets.example/` holds one `.env` template per Secret (from `docs/deployment.md` section 9), plus an `appkeys.json` template.
|
||||
- **Filling them in:** the deployer copies the folder to `deploy/k8s/secrets/`, which git ignores, and fills it in.
|
||||
- **Creating them:** `deploy/create-secrets.sh` runs `kubectl create secret generic --from-env-file / --from-file ... --dry-run=client -o yaml | kubectl apply -f -`. It never prints a value.
|
||||
- **Rejected:**
|
||||
- Sealed Secrets or SOPS: new tooling and keys to manage, for a two-developer team. They can come later.
|
||||
- A Kustomize `secretGenerator`: it would put the values into the rendered output, which the check must stay able to forbid.
|
||||
|
||||
### 4. Traefik IngressRoute for the public routes
|
||||
|
||||
- **What:** the `prod` overlay holds two IngressRoutes on `co-lite.containerverse.dev`:
|
||||
- `/` to `admin-portal:3000`;
|
||||
- `Path(/api/public/whatsapp/webhook)` to `mobile-api:80`.
|
||||
- **Why:** the handover doc already states the routes as Traefik rules, and the cluster runs Traefik.
|
||||
- **TLS:** a `tls:` block whose cert resolver (or cert-manager secret) name is a single field in the overlay (see Open Questions).
|
||||
- **Rejected:** a standard Ingress with Traefik annotations. Exact-path matching is less clear there, and nothing else in the cluster needs portability.
|
||||
|
||||
### 5. The check runs from one pinned container
|
||||
|
||||
- **What:** `deploy/check.sh` sends the `deploy/` folder through stdin into `alpine/k8s:1.33.4`, pinned by digest. That one image has kubectl and kustomize, kubeconform, and python3 with PyYAML.
|
||||
- **Why stdin:** it also works against CI's remote Docker daemon, where bind mounts would not reach the files.
|
||||
- **Steps:**
|
||||
1. Kustomize renders the overlay.
|
||||
2. kubeconform validates the result. The Traefik schemas come from the CRDs catalog.
|
||||
3. `check_rules.py` applies the rules.
|
||||
- **Modes:**
|
||||
- `--self-test` runs every rule against its fixture in `deploy/check-fixtures/`.
|
||||
- `--release` also refuses any `<…>` placeholder. CI runs the plain check, because the cluster facts are still placeholders in git; the deployer runs `--release` before applying.
|
||||
- **Rejected:** separate kubectl, kubeconform and Python images. That is three pulls and three pins for the same result.
|
||||
|
||||
### 6. Pod settings
|
||||
|
||||
- **Common to all pods:**
|
||||
- one replica each;
|
||||
- `TZ` left to the image;
|
||||
- `GCP_CREDENTIAL_FILE` and the `key.json` mount on every Java pod except `api-gateway` and `service-whatsapp`;
|
||||
- `imagePullSecrets` set to one named pull secret.
|
||||
- **service-counter:** `strategy: Recreate`, so a rollout never runs two copies at once and the daily summary is never sent twice.
|
||||
- **Probes:** the startup probe uses `/actuator/health/liveness` and allows up to 5 minutes. The overall `/actuator/health` is 503 on service-email while no mail server is configured.
|
||||
- mobile-api does not turn its probe groups on by itself, so the settings set `MANAGEMENT_HEALTH_PROBES_ENABLED=true` for every Java pod.
|
||||
- Both facts were measured on the local containers.
|
||||
- **WhatsApp Secret:** referenced with `optional: true`, so mobile-api and service-whatsapp start while WhatsApp is off.
|
||||
- **Image tags:** quoted in the overlay. A SHA made only of digits, or shaped like `1e45…`, would otherwise be read as a number.
|
||||
- **Requests:** modest (`100m` CPU and `512Mi` for the Java pods; `256Mi` for the portal), with no CPU limit. `JAVA_OPTS=-Xmx384m` keeps the heap inside the memory limit.
|
||||
- **Security context:** the Java images run as root (documented). The manifests do not set `runAsNonRoot`. If the cluster enforces it, that is a finding for the image, not a manifest workaround.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **[A wrong cluster fact breaks the first apply]** (CRD version, pull-secret name, TLS method). Mitigation: those facts are single overlay fields, listed under Open Questions, and the first apply is done together with the owner.
|
||||
- **[Secrets created by hand drift from the templates]** Mitigation: `create-secrets.sh` refuses to run if any key in a template is missing from the filled file.
|
||||
- **[No automatic deploy means releases lag `main`]** This is accepted for go-live. Every release is a deliberate act with a recorded SHA.
|
||||
- **[The check uses an image pulled from Docker Hub]** Mitigation: it is pinned by version and digest.
|
||||
- **[kubeconform fetches the Traefik schema from GitHub]** Without network access the check fails rather than skipping. CI already needs the network to pull images.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
1. The DBA prepares MySQL, and the Pub/Sub topics and key are created (handover sections 3 and 5).
|
||||
2. Fill in `deploy/k8s/secrets/` and run `deploy/create-secrets.sh`. Create the registry pull secret.
|
||||
3. Run `deploy/set-release.sh <sha>` and `deploy/check.sh`, then `kubectl apply -k deploy/k8s/overlays/prod`.
|
||||
4. Wait for every Deployment to roll out (`kubectl rollout status`), then sign in as the first admin.
|
||||
5. **Rollback:** run `set-release.sh <previous sha>`, apply again, and wait for the rollout. Database changes are forward-only. A release that ran new SQL rolls back only to a SHA that works with that schema; the SQL files say which ones are safe.
|
||||
|
||||
## Open Questions
|
||||
|
||||
These are single overlay fields. They are needed before the first real apply, not to build or check the manifests.
|
||||
|
||||
- **Namespace:** the default is `co-lite`.
|
||||
- **TLS:** the Traefik cert resolver name (for example `letsencrypt`), or a cert-manager ClusterIssuer.
|
||||
- **Pull secret:** its name for `gitea.containerverse.dev`, if the cluster already has one.
|
||||
- **Redis:** the address of "the existing Redis".
|
||||
- **Public-pages hostname:** the separate one for `/r`, `/i`, `/c` and `/p` (handover section 8), if it should exist at go-live.
|
||||
- **Access:** who has kubectl access to the cluster for the first apply.
|
||||
@@ -0,0 +1,46 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Phase 1 ends with Co-Lite running on the team's Kubernetes cluster before go-live on 15 January 2027. CI already publishes the images, and `docs/deployment.md` describes the environment the images need. Nobody has written the Kubernetes manifests yet, so every deploy would be typed by hand from a long document. That invites mistakes in the things that matter most: which paths are public, where secrets come from, and which image version runs.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Add a `deploy/k8s/` folder with Kustomize manifests for the whole system:
|
||||
- a Deployment and a Service for each of the ten images in `docs/deployment.md` section 1, with the names, ports, health probes and settings it lists;
|
||||
- a `prod` overlay that pins every image to one commit SHA, sets the plain settings, and routes the public host through Traefik with TLS.
|
||||
- Expose only two things to the internet: the admin portal, and mobile-api's WhatsApp webhook path. Nothing else gets a route.
|
||||
- Keep every secret out of git. The manifests only refer to Secrets and mounted files by name. Add a checked-in template and a script that creates them from local files the deployer fills in and never commits.
|
||||
- Add a check script, run locally and in CI, that renders the manifests and fails if:
|
||||
- a route reaches anything other than the portal or the webhook path;
|
||||
- an image uses `latest`;
|
||||
- a Secret value appears in the rendered output;
|
||||
- service-counter has more than one replica.
|
||||
- Update `docs/deployment.md` so the deploy steps use the manifests (`kubectl apply -k`) instead of describing them in prose. Add the rollback steps.
|
||||
|
||||
Out of scope:
|
||||
- MySQL and Redis: the DBA's MySQL and the existing Redis stay outside the cluster manifests.
|
||||
- The Pub/Sub project and key.
|
||||
- Choosing an email provider.
|
||||
- Connecting WhatsApp in Meta.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `cluster-deployment`: how Co-Lite is described and rolled out on Kubernetes. It covers what is exposed publicly, how secrets are supplied, how image versions are pinned, and how a release is rolled back.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
None. `release-packaging` (how images are built and published) does not change.
|
||||
|
||||
## Impact
|
||||
|
||||
- **New:** `deploy/k8s/` (base and `prod` overlay), `deploy/k8s/secrets.example/`, `deploy/check.sh`.
|
||||
- **Changed:** `docs/deployment.md` and `.gitea/workflows/ci.yml` (one manifest-check step).
|
||||
- **No application code changes.**
|
||||
- **No new dependencies in the repo.** The check runs `kubectl kustomize` and kubeconform from pinned container images, so the machine needs only Docker.
|
||||
- **The real cluster needs:**
|
||||
- Traefik, with its IngressRoute CRD;
|
||||
- a pull secret for `gitea.containerverse.dev`;
|
||||
- the DNS record for `co-lite.containerverse.dev`.
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
|
||||
Describe how Co-Lite is rolled out to Kubernetes from manifests in the repository, so that public exposure, secrets, image versions and rollback are fixed in reviewed files rather than typed by hand.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: One manifest set deploys the whole system
|
||||
|
||||
The repository SHALL hold Kubernetes manifests that create a Deployment and a Service for each published image. The Service names and ports MUST be the ones the gateway, mobile-api and the portal already expect (`docs/deployment.md` section 1). Each Java service MUST have liveness and readiness probes on its actuator health endpoints. The admin portal MUST have a probe that needs no session.
|
||||
|
||||
#### Scenario: Apply brings every service up
|
||||
|
||||
- **GIVEN** a cluster where the Secrets, the mounted files, the database and the image pull secret already exist
|
||||
- **WHEN** the deployer applies the `prod` overlay
|
||||
- **THEN** a Deployment and a Service exist for all ten images under the expected names and ports
|
||||
- **AND** every pod becomes ready
|
||||
|
||||
#### Scenario: Unhealthy pod gets no traffic
|
||||
|
||||
- **GIVEN** a Java service whose readiness endpoint reports down
|
||||
- **WHEN** Kubernetes checks the pod
|
||||
- **THEN** the pod is not ready and its Service sends it no requests
|
||||
|
||||
### Requirement: Only the portal and the WhatsApp webhook are public
|
||||
|
||||
The manifests SHALL route the public host, over TLS, to the admin-portal Service. They SHALL route exactly the path `/api/public/whatsapp/webhook` to the mobile-api Service. No other Service may be reachable from outside the cluster. The repository's manifest check MUST fail when a route targets any other Service or path.
|
||||
|
||||
#### Scenario: Gateway is not reachable from the internet
|
||||
|
||||
- **WHEN** the rendered `prod` manifests are checked
|
||||
- **THEN** no route targets `api-gateway` or any `service-*`
|
||||
- **AND** the only route to `mobile-api` matches exactly `/api/public/whatsapp/webhook`
|
||||
|
||||
#### Scenario: A new route is caught
|
||||
|
||||
- **GIVEN** a manifest change that adds a route to `api-gateway`
|
||||
- **WHEN** the manifest check runs
|
||||
- **THEN** it fails and names the route
|
||||
|
||||
### Requirement: Secrets never enter the repository
|
||||
|
||||
The manifests SHALL refer to Secrets and mounted files only by name. The repository MUST NOT hold any real secret value. Secret templates hold placeholders only. The script that creates the Secrets MUST read the values from files that git ignores.
|
||||
|
||||
#### Scenario: Rendered manifests hold no secret data
|
||||
|
||||
- **WHEN** the `prod` overlay is rendered
|
||||
- **THEN** it contains no `Secret` object with data
|
||||
- **AND** the manifest check fails if one appears
|
||||
|
||||
#### Scenario: Filled-in secret files cannot be committed
|
||||
|
||||
- **GIVEN** a deployer who fills in the secret files under the secrets folder
|
||||
- **WHEN** they run `git status`
|
||||
- **THEN** those files are ignored
|
||||
|
||||
### Requirement: Releases are pinned by commit and can be rolled back
|
||||
|
||||
The `prod` overlay SHALL pin every image to one commit SHA, never `latest`. Rolling back MUST be done by setting the previous SHA and applying again. The deployment docs MUST describe both steps. Before a real apply, a release check MUST refuse any cluster fact still left as a placeholder.
|
||||
|
||||
#### Scenario: latest is refused
|
||||
|
||||
- **GIVEN** a `prod` overlay where an image tag is `latest` or missing
|
||||
- **WHEN** the manifest check runs
|
||||
- **THEN** it fails and names the image
|
||||
|
||||
#### Scenario: Unfilled cluster fact refused before apply
|
||||
|
||||
- **GIVEN** a `prod` overlay that still holds a `<…>` placeholder, such as the MySQL host
|
||||
- **WHEN** the deployer runs the release check
|
||||
- **THEN** it fails and names each placeholder
|
||||
|
||||
#### Scenario: Roll back to the previous release
|
||||
|
||||
- **GIVEN** a release at SHA B that misbehaves, with SHA A deployed before it
|
||||
- **WHEN** the deployer sets the overlay to SHA A and applies it
|
||||
- **THEN** every Deployment rolls back to the SHA A images
|
||||
|
||||
### Requirement: Single-run jobs stay single
|
||||
|
||||
service-counter SHALL run as exactly one replica. It sends the daily follow-up summary, and two replicas would send it twice. The manifest check MUST fail when service-counter has more than one replica.
|
||||
|
||||
#### Scenario: Counter scaled by mistake
|
||||
|
||||
- **GIVEN** a manifest change that sets service-counter to two replicas
|
||||
- **WHEN** the manifest check runs
|
||||
- **THEN** it fails
|
||||
@@ -0,0 +1,84 @@
|
||||
# Tasks
|
||||
|
||||
## 1. Manifest check first (red)
|
||||
|
||||
- [x] 1.1 Add `deploy/check.sh` and its rule script.
|
||||
- The script renders `deploy/k8s/overlays/prod` with pinned kubectl and kubeconform images, then applies the four rules:
|
||||
- public routes reach only the portal and the exact webhook path;
|
||||
- no image on `latest` or without a tag;
|
||||
- no Secret data in the output;
|
||||
- service-counter has exactly one replica.
|
||||
- Add rule fixtures under `deploy/check-fixtures/`: one passing set and one failing set per rule.
|
||||
- Verify: `deploy/check.sh --self-test` fails each bad fixture with a message naming the offending object, and passes the good one.
|
||||
- Running it against the still-missing overlay fails.
|
||||
- Done: 12 fixtures (one per rule, plus `bad-placeholder.yaml` for `--release`). The first red run passed on an empty render, so the container now stops on the first error, and `--full` requires all ten Deployments and Services.
|
||||
|
||||
## 2. Base manifests
|
||||
|
||||
- [x] 2.1 Add `deploy/k8s/base/`: a Deployment and a Service for each of the ten images, with the names, ports, probes, environment (secret refs and plain values) and mounts from `docs/deployment.md` sections 1, 6 and 7.
|
||||
- service-counter: one replica, `strategy: Recreate`.
|
||||
- Verify: `kubectl kustomize deploy/k8s/base`, run in the check container, renders the ten Deployments and ten Services. kubeconform passes.
|
||||
- Done: 20 resources, all valid. The probe paths were checked against the running local containers. Two fixes came out of that:
|
||||
- mobile-api answered 404 on liveness and readiness, so `MANAGEMENT_HEALTH_PROBES_ENABLED=true` is now in the settings;
|
||||
- service-email's overall health is 503 without a mail server, so the startup probe uses the liveness path.
|
||||
- [x] 2.2 Cross-check the base against `local/docker-compose.yml`: every variable a service reads locally is either set or deliberately left unset in the base.
|
||||
- Verify: a scripted diff of the variable names per service shows no unexplained gaps. Record the deliberate ones in `docs/deployment.md`.
|
||||
- Done: every `${…}` in each `application.yml` is supplied. Deliberately unset: the email keys, `SMSS360_EMAIL`, `CUSTOMER_PORTAL_BASE_URL`, Jumio, and `XXL_JOB_TOKEN` (listed in section 2).
|
||||
- The WhatsApp Secret reference is `optional: true`, so mobile-api starts while WhatsApp is off.
|
||||
|
||||
## 3. Prod overlay, release pinning and routes
|
||||
|
||||
- [x] 3.1 Add `deploy/k8s/overlays/prod/`. It sets:
|
||||
- the namespace;
|
||||
- the `images:` list with one SHA for all ten images;
|
||||
- the plain settings (`ADMIN_PORTAL_BASE_URL`, `REDISHOST`, `MYSQLHOST`, `GCP_PROJECT` and the rest);
|
||||
- the pull secret;
|
||||
- two Traefik IngressRoutes with TLS.
|
||||
|
||||
Verify: `deploy/check.sh` passes on the overlay (task 1 goes green).
|
||||
- [x] 3.2 Add `deploy/set-release.sh <sha>`, which rewrites the overlay's ten tags.
|
||||
- Verify: run it with a test SHA, then confirm that `check.sh` passes and `git diff` shows exactly ten tag lines changed. Running it with `latest` or a non-hex value is refused.
|
||||
- Done: ten lines change. Running it with `latest` or a short SHA is refused.
|
||||
- An all-digit SHA broke the render (YAML read it as a number), so the tags are now quoted. `2222…` and `1e45…` both render and pass.
|
||||
|
||||
## 4. Secrets
|
||||
|
||||
- [x] 4.1 Add `deploy/k8s/secrets.example/`: one `.env` template per Secret, plus an `appkeys.json` and a `key.json` placeholder, all with placeholders only.
|
||||
- Add `deploy/k8s/secrets/` to `.gitignore`.
|
||||
- Verify: a filled-in file under `deploy/k8s/secrets/` is listed by `git check-ignore`.
|
||||
- [x] 4.2 Add `deploy/create-secrets.sh`. It creates or updates each Secret through `kubectl create ... --dry-run=client -o yaml | kubectl apply -f -`. It refuses if a template key is missing or still holds a placeholder, and it never prints a value.
|
||||
- Verify: run it with `--dry-run` against a filled test folder; it prints only the Secret names and the key names.
|
||||
- Verify: a missing key is refused, and the refusal names the key.
|
||||
- Done: the dry run lists seven Secrets with their key names only. A missing `MYSQLPWD` is refused, and so is a placeholder `MYSQLPWD`.
|
||||
- The real path ran in the check container, with `kubectl apply` stubbed:
|
||||
- the `co-lite` namespace is created first, because the first run comes before any apply;
|
||||
- seven Secrets carry the right keys and decode to the filled values;
|
||||
- the registry Secret is a dockerconfigjson for `gitea.containerverse.dev`;
|
||||
- no value appears on stdout.
|
||||
- mobile-api's probes were proven on a throwaway container. Without `MANAGEMENT_HEALTH_PROBES_ENABLED` its liveness and readiness paths are missing; with it, all three return 200.
|
||||
|
||||
## 5. CI and docs
|
||||
|
||||
- [x] 5.1 Add a `deploy/check.sh` step to `.gitea/workflows/ci.yml`, before the image push.
|
||||
- Verify: the workflow file parses, and the step runs locally with the same command.
|
||||
- [x] 5.2 Rewrite the deploy steps in `docs/deployment.md` (sections 2 and 9) around the manifests:
|
||||
- create the Secrets, set the release, run the check, apply, wait for the rollout;
|
||||
- roll back;
|
||||
- list the open cluster facts from `design.md`.
|
||||
|
||||
Verify: following the doc's commands in order against the check container renders and passes.
|
||||
|
||||
## 6. Verification
|
||||
|
||||
- [x] 6.1 Run the full check: `deploy/check.sh` and its self-test, the repository's existing build and tests (unchanged), and `openspec validate add-k8s-deployment --strict`.
|
||||
- Done: the check and the self-test pass, and `openspec validate --strict` passes.
|
||||
- Maven and vitest were not re-run: no module source or build file changed. Only `deploy/`, `docs/`, `.gitignore` and the CI file changed.
|
||||
- [ ] 6.2 Run a server-side dry run against the real cluster: `kubectl apply -k deploy/k8s/overlays/prod --dry-run=server`, by the owner or with the owner's cluster access. Record the result here.
|
||||
- This needs the open cluster facts filled in and access to the cluster. If access is not available before archive, leave the task unticked with a note, as was done for the WhatsApp e2e.
|
||||
- Open (2026-12-03): there is no cluster access from this machine, and the cluster facts are not yet given. Owed by the owner with the first real apply.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Branch from `origin/main`, then open a PR to `main` and merge it.
|
||||
- Archive the change on its own branch, with its own PR.
|
||||
- The first real apply happens with the owner, after the database package and Secrets are in place.
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-03
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,88 @@
|
||||
# cluster-deployment Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Describe how Co-Lite is rolled out to Kubernetes from manifests in the repository, so that public exposure, secrets, image versions and rollback are fixed in reviewed files rather than typed by hand.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: One manifest set deploys the whole system
|
||||
|
||||
The repository SHALL hold Kubernetes manifests that create a Deployment and a Service for each published image. The Service names and ports MUST be the ones the gateway, mobile-api and the portal already expect (`docs/deployment.md` section 1). Each Java service MUST have liveness and readiness probes on its actuator health endpoints. The admin portal MUST have a probe that needs no session.
|
||||
|
||||
#### Scenario: Apply brings every service up
|
||||
|
||||
- **GIVEN** a cluster where the Secrets, the mounted files, the database and the image pull secret already exist
|
||||
- **WHEN** the deployer applies the `prod` overlay
|
||||
- **THEN** a Deployment and a Service exist for all ten images under the expected names and ports
|
||||
- **AND** every pod becomes ready
|
||||
|
||||
#### Scenario: Unhealthy pod gets no traffic
|
||||
|
||||
- **GIVEN** a Java service whose readiness endpoint reports down
|
||||
- **WHEN** Kubernetes checks the pod
|
||||
- **THEN** the pod is not ready and its Service sends it no requests
|
||||
|
||||
### Requirement: Only the portal and the WhatsApp webhook are public
|
||||
|
||||
The manifests SHALL route the public host, over TLS, to the admin-portal Service. They SHALL route exactly the path `/api/public/whatsapp/webhook` to the mobile-api Service. No other Service may be reachable from outside the cluster. The repository's manifest check MUST fail when a route targets any other Service or path.
|
||||
|
||||
#### Scenario: Gateway is not reachable from the internet
|
||||
|
||||
- **WHEN** the rendered `prod` manifests are checked
|
||||
- **THEN** no route targets `api-gateway` or any `service-*`
|
||||
- **AND** the only route to `mobile-api` matches exactly `/api/public/whatsapp/webhook`
|
||||
|
||||
#### Scenario: A new route is caught
|
||||
|
||||
- **GIVEN** a manifest change that adds a route to `api-gateway`
|
||||
- **WHEN** the manifest check runs
|
||||
- **THEN** it fails and names the route
|
||||
|
||||
### Requirement: Secrets never enter the repository
|
||||
|
||||
The manifests SHALL refer to Secrets and mounted files only by name. The repository MUST NOT hold any real secret value. Secret templates hold placeholders only. The script that creates the Secrets MUST read the values from files that git ignores.
|
||||
|
||||
#### Scenario: Rendered manifests hold no secret data
|
||||
|
||||
- **WHEN** the `prod` overlay is rendered
|
||||
- **THEN** it contains no `Secret` object with data
|
||||
- **AND** the manifest check fails if one appears
|
||||
|
||||
#### Scenario: Filled-in secret files cannot be committed
|
||||
|
||||
- **GIVEN** a deployer who fills in the secret files under the secrets folder
|
||||
- **WHEN** they run `git status`
|
||||
- **THEN** those files are ignored
|
||||
|
||||
### Requirement: Releases are pinned by commit and can be rolled back
|
||||
|
||||
The `prod` overlay SHALL pin every image to one commit SHA, never `latest`. Rolling back MUST be done by setting the previous SHA and applying again. The deployment docs MUST describe both steps. Before a real apply, a release check MUST refuse any cluster fact still left as a placeholder.
|
||||
|
||||
#### Scenario: latest is refused
|
||||
|
||||
- **GIVEN** a `prod` overlay where an image tag is `latest` or missing
|
||||
- **WHEN** the manifest check runs
|
||||
- **THEN** it fails and names the image
|
||||
|
||||
#### Scenario: Unfilled cluster fact refused before apply
|
||||
|
||||
- **GIVEN** a `prod` overlay that still holds a `<…>` placeholder, such as the MySQL host
|
||||
- **WHEN** the deployer runs the release check
|
||||
- **THEN** it fails and names each placeholder
|
||||
|
||||
#### Scenario: Roll back to the previous release
|
||||
|
||||
- **GIVEN** a release at SHA B that misbehaves, with SHA A deployed before it
|
||||
- **WHEN** the deployer sets the overlay to SHA A and applies it
|
||||
- **THEN** every Deployment rolls back to the SHA A images
|
||||
|
||||
### Requirement: Single-run jobs stay single
|
||||
|
||||
service-counter SHALL run as exactly one replica. It sends the daily follow-up summary, and two replicas would send it twice. The manifest check MUST fail when service-counter has more than one replica.
|
||||
|
||||
#### Scenario: Counter scaled by mistake
|
||||
|
||||
- **GIVEN** a manifest change that sets service-counter to two replicas
|
||||
- **WHEN** the manifest check runs
|
||||
- **THEN** it fails
|
||||
@@ -63,7 +63,7 @@ A page save SHALL be refused with the offending field path, writing nothing, whe
|
||||
|
||||
### Requirement: Block References Stay Inside The Company
|
||||
|
||||
A block's image SHALL be an image of the page's company, and a FORM block's event SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
|
||||
A block's image SHALL be an image of the page's company, and the event of a FORM block or of a HERO block that names one SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
|
||||
|
||||
#### Scenario: Another company's event
|
||||
|
||||
@@ -71,6 +71,12 @@ A block's image SHALL be an image of the page's company, and a FORM block's even
|
||||
- **WHEN** INS staff save a FORM block pointing at `CV Roadshow`
|
||||
- **THEN** the save is refused on that block's event field
|
||||
|
||||
#### Scenario: Another company's event in a hero
|
||||
|
||||
- **GIVEN** event `CV Roadshow` belongs to CV
|
||||
- **WHEN** INS staff save a HERO block whose event is `CV Roadshow`
|
||||
- **THEN** the save is refused on that block's event field
|
||||
|
||||
### Requirement: Page Content Cannot Run Scripts
|
||||
|
||||
A button SHALL have both a label and a link or neither. The link SHALL start with a single `/`, `https://`, `mailto:`, `tel:`, or `#` plus a valid block link name. A save SHALL be refused when RICH_TEXT or IMAGE_TEXT HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise that HTML against an allow-list. HTML blocks are exempt: they only run sealed.
|
||||
@@ -209,7 +215,7 @@ Pages and page images SHALL follow the company scoping rules: staff see, edit an
|
||||
|
||||
### Requirement: The Page Editor
|
||||
|
||||
The editor SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status and the block list. Blocks SHALL be added, moved up or down and removed. A chosen image SHALL be uploaded only when the page is saved. A FORM block SHALL pick from the company's enabled events that have not ended.
|
||||
At 1024 px and wider the editor SHALL be the on-page editor. Below 1024 px it SHALL be the form editor. Both SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status, adding, moving and removing blocks, and images uploaded only on save. A FORM block SHALL pick from the company's enabled events that have not ended.
|
||||
|
||||
#### Scenario: Slug follows the title until edited
|
||||
|
||||
@@ -217,14 +223,25 @@ The editor SHALL offer the title, a slug filled from the title until edited, a m
|
||||
- **WHEN** staff type the title "Hotel Technology"
|
||||
- **THEN** the slug becomes `hotel-technology`
|
||||
|
||||
#### Scenario: Narrow window keeps the form
|
||||
|
||||
- **WHEN** staff open a page in a window 900 px wide
|
||||
- **THEN** the form editor shows, with Preview
|
||||
|
||||
### Requirement: Saving And Deleting In The Editor
|
||||
|
||||
Server field errors SHALL show next to their fields, keeping all entered values. After a save the editor SHALL offer a link to view the page. Deleting a page SHALL ask first, and unsaved edits SHALL be guarded.
|
||||
Server field errors SHALL show at their fields, keeping all entered values. After a save the editor SHALL offer a link to view the page. Deleting a page SHALL ask first. With unsaved edits, reloading, closing and following an in-app link SHALL ask first.
|
||||
|
||||
#### Scenario: Server error at its field
|
||||
|
||||
- **WHEN** staff save a HERO button link `javascript:alert(1)`
|
||||
- **THEN** the error shows next to that button link and every entered value stays
|
||||
- **THEN** the error shows at that button link and every entered value stays
|
||||
|
||||
#### Scenario: Leaving by an in-app link
|
||||
|
||||
- **GIVEN** staff changed a heading and did not save
|
||||
- **WHEN** they click Pages in the menu
|
||||
- **THEN** the editor asks before leaving, and Cancel keeps them on the page with the change
|
||||
|
||||
### Requirement: Custom HTML Runs Sealed
|
||||
|
||||
@@ -276,13 +293,20 @@ The frame SHALL grow to fit its content, between 100 and 20000 pixels, using hei
|
||||
|
||||
### Requirement: The Custom HTML Block In The Editor
|
||||
|
||||
The editor SHALL offer "Add Custom HTML", which adds an HTML block with a monospace text box, a 200000-character counter and a note that forms inside the pasted HTML do not send and the sign-up form block collects leads. The editor SHALL also offer a "hide page header" switch for the page.
|
||||
The editor SHALL offer adding a Custom HTML block, edited in a monospace text box with a 200000-character counter and a note that forms inside it do not send. On the canvas the block SHALL show its last saved version as a sealed frame, marked "Save to update" while its HTML has unsaved edits. The editor SHALL offer a "hide page header" switch.
|
||||
|
||||
#### Scenario: Adding a Custom HTML block
|
||||
|
||||
- **WHEN** staff add a Custom HTML block and paste HTML into it
|
||||
- **THEN** the block shows the pasted HTML, the character count and the note about forms
|
||||
|
||||
#### Scenario: Unsaved HTML on the canvas
|
||||
|
||||
- **GIVEN** a saved page with a Custom HTML block
|
||||
- **WHEN** staff change its HTML in the panel
|
||||
- **THEN** the canvas marks the block "Save to update"
|
||||
- **AND** after Save the canvas shows the new HTML
|
||||
|
||||
#### Scenario: Hiding the header
|
||||
|
||||
- **WHEN** staff turn on "hide page header" and save
|
||||
@@ -412,13 +436,13 @@ A HERO block MAY have no image; it then shows its heading, text and button on it
|
||||
|
||||
### Requirement: New Sections In The Editor
|
||||
|
||||
The page editor SHALL offer adding FEATURES, STEPS, TRUST and CTA blocks, editing their fields, adding, removing and reordering cards, and choosing any block's look. Refusals SHALL show at the field they name, including card fields.
|
||||
Both editors SHALL offer adding FEATURES, STEPS, TRUST and CTA blocks, editing their fields, adding, removing and reordering cards, and choosing any block's look. Refusals SHALL show at the field they name, including card fields.
|
||||
|
||||
#### Scenario: A refused card title shows at its field
|
||||
|
||||
- **GIVEN** staff editing a page with a FEATURES block
|
||||
- **WHEN** the save is refused on field `blocks[0].cards[1].title`
|
||||
- **THEN** the message shows under the second card's title field
|
||||
- **THEN** the message shows at the second card's title field
|
||||
|
||||
### Requirement: Published Pages Keep A Separate Draft
|
||||
|
||||
@@ -483,3 +507,101 @@ Duplicate SHALL open the editor with a copy of the page's current content (its d
|
||||
- **GIVEN** INS page `hotel` titled "Hotel day"
|
||||
- **WHEN** staff press Duplicate on it and save
|
||||
- **THEN** a new draft INS page `hotel-copy` titled "Hotel day (copy)" exists with the same sections
|
||||
|
||||
### Requirement: The Page Canvas
|
||||
|
||||
The on-page editor SHALL show the page on a canvas, rendered as visitors see it, with a Desktop view (1280 px wide, scaled to fit) and a Phone view (390 px wide). Changes SHALL show on the canvas as they are made, before saving. Links and buttons on the canvas SHALL NOT navigate, and the sign-up form SHALL show its preview note.
|
||||
|
||||
#### Scenario: Phone view uses the phone layout
|
||||
|
||||
- **GIVEN** a page with a FEATURES block of three cards
|
||||
- **WHEN** staff switch to Phone
|
||||
- **THEN** the cards stack in one column on the canvas
|
||||
|
||||
#### Scenario: A change shows before saving
|
||||
|
||||
- **WHEN** staff change a FEATURES card title in the side panel
|
||||
- **THEN** the canvas shows the new title at once
|
||||
|
||||
### Requirement: Edit Text On The Page
|
||||
|
||||
Clicking a heading, short text, button label, card title or text, or FAQ question or answer on the canvas SHALL edit it in place as plain text, with the server's length limit shown when close. Rich text SHALL be edited in place with bold, italic, link, lists and alignment, and links SHALL follow the page link rule. An empty field SHALL show a faded cue naming it, and empty rich text SHALL keep room to click into. Clicking an image spot SHALL open the file picker.
|
||||
|
||||
#### Scenario: Edit a heading in place
|
||||
|
||||
- **WHEN** staff click the hero heading on the canvas and type "Hotel week"
|
||||
- **THEN** the canvas and the side panel show "Hotel week"
|
||||
|
||||
#### Scenario: An unsafe link is refused in rich text
|
||||
|
||||
- **WHEN** staff add the link `javascript:alert(1)` in a Text block on the canvas
|
||||
- **THEN** the link is not added and the toolbar says why
|
||||
|
||||
### Requirement: Section Selection And Actions
|
||||
|
||||
Clicking a section on the canvas SHALL select it, outline it and show its settings in the side panel. With none selected, the panel SHALL show the page settings. A selected section SHALL offer drag, up, down, duplicate and delete. "Add section" between sections and at the end SHALL offer every block type. Up and down SHALL work from the keyboard. A section that is added, duplicated or moved SHALL be brought into view on the canvas.
|
||||
|
||||
#### Scenario: Duplicate a section
|
||||
|
||||
- **WHEN** staff select the second section and press Duplicate
|
||||
- **THEN** a copy appears as the third section and is selected
|
||||
|
||||
#### Scenario: Add a section between two
|
||||
|
||||
- **WHEN** staff press Add section between the first and second sections and choose Steps
|
||||
- **THEN** a Steps section appears second and is selected
|
||||
|
||||
#### Scenario: Add a section from the side panel
|
||||
|
||||
- **GIVEN** the canvas shows the top of a long page
|
||||
- **WHEN** staff press Add Text in the side panel
|
||||
- **THEN** the canvas scrolls to the new Text section at the end, which shows a faded "Content" cue to type into
|
||||
|
||||
### Requirement: Undo And Redo
|
||||
|
||||
The on-page editor SHALL undo and redo page changes, up to 50 steps, by buttons and by Ctrl+Z and Ctrl+Shift+Z. The keys SHALL work wherever focus is in the editor, including after the focused control is removed or disabled, except inside a field outside the editor. Typing in one field SHALL be one step. Saving SHALL NOT clear the history.
|
||||
|
||||
#### Scenario: Undo a delete
|
||||
|
||||
- **GIVEN** staff deleted the FAQ section
|
||||
- **WHEN** they press Ctrl+Z
|
||||
- **THEN** the FAQ section is back in its place with its content
|
||||
|
||||
### Requirement: Refusals On The Canvas
|
||||
|
||||
When a save or publish is refused on a block field, the editor SHALL select that block, outline it, scroll it into view and show the message at the field in the side panel. A refusal on a page field SHALL show in the page settings.
|
||||
|
||||
#### Scenario: A form without an event
|
||||
|
||||
- **GIVEN** a page from the Event sign-up template
|
||||
- **WHEN** staff save without choosing the form's event
|
||||
- **THEN** the form section is selected and outlined and the panel shows the message at the Event field
|
||||
|
||||
### Requirement: Hero With A Sign-Up Form
|
||||
|
||||
A HERO block MAY name an event. When it does, the hero SHALL show Co-Lite's sign-up form for that event in a card beside its heading, text and button on wide screens, and below them on narrow screens. The hero's form SHALL follow every rule of the FORM block (see "The Form Block Registers For An Event" and "The Form Block Closes With Its Event"). A HERO block without an event SHALL show no form.
|
||||
|
||||
#### Scenario: Sign up from the hero
|
||||
|
||||
- **GIVEN** page `/p/INS/hotel-technology` has a HERO block whose event is `INS website enquiries`
|
||||
- **WHEN** a new visitor submits the form in the hero from a URL with `utm_source=facebook`
|
||||
- **THEN** a new lead and an event lead with source Web page, no salesperson and UTM source `facebook` are created
|
||||
|
||||
#### Scenario: Hero form closes with its event
|
||||
|
||||
- **GIVEN** the HERO block's event ended yesterday
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the hero still shows its heading and text, and its form area says sign-up is closed
|
||||
|
||||
#### Scenario: Hero without an event
|
||||
|
||||
- **WHEN** a visitor opens a page whose HERO block names no event
|
||||
- **THEN** the hero shows no form
|
||||
- **AND** a submit addressed to that block is refused as not found
|
||||
|
||||
#### Scenario: Pick the hero's event in the editor
|
||||
|
||||
- **GIVEN** staff editing a page with a HERO block
|
||||
- **WHEN** they pick `INS website enquiries` under the hero's sign-up form setting
|
||||
- **THEN** the canvas shows the form card beside the hero text
|
||||
- **AND** choosing "No form" removes it
|
||||
@@ -6,6 +6,7 @@ import { BLOCK_LABELS, ICONS, LOOKS, imageSrc, type CmsBlock, type CmsCard, type
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { Switch } from "@/app/components/ui/switch";
|
||||
import { Textarea } from "@/app/components/ui/textarea";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { RichTextEditor } from "./RichTextEditor";
|
||||
@@ -14,7 +15,7 @@ import { RichTextEditor } from "./RichTextEditor";
|
||||
|
||||
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. Every type also shows "anchor". */
|
||||
const INLINE: Record<string, string[]> = {
|
||||
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl"],
|
||||
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl", "eventUuid", "fullWidth", "formHeading", "formText", "cards"],
|
||||
RICH_TEXT: ["html"],
|
||||
IMAGE_TEXT: ["imageId", "imagePosition", "heading", "html", "buttonLabel", "buttonUrl"],
|
||||
FAQ: ["heading", "items"],
|
||||
@@ -34,10 +35,12 @@ const ICON_LABELS: Record<string, string> = {
|
||||
"shield-check": "PagesIconShieldCheck", cloud: "PagesIconCloud", wrench: "PagesIconWrench", headset: "PagesIconHeadset",
|
||||
users: "PagesIconUsers", calendar: "PagesIconCalendar", star: "PagesIconStar",
|
||||
};
|
||||
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; empty: CmsCard }> = {
|
||||
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, empty: { icon: "star", title: "", text: "" } },
|
||||
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, empty: { title: "", text: "" } },
|
||||
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, empty: { title: "" } },
|
||||
// add-hero-full-width: a hero's points are title-only cards, and it may have none.
|
||||
const CARD_KINDS: Record<string, { legend: string; add: string; icon: boolean; text: boolean; min: number; empty: CmsCard }> = {
|
||||
FEATURES: { legend: "PagesCardN", add: "PagesAddCard", icon: true, text: true, min: 2, empty: { icon: "star", title: "", text: "" } },
|
||||
STEPS: { legend: "PagesStepN", add: "PagesAddStep", icon: false, text: true, min: 2, empty: { title: "", text: "" } },
|
||||
TRUST: { legend: "PagesItemN", add: "PagesAddItem", icon: false, text: false, min: 2, empty: { title: "" } },
|
||||
HERO: { legend: "PagesPointN", add: "PagesAddPoint", icon: false, text: false, min: 0, empty: { title: "" } },
|
||||
};
|
||||
const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
|
||||
|
||||
@@ -83,7 +86,7 @@ export function BlockFields(props: {
|
||||
const fid = (name: string) => `block-${id}-${name}`;
|
||||
const topErrors = Object.entries(errors).filter(([path]) => path !== "anchor" && path !== "look" && !INLINE[block.type]?.includes(path) && !LISTED.test(path));
|
||||
|
||||
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor", labelCode: string) => (
|
||||
const text = (name: "heading" | "text" | "buttonLabel" | "buttonUrl" | "anchor" | "formHeading" | "formText", labelCode: string) => (
|
||||
<Field id={fid(name)} label={t(labelCode)} error={errors[name]}>
|
||||
<Input id={fid(name)} value={block[name] ?? ""} disabled={saving} aria-invalid={!!errors[name]} onChange={(e) => set({ [name]: e.target.value })} />
|
||||
</Field>
|
||||
@@ -96,6 +99,20 @@ export function BlockFields(props: {
|
||||
);
|
||||
|
||||
const preview = pendingImage?.preview ?? (block.imageId ? imageSrc(block.imageId) : undefined);
|
||||
// The FORM block's event, and the hero's optional sign-up form (add-hero-signup-form): the same picker and hint.
|
||||
const eventPicker = (labelCode: string, emptyCode: string) => (
|
||||
<Field id={fid("event")} label={t(labelCode)} error={errors.eventUuid}>
|
||||
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
|
||||
onChange={(e) => set(e.target.value ? { eventUuid: e.target.value } : { eventUuid: null, formHeading: undefined, formText: undefined })}>
|
||||
<option value="">{t(emptyCode)}</option>
|
||||
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
|
||||
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? (
|
||||
<option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option>
|
||||
) : null}
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">{t("PagesFormEventHint")}</p>
|
||||
</Field>
|
||||
);
|
||||
const image = (
|
||||
<Field id={fid("image")} label={t("PagesImage")} error={errors.imageId}>
|
||||
<Input
|
||||
@@ -126,8 +143,8 @@ export function BlockFields(props: {
|
||||
<>
|
||||
{cards.map((card, i) => {
|
||||
const err = (f: string) => errors[`cards[${i}].${f}`];
|
||||
const cardField = (f: "title" | "text", labelCode: string, multiline: boolean) => (
|
||||
<Field id={fid(`c${i}${f}`)} label={t(labelCode)} error={err(f)}>
|
||||
const cardField = (f: "title" | "text", label: string, multiline: boolean) => (
|
||||
<Field id={fid(`c${i}${f}`)} label={label} error={err(f)}>
|
||||
{multiline
|
||||
? <Textarea id={fid(`c${i}${f}`)} rows={2} value={card[f] ?? ""} disabled={saving} aria-invalid={!!err(f)}
|
||||
onChange={(e) => setCards(cards.map((c, j) => (j === i ? { ...c, [f]: e.target.value } : c)))} />
|
||||
@@ -146,12 +163,12 @@ export function BlockFields(props: {
|
||||
</select>
|
||||
</Field>
|
||||
) : null}
|
||||
{cardField("title", "PagesCardTitle", false)}
|
||||
{kind.text ? cardField("text", "PagesCardText", true) : null}
|
||||
{cardField("title", kind.min ? t("PagesCardTitle") : t(kind.legend, { number: i + 1 }), false)}
|
||||
{kind.text ? cardField("text", t("PagesCardText"), true) : null}
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Button type="button" variant="ghost" size="sm" disabled={saving || i === 0} onClick={() => moveCard(i, -1)}>{t("PagesMoveUp")}</Button>
|
||||
<Button type="button" variant="ghost" size="sm" disabled={saving || i === cards.length - 1} onClick={() => moveCard(i, 1)}>{t("PagesMoveDown")}</Button>
|
||||
<Button type="button" variant="ghost" size="sm" disabled={saving || cards.length <= 2} onClick={() => setCards(cards.filter((_, j) => j !== i))}>{t("PagesRemoveCard")}</Button>
|
||||
<Button type="button" variant="ghost" size="sm" disabled={saving || cards.length <= kind.min} onClick={() => setCards(cards.filter((_, j) => j !== i))}>{t("PagesRemoveCard")}</Button>
|
||||
</div>
|
||||
</fieldset>
|
||||
);
|
||||
@@ -190,6 +207,18 @@ export function BlockFields(props: {
|
||||
{text("text", "PagesText")}
|
||||
{text("buttonLabel", "PagesButtonLabel")}
|
||||
{text("buttonUrl", "PagesButtonLink")}
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch id={fid("fullWidth")} checked={!!block.fullWidth} disabled={saving} onCheckedChange={(on) => set({ fullWidth: on || undefined })} />
|
||||
<Label htmlFor={fid("fullWidth")}>{t("PagesFullWidth")}</Label>
|
||||
</div>
|
||||
{cardList}
|
||||
{eventPicker("PagesHeroForm", "PagesNoForm")}
|
||||
{block.eventUuid ? (
|
||||
<>
|
||||
{text("formHeading", "PagesFormHeading")}
|
||||
{text("formText", "PagesFormText")}
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -249,17 +278,7 @@ export function BlockFields(props: {
|
||||
{block.type === "FORM" && (
|
||||
<>
|
||||
{text("heading", "PagesHeading")}
|
||||
<Field id={fid("event")} label={t("PagesFormEvent")} error={errors.eventUuid}>
|
||||
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
|
||||
onChange={(e) => set({ eventUuid: e.target.value || null })}>
|
||||
<option value="">{t("PagesChooseEvent")}</option>
|
||||
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
|
||||
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? (
|
||||
<option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option>
|
||||
) : null}
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">{t("PagesFormEventHint")}</p>
|
||||
</Field>
|
||||
{eventPicker("PagesFormEvent", "PagesChooseEvent")}
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -58,6 +58,18 @@ describe("LandingPage: Custom HTML", () => {
|
||||
expect(frame().style.height).toBe("2400px");
|
||||
});
|
||||
|
||||
// add-hero-full-width: the frame's first report can arrive before the page listens, so the page asks once it does.
|
||||
it("asks its frame for a height report once it listens, and again when the frame loads", () => {
|
||||
const sealed = { postMessage: vi.fn() };
|
||||
const getter = vi.spyOn(HTMLIFrameElement.prototype, "contentWindow", "get").mockReturnValue(sealed as unknown as Window);
|
||||
onTestFinished(() => getter.mockRestore());
|
||||
render(<LandingPage company={company} page={page([HTML])} />);
|
||||
expect(sealed.postMessage).toHaveBeenCalledWith({ type: "colite-frame-ask" }, "*");
|
||||
sealed.postMessage.mockClear();
|
||||
act(() => { frame().dispatchEvent(new Event("load")); });
|
||||
expect(sealed.postMessage).toHaveBeenCalledWith({ type: "colite-frame-ask" }, "*");
|
||||
});
|
||||
|
||||
it("grows inside another document too: it listens on its own document's window (add-page-visual-editor)", () => {
|
||||
const host = document.createElement("iframe");
|
||||
document.body.appendChild(host);
|
||||
@@ -80,6 +92,7 @@ describe("LandingPage: Custom HTML", () => {
|
||||
render(<LandingPage company={company} page={page([HTML], true)} />);
|
||||
const title = screen.getByRole("heading", { level: 1, name: "Hotel day" });
|
||||
expect(title.parentElement!.className).not.toMatch(/space-y/);
|
||||
expect(frame().parentElement!.className).toMatch(/space-y/);
|
||||
// add-hero-full-width: spacing is a top margin on each block row after the first, so the first row has none.
|
||||
expect(frame().closest("main > div > div")).not.toHaveClass("mt-10");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { LandingPage, type PublicBlock } from "./CmsBlocks";
|
||||
@@ -70,6 +70,77 @@ describe("LandingPage", () => {
|
||||
expect(JSON.parse(String((init as RequestInit).body))).toMatchObject({ name: "Tan", utmSource: "fb", utmMedium: "cpc", utmCampaign: "jan" });
|
||||
expect(await screen.findByText("Sign-up is closed.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// add-hero-signup-form: a hero with an event carries the sign-up form beside its text.
|
||||
it("a hero with an event shows the sign-up form inside the hero and posts to the hero's block", async () => {
|
||||
window.history.replaceState(null, "", "/p/INS/hotel?utm_source=fb");
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(new Response(JSON.stringify({ code: "FORM_CLOSED" }), { status: 409 }));
|
||||
const user = userEvent.setup();
|
||||
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77", form: info }])} />);
|
||||
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
|
||||
expect(hero).toContainElement(screen.getByLabelText("Your name"));
|
||||
await user.type(screen.getByLabelText("Your name"), "Tan");
|
||||
await user.type(screen.getByLabelText("Mobile number"), "0125550101");
|
||||
await user.click(screen.getByRole("checkbox"));
|
||||
await user.click(screen.getByRole("button", { name: "Register" }));
|
||||
expect(fetchMock.mock.calls[0][0]).toBe("/api/public/pages/INS/hotel/form/0");
|
||||
});
|
||||
|
||||
it("a hero whose form closed keeps its text and says so; a hero without an event has no form", () => {
|
||||
const { unmount } = render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77", closed: true }])} />);
|
||||
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
|
||||
expect(hero).toHaveTextContent("Sign-up is closed.");
|
||||
unmount();
|
||||
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "Plain" }])} />);
|
||||
expect(screen.queryByText("Sign-up is closed.")).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText("Your name")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("the preview of a hero with an event shows the form's note in the hero", () => {
|
||||
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77" }])} preview />);
|
||||
expect(screen.getByRole("heading", { name: "One partner" }).closest("section"))
|
||||
.toHaveTextContent("The sign-up form shows here on the published page.");
|
||||
});
|
||||
});
|
||||
|
||||
// add-hero-full-width: edge-to-edge hero, points, the form card's heading, and flush full-width neighbours.
|
||||
describe("LandingPage full-width hero", () => {
|
||||
const ins = { type: "HERO" as const, heading: "One partner", fullWidth: true, eventUuid: "77", closed: true,
|
||||
cards: [{ title: "One accountable partner" }, { title: "Local support team in Malaysia" }],
|
||||
formHeading: "Get a free consultation", formText: "Tell us about your property." };
|
||||
|
||||
it("runs outside the page width with square corners; a plain hero stays boxed in the page width", () => {
|
||||
render(<LandingPage company={company} page={page([ins, { type: "HERO", heading: "Boxed" }])} />);
|
||||
const wide = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
|
||||
expect(wide.closest(".max-w-5xl")).toBeNull();
|
||||
expect(wide).not.toHaveClass("rounded-lg");
|
||||
const boxed = screen.getByRole("heading", { name: "Boxed" }).closest("section")!;
|
||||
expect(boxed.closest(".max-w-5xl")).not.toBeNull();
|
||||
expect(boxed).toHaveClass("rounded-lg");
|
||||
});
|
||||
|
||||
it("shows its points as a list under the text", () => {
|
||||
render(<LandingPage company={company} page={page([ins])} />);
|
||||
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
|
||||
const items = within(hero).getAllByRole("listitem");
|
||||
expect(items.map((li) => li.textContent)).toEqual(["One accountable partner", "Local support team in Malaysia"]);
|
||||
});
|
||||
|
||||
it("starts the form card with its heading and text", () => {
|
||||
render(<LandingPage company={company} page={page([ins])} />);
|
||||
const title = screen.getByRole("heading", { name: "Get a free consultation" });
|
||||
const card = title.parentElement!.parentElement!;
|
||||
expect(card).toHaveTextContent(/^Get a free consultation\s*Tell us about your property\./);
|
||||
expect(card).toHaveTextContent("Sign-up is closed.");
|
||||
});
|
||||
|
||||
it("joins a Custom HTML block and a full-width hero with no gap; other blocks keep theirs", () => {
|
||||
render(<LandingPage company={company} frameBase="/f" page={page([
|
||||
{ type: "HTML", html: "<header>Top</header>" }, ins, { type: "HTML", html: "<p>Rest</p>" }, { type: "RICH_TEXT", html: "<p>After</p>" },
|
||||
])} />);
|
||||
const rows = Array.from(document.querySelector("main > div")!.children);
|
||||
expect(rows.map((r) => r.classList.contains("mt-10"))).toEqual([false, false, false, true]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("utmTags", () => {
|
||||
|
||||
@@ -46,19 +46,80 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
|
||||
const image = block.imageId ? imageSrc(block.imageId) : undefined;
|
||||
const button = <ButtonLink block={block} index={index} edit={edit} />;
|
||||
switch (block.type) {
|
||||
case "HERO":
|
||||
case "HERO": {
|
||||
const wide = !!block.fullWidth;
|
||||
const points = block.cards?.length ? (
|
||||
<ul className="space-y-2">
|
||||
{block.cards.map((card, i) => (
|
||||
<li key={i} className="flex items-baseline gap-3 before:size-2 before:shrink-0 before:rounded-full before:bg-primary">
|
||||
<Text as="span" index={index} path={`cards.${i}.title`} value={card.title} max={80} code="PagesPointN" n={i + 1} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null;
|
||||
const words = (
|
||||
<>
|
||||
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading"
|
||||
className={wide ? "font-serif text-4xl leading-tight font-semibold sm:text-5xl" : "text-3xl font-semibold sm:text-4xl"} />
|
||||
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg" />
|
||||
{points}
|
||||
<div>{button}</div>
|
||||
</>
|
||||
);
|
||||
// add-hero-signup-form: with an event, the sign-up form sits in a card beside the text (below it on phones).
|
||||
// add-hero-full-width: the card may open with its own heading and text.
|
||||
const card = block.eventUuid ? (
|
||||
<div className="space-y-4 rounded-lg border bg-card p-6 text-card-foreground shadow-card">
|
||||
{block.formHeading || block.formText || edit ? (
|
||||
<div className="space-y-1">
|
||||
<Text as="h3" index={index} path="formHeading" value={block.formHeading} max={80} code="PagesFormHeading" className="font-serif text-2xl font-semibold" />
|
||||
<Text as="p" index={index} path="formText" value={block.formText} max={200} code="PagesFormText" className="text-sm text-muted-foreground" />
|
||||
</div>
|
||||
) : null}
|
||||
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} />
|
||||
</div>
|
||||
) : null;
|
||||
const back = bandOf(block.look) ? "" : "bg-muted";
|
||||
if (wide) {
|
||||
// Edge to edge; the shade is darkest behind the text and clears toward the far side. The text is centred in the
|
||||
// hero's opening height, not beside a long form, so it stays in the first screen.
|
||||
const grid = `mx-auto grid w-full max-w-6xl items-start gap-8 px-4 pt-16 pb-12 ${card ? "md:grid-cols-[minmax(0,1fr)_minmax(0,28rem)]" : ""}`;
|
||||
return (
|
||||
<section className={`relative overflow-hidden ${back}`}>
|
||||
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
|
||||
<HeroShade index={index} image={!!image} shaded="relative bg-gradient-to-r from-black/75 via-black/45 to-black/10 text-white" plain="">
|
||||
<div className={grid}>
|
||||
<div className="flex flex-col justify-center gap-4 md:min-h-[32rem]">{words}</div>
|
||||
{card}
|
||||
</div>
|
||||
</HeroShade>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (card) {
|
||||
// Top padding leaves room for the editor's image button in the corner.
|
||||
const grid = "grid items-start gap-6 px-6 pt-16 pb-6 md:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] md:px-10 md:pb-10";
|
||||
return (
|
||||
<section className={`relative overflow-hidden rounded-lg ${back}`}>
|
||||
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
|
||||
<HeroShade index={index} image={!!image} shaded={`relative ${grid} bg-gradient-to-r from-black/80 via-black/60 to-black/40 text-white sm:min-h-96`} plain={grid}>
|
||||
<div className="flex flex-col gap-3">{words}</div>
|
||||
{card}
|
||||
</HeroShade>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className={`relative overflow-hidden rounded-lg ${bandOf(block.look) ? "" : "bg-muted"}`}>
|
||||
<section className={`relative overflow-hidden rounded-lg ${back}`}>
|
||||
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
|
||||
<HeroShade index={index} image={!!image}
|
||||
shaded="relative flex min-h-72 flex-col justify-end gap-3 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-6 text-white sm:min-h-96"
|
||||
plain="flex flex-col gap-3 p-6">
|
||||
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-3xl font-semibold sm:text-4xl" />
|
||||
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg" />
|
||||
<div>{button}</div>
|
||||
{words}
|
||||
</HeroShade>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
case "RICH_TEXT":
|
||||
return block.html || edit ? (
|
||||
<section><RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot></section>
|
||||
@@ -167,9 +228,14 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
|
||||
|
||||
const WIDTH = "mx-auto w-full max-w-5xl px-4";
|
||||
|
||||
/** Blocks that run the full window width: Custom HTML, and a full-width hero. Two of them in a row join with no gap. */
|
||||
const bleeds = (block: PublicBlock) => block.type === "HTML" || (block.type === "HERO" && !!block.fullWidth);
|
||||
|
||||
/** A block in the page width; with a non-default look, inside a full-width band of that colour. */
|
||||
function Section({ block, index, children }: { block: PublicBlock; index: number; children: ReactNode }) {
|
||||
const band = bandOf(block.look);
|
||||
// add-hero-full-width: a full-width hero sets its own width.
|
||||
if (bleeds(block)) return <EditSection index={index}><div id={anchorId(block.anchor)}>{children}</div></EditSection>;
|
||||
if (!band) return <EditSection index={index}><div id={anchorId(block.anchor)} className={WIDTH}>{children}</div></EditSection>;
|
||||
return (
|
||||
<EditSection index={index}>
|
||||
@@ -213,10 +279,14 @@ export function LandingPage({ company, page, banner, preview, frameBase, edit }:
|
||||
</header>}
|
||||
<main className={page.hideHeader ? "pb-8" : "py-8"}>
|
||||
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
|
||||
<div className="space-y-10">
|
||||
{page.blocks.map((block, i) => block.type === "HTML"
|
||||
? <HtmlSpot key={i} index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot>
|
||||
: <Section key={i} block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>)}
|
||||
<div>
|
||||
{page.blocks.map((block, i) => (
|
||||
<div key={i} className={i > 0 && !(bleeds(block) && bleeds(page.blocks[i - 1])) ? "mt-10" : undefined}>
|
||||
{block.type === "HTML"
|
||||
? <HtmlSpot index={i}><HtmlFrame id={anchorId(block.anchor)} src={`${frames}/${i}${edit ? `?v=${edit.frameVersion}` : ""}`} title={page.title} /></HtmlSpot>
|
||||
: <Section block={block} index={i}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} edit={!!edit} /></Section>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -102,7 +102,7 @@ export function ImageSpot({ index, src, className, corner }: { index: number; sr
|
||||
<>
|
||||
{img}
|
||||
<button type="button" aria-label={t("PagesImage")} onClick={open}
|
||||
className="absolute top-3 right-3 z-10 flex size-10 cursor-pointer items-center justify-center rounded-full bg-background/90 text-foreground shadow hover:bg-background">
|
||||
className="absolute top-3 left-3 z-10 flex size-10 cursor-pointer items-center justify-center rounded-full bg-background/90 text-foreground shadow hover:bg-background">
|
||||
<ImagePlus aria-hidden="true" className="size-5" />
|
||||
</button>
|
||||
</>
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
|
||||
import { FRAME_ASK_MESSAGE, FRAME_SANDBOX, frameAnchor, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
|
||||
|
||||
// add-hero-full-width: the frame may have reported before this page listened; ask on mount, and again when it loads.
|
||||
const ask = (frame: HTMLIFrameElement | null) => frame?.contentWindow?.postMessage({ type: FRAME_ASK_MESSAGE }, "*");
|
||||
|
||||
/** A Custom HTML block: the sealed frame, sized by height reports and scrolled to by #name requests from that frame's own window only. */
|
||||
export function HtmlFrame({ id, src, title }: { id?: string; src: string; title: string }) {
|
||||
@@ -22,7 +25,8 @@ export function HtmlFrame({ id, src, title }: { id?: string; src: string; title:
|
||||
if (block?.closest("main")) block.scrollIntoView({ behavior: "smooth" });
|
||||
};
|
||||
host.addEventListener("message", onMessage);
|
||||
ask(ref.current);
|
||||
return () => host.removeEventListener("message", onMessage);
|
||||
}, []);
|
||||
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
|
||||
return <iframe ref={ref} id={id} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" onLoad={(e) => ask(e.currentTarget)} className="block w-full border-0" style={{ height: `${size.height}px` }} />;
|
||||
}
|
||||
@@ -56,7 +56,8 @@ describe("PageEditor", () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
const picker = await screen.findByLabelText("Event");
|
||||
await waitFor(() => expect(screen.getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
|
||||
// Scoped to the FORM block's picker: since add-hero-signup-form the hero offers the same events in its own picker.
|
||||
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
|
||||
expect(screen.queryByRole("option", { name: "Old fair" })).not.toBeInTheDocument();
|
||||
expect(picker).toHaveValue("3312726793093644288");
|
||||
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel");
|
||||
@@ -106,6 +107,51 @@ describe("PageEditor", () => {
|
||||
expect(memoryRouter.push).toHaveBeenCalledWith("/pages");
|
||||
});
|
||||
|
||||
// add-hero-signup-form: the hero's own event picker, "No form" by default; its event is saved with the hero.
|
||||
it("gives a hero a sign-up form for a chosen event, and No form takes it away", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
const picker = await screen.findByLabelText("Sign-up form");
|
||||
expect(picker).toHaveValue("");
|
||||
expect(within(picker).getByRole("option", { name: "No form" })).toBeInTheDocument();
|
||||
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
|
||||
await user.selectOptions(picker, "3312726793093644288");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.savePage.mock.calls[0][1].blocks[0]).toMatchObject({ type: "HERO", eventUuid: "3312726793093644288" });
|
||||
await user.selectOptions(screen.getByLabelText("Sign-up form"), "");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(2));
|
||||
expect(mocks.savePage.mock.calls[1][1].blocks[0].eventUuid ?? null).toBeNull();
|
||||
});
|
||||
|
||||
// add-hero-full-width: Full width, points, and the form card's heading and text (only while the hero has a form).
|
||||
it("saves a full-width hero with points and a form heading; No form drops the heading and text", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
const picker = await screen.findByLabelText("Sign-up form");
|
||||
expect(screen.queryByLabelText("Form heading")).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("switch", { name: "Full width" }));
|
||||
await user.click(screen.getByRole("button", { name: "Add point" }));
|
||||
await user.type(screen.getByRole("textbox", { name: "Point 1" }), "Local support team");
|
||||
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
|
||||
await user.selectOptions(picker, "3312726793093644288");
|
||||
await user.type(screen.getByLabelText("Form heading"), "Get a free consultation");
|
||||
await user.type(screen.getByLabelText("Form text"), "It takes a minute.");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.savePage.mock.calls[0][1].blocks[0]).toMatchObject({
|
||||
type: "HERO", fullWidth: true, cards: [{ title: "Local support team" }],
|
||||
formHeading: "Get a free consultation", formText: "It takes a minute.",
|
||||
});
|
||||
await user.selectOptions(screen.getByLabelText("Sign-up form"), "");
|
||||
expect(screen.queryByLabelText("Form heading")).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(2));
|
||||
const hero = mocks.savePage.mock.calls[1][1].blocks[0];
|
||||
expect([hero.formHeading, hero.formText]).toEqual([undefined, undefined]);
|
||||
});
|
||||
|
||||
it("a super admin must choose a company for a new page", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: true, companyCode: null });
|
||||
const user = userEvent.setup();
|
||||
|
||||
@@ -49,6 +49,25 @@ describe("moveItem", () => {
|
||||
});
|
||||
|
||||
describe("usePageDraft for the on-page editor", () => {
|
||||
it("a company switch clears the event of every FORM block and of a hero's sign-up form", async () => {
|
||||
mocks.getPage.mockResolvedValueOnce({ ...stored, blocks: [
|
||||
{ type: "HERO" as const, heading: "Hi", eventUuid: "77" }, { type: "FORM" as const, eventUuid: "77" }, { type: "HERO" as const, heading: "Plain" },
|
||||
] });
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.changeCompany(3));
|
||||
expect(result.current.rows.map((r) => r.block.eventUuid ?? null)).toEqual([null, null, null]);
|
||||
});
|
||||
|
||||
// add-hero-full-width: the form card's heading and text go with the form, or the server refuses the save.
|
||||
it("a company switch also drops a hero's form heading and text", async () => {
|
||||
mocks.getPage.mockResolvedValueOnce({ ...stored, blocks: [
|
||||
{ type: "HERO" as const, heading: "Hi", eventUuid: "77", formHeading: "Get a free consultation", formText: "Quick." },
|
||||
] });
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.changeCompany(3));
|
||||
expect(result.current.rows[0].block).toEqual({ type: "HERO", heading: "Hi", eventUuid: null });
|
||||
});
|
||||
|
||||
it("keeps the company's branding from the loaded page", async () => {
|
||||
const { result } = await loaded();
|
||||
expect(result.current.branding).toEqual(stored.company);
|
||||
|
||||
@@ -191,11 +191,18 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
|
||||
step("page:title");
|
||||
setDraft((d) => withTitle(d, title));
|
||||
};
|
||||
/** A super admin's new page changes company: FORM blocks lose their event, which belongs to the old one. */
|
||||
/**
|
||||
* A super admin's new page changes company: FORM blocks and hero sign-up forms lose their event, which belongs to the old one,
|
||||
* and a hero's form heading and text go with its form (add-hero-full-width).
|
||||
*/
|
||||
const changeCompany = (companyId: number) => {
|
||||
step(null);
|
||||
setDraft((d) => ({ ...d, companyId }));
|
||||
setRows((rs) => rs.map((r) => (r.block.type === "FORM" ? { ...r, block: { ...r.block, eventUuid: null } } : r)));
|
||||
setRows((rs) => rs.map((r) => {
|
||||
if (!r.block.eventUuid) return r;
|
||||
const { formHeading: _h, formText: _t, ...block } = r.block;
|
||||
return { ...r, block: { ...block, eventUuid: null } };
|
||||
}));
|
||||
};
|
||||
const setBlock = (key: number, update: (block: CmsBlock) => CmsBlock) =>
|
||||
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
|
||||
|
||||
@@ -118,6 +118,17 @@ describe("VisualEditor", () => {
|
||||
expect(section(1)).toHaveAttribute("data-selected", "true");
|
||||
});
|
||||
|
||||
// A toolbar hung above the section was clipped at the canvas top (first section, or a section scrolled to the top).
|
||||
it("keeps the section toolbar inside the section, clear of the hero's image button", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(0));
|
||||
const bar = canvas.getByRole("toolbar");
|
||||
expect(bar.className).not.toMatch(/(^|\s)-top-/);
|
||||
expect(bar.className).toMatch(/(^|\s)top-2(\s|$)/);
|
||||
expect(bar.className).toMatch(/(^|\s)right-2(\s|$)/);
|
||||
expect(within(section(0)).getByRole("button", { name: "Image" }).className).toMatch(/(^|\s)left-3(\s|$)/);
|
||||
});
|
||||
|
||||
it("undoes a delete with Ctrl+Z and redoes it with Ctrl+Shift+Z", async () => {
|
||||
const canvas = await open();
|
||||
fireEvent.click(section(2));
|
||||
|
||||
@@ -119,7 +119,7 @@ export function VisualEditor({ p, ask }: { p: Draft; ask: Ask }) {
|
||||
<>
|
||||
{selected === i ? (
|
||||
<div role="toolbar" aria-label={t(BLOCK_LABELS[rows[i].block.type])} onClick={(e) => e.stopPropagation()}
|
||||
className="absolute -top-5 right-2 z-30 flex items-center gap-0.5 rounded-md border bg-popover p-0.5 text-popover-foreground shadow-md">
|
||||
className="absolute top-2 right-2 z-30 flex items-center gap-0.5 rounded-md border bg-popover p-0.5 text-popover-foreground shadow-md">
|
||||
<span draggable aria-label={t("PagesDragSection")} title={t("PagesDragSection")}
|
||||
className="flex size-8 cursor-grab items-center justify-center rounded-md hover:bg-accent"
|
||||
onDragStart={(e) => { e.dataTransfer.setData("text/plain", String(i)); e.dataTransfer.effectAllowed = "move"; setDrag({ from: i, to: null }); }}
|
||||
|
||||
@@ -30,7 +30,7 @@ export const BLOCK_LABELS: Record<BlockType, string> = {
|
||||
CTA: "PagesBlockCta",
|
||||
};
|
||||
|
||||
/** A FEATURES (icon, title, text), STEPS (title, text) or TRUST (title) card. */
|
||||
/** A FEATURES (icon, title, text), STEPS (title, text) or TRUST (title) card; a HERO's points are title-only cards. */
|
||||
export interface CmsCard {
|
||||
icon?: string;
|
||||
title: string;
|
||||
@@ -58,6 +58,10 @@ export interface CmsBlock {
|
||||
cards?: CmsCard[];
|
||||
/** The FORM block's event (a Snowflake uuid, kept as a string). */
|
||||
eventUuid?: string | null;
|
||||
/** add-hero-full-width: a HERO across the whole window, and its form card's heading (80) and text (200). */
|
||||
fullWidth?: boolean;
|
||||
formHeading?: string;
|
||||
formText?: string;
|
||||
}
|
||||
|
||||
export type PageStatus = "DRAFT" | "PUBLISHED";
|
||||
|
||||
@@ -37,3 +37,23 @@ describe("frame script: same-page links", () => {
|
||||
expect(post.mock.calls.filter(([d]) => (d as { type: string }).type === "colite-frame-anchor")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("frame script: height report", () => {
|
||||
it("reports the content's height, not the frame's own, so a short block can shrink below its start height", () => {
|
||||
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
||||
const root = document.documentElement;
|
||||
vi.spyOn(root, "scrollHeight", "get").mockReturnValue(600);
|
||||
vi.spyOn(root, "getBoundingClientRect").mockReturnValue({ height: 69.4 } as DOMRect);
|
||||
runFrameScript("<header>Top bar</header>");
|
||||
expect(post).toHaveBeenCalledWith({ type: "colite-frame-height", height: 70 }, "*");
|
||||
});
|
||||
|
||||
it("reports again when the page asks", () => {
|
||||
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
||||
vi.spyOn(document.documentElement, "getBoundingClientRect").mockReturnValue({ height: 68 } as DOMRect);
|
||||
runFrameScript("<header>Top bar</header>");
|
||||
post.mockClear();
|
||||
window.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-ask" } }));
|
||||
expect(post).toHaveBeenCalledWith({ type: "colite-frame-height", height: 68 }, "*");
|
||||
});
|
||||
});
|
||||
@@ -33,11 +33,13 @@ describe("frameHtml", () => {
|
||||
expect(frameResponse("<p>x</p>", { preview: false }).headers.get("cache-control")).not.toBe("no-store");
|
||||
});
|
||||
|
||||
it("clamps a reported height between 100 and 20000 pixels and ignores junk", () => {
|
||||
// add-hero-full-width: the floor is 20 px, so a 68 px top bar keeps its own height.
|
||||
it("clamps a reported height between 20 and 20000 pixels and ignores junk", () => {
|
||||
const start = { height: START_HEIGHT, steps: [] };
|
||||
expect(START_HEIGHT).toBe(600);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 3000 }).height).toBe(3000);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 10 }).height).toBe(100);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 68 }).height).toBe(68);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 10 }).height).toBe(20);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 99999 }).height).toBe(20000);
|
||||
for (const junk of [null, "600", { type: "other", height: 900 }, { type: "colite-frame-height", height: "900" }, { type: "colite-frame-height", height: NaN }]) {
|
||||
expect(nextFrameHeight(start, junk)).toBe(start);
|
||||
|
||||
@@ -6,8 +6,10 @@ export const FRAME_SANDBOX = "allow-scripts allow-popups allow-popups-to-escape-
|
||||
/** The frame document's own policy. next.config sends it too: config headers replace a route's header of the same name. */
|
||||
export const FRAME_CSP = `sandbox ${FRAME_SANDBOX}; frame-ancestors 'self'`;
|
||||
export const FRAME_MESSAGE = "colite-frame-height";
|
||||
/** The page asks a frame to report its height again: its first report can come before the page listens (add-hero-full-width). */
|
||||
export const FRAME_ASK_MESSAGE = "colite-frame-ask";
|
||||
export const START_HEIGHT = 600;
|
||||
const MIN_HEIGHT = 100;
|
||||
const MIN_HEIGHT = 20;
|
||||
const MAX_HEIGHT = 20000;
|
||||
|
||||
export const FRAME_ANCHOR_MESSAGE = "colite-frame-anchor";
|
||||
@@ -15,11 +17,11 @@ export const FRAME_ANCHOR_MESSAGE = "colite-frame-anchor";
|
||||
const ANCHOR_SOURCE = "^(?!reg-)[a-z0-9][a-z0-9-]{0,39}$";
|
||||
const ANCHOR = new RegExp(ANCHOR_SOURCE);
|
||||
|
||||
// Posts the document height to the parent page on load and whenever it changes. A click on a #name link
|
||||
// Posts the content height (not scrollHeight, which never drops below the frame itself) to the parent page on load, whenever it changes, and when the page asks. A click on a #name link
|
||||
// (add-page-anchor-links) asks the page to scroll instead: the frame is as tall as its content and never scrolls.
|
||||
const FRAME_SCRIPT =
|
||||
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.scrollHeight)},"*")}` +
|
||||
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s();` +
|
||||
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.getBoundingClientRect().height)},"*")}` +
|
||||
`addEventListener("load",s);addEventListener("message",function(e){if(e.data&&e.data.type==="${FRAME_ASK_MESSAGE}")s()});if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s();` +
|
||||
`document.addEventListener("click",function(e){var a=e.target&&e.target.closest&&e.target.closest('a[href^="#"]');if(!a)return;` +
|
||||
`var n=a.getAttribute("href").slice(1);if(!/${ANCHOR_SOURCE}/.test(n))return;e.preventDefault();var t=document.getElementById(n);` +
|
||||
`parent.postMessage({type:"${FRAME_ANCHOR_MESSAGE}",name:n,y:t?Math.round(t.getBoundingClientRect().top+scrollY):null},"*")})})();</script>`;
|
||||
|
||||
@@ -868,6 +868,13 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
PagesFormEventHint: "Sign-ups become leads of this event. For general enquiries, pick your standing enquiries event.",
|
||||
PagesFormClosed: "Sign-up is closed.",
|
||||
PagesFormPreview: "The sign-up form shows here on the published page.",
|
||||
PagesHeroForm: "Sign-up form",
|
||||
PagesNoForm: "No form",
|
||||
PagesFullWidth: "Full width",
|
||||
PagesPointN: "Point {number}",
|
||||
PagesAddPoint: "Add point",
|
||||
PagesFormHeading: "Form heading",
|
||||
PagesFormText: "Form text",
|
||||
PagesToolbar: "Formatting",
|
||||
PagesTextStyle: "Text style",
|
||||
PagesParagraph: "Paragraph",
|
||||
|
||||
@@ -853,6 +853,13 @@
|
||||
"NoticeWhatsappBodyNoName": "来自新联系人",
|
||||
"PagesFormClosed": "报名已截止。",
|
||||
"PagesFormPreview": "发布后的网页会在此显示报名表。",
|
||||
"PagesHeroForm": "报名表单",
|
||||
"PagesNoForm": "不显示表单",
|
||||
"PagesFullWidth": "全宽",
|
||||
"PagesPointN": "要点 {number}",
|
||||
"PagesAddPoint": "添加要点",
|
||||
"PagesFormHeading": "表单标题",
|
||||
"PagesFormText": "表单说明",
|
||||
"PagesToolbar": "格式",
|
||||
"PagesTextStyle": "文字样式",
|
||||
"PagesParagraph": "段落",
|
||||
|
||||
+7
-2
@@ -48,7 +48,7 @@ public class PublicPageService {
|
||||
List<Map<String, Object>> blocks = new ArrayList<>();
|
||||
for (Object b : blocks(f.page())) {
|
||||
Map<String, Object> block = new LinkedHashMap<>((Map<String, Object>) b);
|
||||
if ("FORM".equals(block.get("type"))) {
|
||||
if (hasForm(block)) {
|
||||
PublicRegistrationService.Open o = open(f.companyId(), block);
|
||||
if (o == null) block.put("closed", true);
|
||||
else block.put("form", registration.eventView(o));
|
||||
@@ -64,11 +64,16 @@ public class PublicPageService {
|
||||
return Map.of("company", f.company(), "page", page);
|
||||
}
|
||||
|
||||
/** A FORM block, or a HERO with an event: its sign-up form sits beside the hero text (add-hero-signup-form). */
|
||||
private static boolean hasForm(Map<?, ?> block) {
|
||||
return "FORM".equals(block.get("type")) || ("HERO".equals(block.get("type")) && block.get("eventUuid") != null);
|
||||
}
|
||||
|
||||
public Map<String, Object> submit(String companyCode, String slug, int blockIndex, PublicPageFormRequest r) {
|
||||
registration.limit("page:load:" + PublicRegistrationService.ip(), LOAD_LIMIT, "Too many requests from this device. Try again later.");
|
||||
Found f = find(companyCode, slug);
|
||||
List<?> blocks = blocks(f.page());
|
||||
if (blockIndex < 0 || blockIndex >= blocks.size() || !"FORM".equals(((Map<?, ?>) blocks.get(blockIndex)).get("type"))) {
|
||||
if (blockIndex < 0 || blockIndex >= blocks.size() || !hasForm((Map<?, ?>) blocks.get(blockIndex))) {
|
||||
throw notFound();
|
||||
}
|
||||
PublicRegistrationService.Open o = open(f.companyId(), (Map<String, Object>) blocks.get(blockIndex));
|
||||
|
||||
+36
@@ -180,6 +180,42 @@ class PublicPageServiceTest {
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeroWithAnEventCarriesTheSignUpFormAndTakesSubmits() {
|
||||
// add-hero-signup-form: block 0 is a hero with the form beside its text, block 1 a hero without one.
|
||||
Map<String, Object> heroes = page();
|
||||
heroes.put("blocks", List.of(
|
||||
new HashMap<>(Map.of("type", "HERO", "heading", "One partner", "eventUuid", String.valueOf(EV))),
|
||||
Map.of("type", "HERO", "heading", "No form here")));
|
||||
when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("hotel-technology")))
|
||||
.thenReturn(ResponseEntity.ok(heroes));
|
||||
|
||||
List<Map<String, Object>> blocks = (List<Map<String, Object>>) ((Map<String, Object>) service.page("INS", "hotel-technology").get("page")).get("blocks");
|
||||
assertThat((Map<String, Object>) blocks.get(0).get("form")).containsEntry("eventName", "INS website enquiries");
|
||||
assertThat(blocks.get(1)).doesNotContainKeys("form", "closed");
|
||||
|
||||
service.submit("INS", "hotel-technology", 0, visitor(null));
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("eventUuid", EV).containsEntry("source", "WEB");
|
||||
|
||||
assertThatThrownBy(() -> service.submit("INS", "hotel-technology", 1, visitor(null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("PAGE_NOT_FOUND"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeroFormWhoseEventEndedIsClosed() {
|
||||
Map<String, Object> hero = page();
|
||||
hero.put("blocks", List.of(new HashMap<>(Map.of("type", "HERO", "heading", "One partner", "eventUuid", String.valueOf(EV)))));
|
||||
when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("hotel-technology")))
|
||||
.thenReturn(ResponseEntity.ok(hero));
|
||||
stubEvent(LocalDateTime.of(2027, 1, 15, 23, 59));
|
||||
List<Map<String, Object>> blocks = (List<Map<String, Object>>) ((Map<String, Object>) service.page("INS", "hotel-technology").get("page")).get("blocks");
|
||||
assertThat(blocks.get(0)).containsEntry("closed", true).containsEntry("heading", "One partner").doesNotContainKey("form");
|
||||
assertThatThrownBy(() -> service.submit("INS", "hotel-technology", 0, visitor(null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("FORM_CLOSED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHoneypotLooksLikeSuccessAndStoresNothing() {
|
||||
assertThat(service.submit("INS", "hotel-technology", 1, visitor("http://spam"))).containsKey("eventName");
|
||||
|
||||
+6
-1
@@ -10,7 +10,7 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* One landing-page block. Which fields apply depends on {@code type}:
|
||||
* HERO (imageId, heading, text, button), RICH_TEXT (html), IMAGE_TEXT (imageId, imagePosition, heading, html, button),
|
||||
* HERO (imageId, heading, text, button, optional eventUuid for a sign-up form beside the text, fullWidth, formHeading and formText, cards as title-only points), RICH_TEXT (html), IMAGE_TEXT (imageId, imagePosition, heading, html, button),
|
||||
* FAQ (heading, items), FORM (heading, eventUuid), HTML (html), FEATURES (heading, text, cards), STEPS (heading, cards),
|
||||
* TRUST (cards), CTA (heading, text, button). Any block may carry anchor and look.
|
||||
*/
|
||||
@@ -35,4 +35,9 @@ public class CmsBlock {
|
||||
/** A Snowflake value beyond JavaScript number precision: written as a string, read from either. */
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long eventUuid;
|
||||
/** add-hero-full-width: a HERO spanning the whole window. */
|
||||
private Boolean fullWidth;
|
||||
/** add-hero-full-width: heading (80) and text (200) at the top of a HERO's form card; only with an event. */
|
||||
private String formHeading;
|
||||
private String formText;
|
||||
}
|
||||
+23
-7
@@ -27,7 +27,7 @@ public final class CmsBlockValidator {
|
||||
/** Section looks and feature icons (add-page-sections). */
|
||||
private static final Set<String> LOOKS = Set.of("DEFAULT", "MUTED", "DARK", "ACCENT");
|
||||
static final Set<String> ICONS = Set.of("wifi", "phone", "tv", "monitor", "lock", "shield-check", "cloud", "wrench", "headset", "users", "calendar", "star");
|
||||
private static final Set<String> CARD_TYPES = Set.of("FEATURES", "STEPS", "TRUST");
|
||||
private static final Set<String> CARD_TYPES = Set.of("FEATURES", "STEPS", "TRUST", "HERO");
|
||||
private static final Pattern SCRIPT = Pattern.compile("(?i)<\\s*script|\\son[a-z]+\\s*=|javascript\\s*:");
|
||||
|
||||
private CmsBlockValidator() {
|
||||
@@ -71,6 +71,22 @@ public final class CmsBlockValidator {
|
||||
max(b.getHeading(), path + ".heading", 120);
|
||||
max(b.getText(), path + ".text", 300);
|
||||
button(b, path);
|
||||
// add-hero-signup-form: an optional sign-up form beside the hero text, for an event of the page's company.
|
||||
if (b.getEventUuid() != null && !ownEvent.test(b.getEventUuid())) {
|
||||
throw refuse(path + ".eventUuid", "PagesBadEvent");
|
||||
}
|
||||
// add-hero-full-width: up to 6 title-only points, and a form card heading and text only with a form.
|
||||
if (b.getCards() != null) {
|
||||
cards(b, path, 0, false, false);
|
||||
}
|
||||
max(b.getFormHeading(), path + ".formHeading", 80);
|
||||
max(b.getFormText(), path + ".formText", 200);
|
||||
if (b.getEventUuid() == null && b.getFormHeading() != null) {
|
||||
throw refuse(path + ".formHeading", "PagesUnusedField");
|
||||
}
|
||||
if (b.getEventUuid() == null && b.getFormText() != null) {
|
||||
throw refuse(path + ".formText", "PagesUnusedField");
|
||||
}
|
||||
}
|
||||
case "RICH_TEXT" -> html(b.getHtml(), path + ".html");
|
||||
case "HTML" -> {
|
||||
@@ -98,18 +114,18 @@ public final class CmsBlockValidator {
|
||||
required(b.getHeading(), path + ".heading");
|
||||
max(b.getHeading(), path + ".heading", 120);
|
||||
max(b.getText(), path + ".text", 300);
|
||||
cards(b, path, true, true);
|
||||
cards(b, path, 2, true, true);
|
||||
}
|
||||
case "STEPS" -> {
|
||||
required(b.getHeading(), path + ".heading");
|
||||
max(b.getHeading(), path + ".heading", 120);
|
||||
cards(b, path, false, true);
|
||||
cards(b, path, 2, false, true);
|
||||
}
|
||||
case "TRUST" -> {
|
||||
if (b.getHeading() != null) {
|
||||
throw refuse(path + ".heading", "PagesUnusedField");
|
||||
}
|
||||
cards(b, path, false, false);
|
||||
cards(b, path, 2, false, false);
|
||||
}
|
||||
case "CTA" -> {
|
||||
required(b.getHeading(), path + ".heading");
|
||||
@@ -169,10 +185,10 @@ public final class CmsBlockValidator {
|
||||
}
|
||||
}
|
||||
|
||||
/** 2 to 6 cards; an icon from the list where the type uses one, a title (80), a text (300) where used, nothing else. */
|
||||
private static void cards(CmsBlock b, String path, boolean icon, boolean text) {
|
||||
/** min to 6 cards; an icon from the list where the type uses one, a title (80), a text (300) where used, nothing else. */
|
||||
private static void cards(CmsBlock b, String path, int min, boolean icon, boolean text) {
|
||||
List<CmsCard> cards = b.getCards();
|
||||
if (cards == null || cards.size() < 2 || cards.size() > 6) {
|
||||
if (cards == null || cards.size() < min || cards.size() > 6) {
|
||||
throw refuse(path + ".cards", "PagesCardCount");
|
||||
}
|
||||
for (int i = 0; i < cards.size(); i++) {
|
||||
|
||||
+68
@@ -1,6 +1,7 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.services.counter.dto.CmsBlock;
|
||||
import com.solvway.services.counter.dto.CmsCard;
|
||||
import com.solvway.services.counter.dto.CmsFaqItem;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -154,6 +155,18 @@ class CmsBlockValidatorTest {
|
||||
refused(List.of(form(901)), "blocks[0].eventUuid", "PagesBadEvent");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeroMayCarryTheSignUpFormForAnEventOfThePagesCompany() {
|
||||
// add-hero-signup-form: the event is optional; when set it must be the company's own, as on a FORM block.
|
||||
validate(List.of(hero()));
|
||||
CmsBlock own = hero();
|
||||
own.setEventUuid(OWN_EVENT);
|
||||
validate(List.of(own));
|
||||
CmsBlock foreign = hero();
|
||||
foreign.setEventUuid(901L);
|
||||
refused(List.of(foreign), "blocks[0].eventUuid", "PagesBadEvent");
|
||||
}
|
||||
|
||||
private static CmsBlock custom(String html) {
|
||||
CmsBlock b = new CmsBlock();
|
||||
b.setType("HTML");
|
||||
@@ -204,4 +217,59 @@ class CmsBlockValidatorTest {
|
||||
again.setAnchor("signup");
|
||||
refused(List.of(named, again), "blocks[1].anchor", "PagesAnchorTaken");
|
||||
}
|
||||
|
||||
// add-hero-full-width: points are title-only cards, 0 to 6 of them.
|
||||
private static List<CmsCard> points(int n) {
|
||||
List<CmsCard> out = new ArrayList<>();
|
||||
for (int i = 0; i < n; i++) out.add(new CmsCard(null, "Local support team in Malaysia", null));
|
||||
return out;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeroMayCarryUpToSixTitleOnlyPoints() {
|
||||
CmsBlock one = hero();
|
||||
one.setCards(points(1));
|
||||
CmsBlock six = hero();
|
||||
six.setCards(points(6));
|
||||
assertThatCode(() -> validate(List.of(one, six))).doesNotThrowAnyException();
|
||||
CmsBlock seven = hero();
|
||||
seven.setCards(points(7));
|
||||
refused(List.of(seven), "blocks[0].cards", "PagesCardCount");
|
||||
CmsBlock blank = hero();
|
||||
blank.setCards(List.of(new CmsCard(null, " ", null)));
|
||||
refused(List.of(blank), "blocks[0].cards[0].title", "PagesRequired");
|
||||
CmsBlock longPoint = hero();
|
||||
longPoint.setCards(List.of(new CmsCard(null, "x".repeat(81), null)));
|
||||
refused(List.of(longPoint), "blocks[0].cards[0].title", "PagesTooLong");
|
||||
CmsBlock withIcon = hero();
|
||||
withIcon.setCards(List.of(new CmsCard("wifi", "WiFi", null)));
|
||||
refused(List.of(withIcon), "blocks[0].cards[0].icon", "PagesUnusedField");
|
||||
CmsBlock withText = hero();
|
||||
withText.setCards(List.of(new CmsCard(null, "WiFi", "More")));
|
||||
refused(List.of(withText), "blocks[0].cards[0].text", "PagesUnusedField");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeroWithAFormMayCarryAFormHeadingAndText() {
|
||||
CmsBlock ok = hero();
|
||||
ok.setEventUuid(OWN_EVENT);
|
||||
ok.setFullWidth(true);
|
||||
ok.setFormHeading("Get a free consultation");
|
||||
ok.setFormText("Tell us about your property. It takes under a minute.");
|
||||
assertThatCode(() -> validate(List.of(ok))).doesNotThrowAnyException();
|
||||
CmsBlock longHeading = hero();
|
||||
longHeading.setEventUuid(OWN_EVENT);
|
||||
longHeading.setFormHeading("x".repeat(81));
|
||||
refused(List.of(longHeading), "blocks[0].formHeading", "PagesTooLong");
|
||||
CmsBlock longText = hero();
|
||||
longText.setEventUuid(OWN_EVENT);
|
||||
longText.setFormText("x".repeat(201));
|
||||
refused(List.of(longText), "blocks[0].formText", "PagesTooLong");
|
||||
CmsBlock noForm = hero();
|
||||
noForm.setFormHeading("Get a free consultation");
|
||||
refused(List.of(noForm), "blocks[0].formHeading", "PagesUnusedField");
|
||||
CmsBlock noFormText = hero();
|
||||
noFormText.setFormText("Tell us more");
|
||||
refused(List.of(noFormText), "blocks[0].formText", "PagesUnusedField");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user