werkstaetten-app/mobile/scripts/prepare.mjs
Friederich Loheide 21a54da2e3 Erscheinungsbild je Einrichtung: Vorlagen, Schriften, Farben, mehrere Installationen
- Drei Design-Vorlagen (Kreis, Klar, Kacheln) mit Feinschliff: vier gut lesbare
  Schriften, eckig/rund/sehr rund, Hausfarben mit Live-Kontrastprüfung und
  „Farbe anpassen“; der Server lehnt zu helle Farben mit Vorschlag ab
- Fertige Farbpaare alle mit mindestens 4,5:1 zu Weiß
- Markenfarben greifen jetzt zuverlässig (Spezifität der eingebetteten Variablen);
  dunkle Darstellung wird aus der Hauptfarbe abgeleitet statt fest Indigo
- Checkliste „Erste Schritte“ im Dashboard für neue Einrichtungen
- Startwerte (APP_NAME, ORG_NAME, BRAND_COLOR, ACCENT_COLOR) beim ersten Start
- deploy/: neue-einrichtung.sh, aktualisieren.sh, sichern.sh für eine
  Installation je Kunde mit gemeinsamem Image
- mobile/: KUNDE=<kurzname> baut die App einer Einrichtung aus mobile/kunden/<kurzname>/
  inklusive deren Firebase-Dateien

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 17:54:11 +00:00

204 lines
9.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Bereitet die nativen Projekte vor – wird von `npm run sync` vor `cap sync` ausgeführt.
* Überträgt App-ID, Name, Adresse und Farbe aus mobile/.env in Android und iOS und
* richtet Push-Nachrichten und App-Links ein. Mehrfaches Ausführen ist unbedenklich.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadEnv } from '../env.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const env = loadEnv();
const host = new URL(env.appUrl).host;
const p = (...parts) => path.join(root, ...parts);
const read = (f) => fs.readFileSync(f, 'utf8');
const write = (f, s) => fs.writeFileSync(f, s);
const xmlEsc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const warnings = [];
// Firebase-Dateien der Einrichtung übernehmen. Fehlt eine, wird die einer anderen
// Einrichtung entfernt – sonst landeten Push-Anmeldungen im falschen Firebase-Projekt.
if (env.kunde) {
for (const [name, target] of [
['google-services.json', p('android', 'app', 'google-services.json')],
['GoogleService-Info.plist', p('ios', 'App', 'App', 'GoogleService-Info.plist')]
]) {
const src = path.join(env.dir, name);
if (fs.existsSync(src)) fs.copyFileSync(src, target);
else fs.rmSync(target, { force: true });
}
}
const assetsFor = fs.existsSync(p('assets', '.einrichtung')) ? read(p('assets', '.einrichtung')).trim() : '';
if (assetsFor && assetsFor !== env.appId)
warnings.push(`Symbole stammen noch von ${assetsFor} – zuerst \`${env.kunde ? `KUNDE=${env.kunde} ` : ''}npm run assets\` ausführen.`);
if (!env.appUrl.startsWith('https://')) warnings.push('APP_URL muss mit https:// beginnen (Apple und Google verlangen HTTPS).');
if (env.appUrl.includes('example.org')) warnings.push('APP_URL ist noch der Platzhalter – bitte in mobile/.env eintragen.');
if (env.appId.startsWith('org.example')) warnings.push('APP_ID ist noch der Platzhalter – vor dem ersten Hochladen in die Stores festlegen (später nicht mehr änderbar).');
if (!/^[a-zA-Z][\w]*(\.[a-zA-Z][\w]*)+$/.test(env.appId)) throw new Error(`APP_ID „${env.appId}“ ist ungültig (Beispiel: org.lindenhof.app).`);
if (!/^#[0-9a-f]{6}$/i.test(env.brandColor)) throw new Error(`BRAND_COLOR „${env.brandColor}“ ist ungültig (Beispiel: #2e2672).`);
/** Bereich zwischen zwei Markierungen ersetzen oder einfügen */
function block(text, name, content, insertBefore, indent = '') {
const start = `${indent}<!-- werkstatt:${name}:start -->`;
const end = `${indent}<!-- werkstatt:${name}:end -->`;
const full = `${start}\n${content}\n${end}`;
const re = new RegExp(`[ \\t]*<!-- werkstatt:${name}:start -->[\\s\\S]*?<!-- werkstatt:${name}:end -->`);
if (re.test(text)) return text.replace(re, full);
if (!text.includes(insertBefore)) throw new Error(`Einfügestelle „${insertBefore}“ nicht gefunden`);
return text.replace(insertBefore, `${full}\n${insertBefore}`);
}
// ─── Offline-Seite ───────────────────────────────────────────────────────────
write(
p('www', 'offline.html'),
`<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>${xmlEsc(env.appName)}</title>
<style>
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: ${env.brandColor}; color: #fff;
font: 500 18px/1.6 system-ui, -apple-system, 'Segoe UI', sans-serif; text-align: center; padding: 24px; box-sizing: border-box; }
h1 { font-size: 26px; margin: 0 0 8px; }
p { margin: 0 0 28px; opacity: .9; }
a { display: inline-block; background: #fff; color: ${env.brandColor}; font-weight: 700; text-decoration: none;
padding: 14px 28px; border-radius: 999px; }
</style>
</head>
<body>
<main>
<h1>Keine Verbindung</h1>
<p>${xmlEsc(env.appName)} braucht Internet.<br>Bitte prüfe WLAN oder mobile Daten.</p>
<a href="${env.appUrl}/">Noch einmal versuchen</a>
</main>
</body>
</html>
`
);
// ─── Android ─────────────────────────────────────────────────────────────────
if (fs.existsSync(p('android'))) {
const gradle = p('android', 'app', 'build.gradle');
write(gradle, read(gradle).replace(/applicationId "[^"]*"/, `applicationId "${env.appId}"`));
const strings = p('android', 'app', 'src', 'main', 'res', 'values', 'strings.xml');
let s = read(strings);
for (const [key, value] of [
['app_name', env.appName],
['title_activity_main', env.appName],
['package_name', env.appId],
['custom_url_scheme', env.appId]
])
s = s.replace(new RegExp(`(<string name="${key}">)[^<]*(</string>)`), `$1${xmlEsc(value)}$2`);
write(strings, s);
// Farbe für das Benachrichtigungssymbol und den Symbol-Hintergrund
write(
p('android', 'app', 'src', 'main', 'res', 'values', 'werkstatt_colors.xml'),
`<?xml version="1.0" encoding="utf-8"?>\n<resources>\n <color name="werkstatt_brand">${env.brandColor}</color>\n</resources>\n`
);
const manifestFile = p('android', 'app', 'src', 'main', 'AndroidManifest.xml');
let m = read(manifestFile);
// App-Links: Links zur Website öffnen direkt die App (Nachweis: /.well-known/assetlinks.json)
m = block(
m,
'applinks',
` <intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="${host}" />
</intent-filter>`,
' </activity>',
' '
);
// Symbol und Farbe für Push-Nachrichten (Symbol erzeugt `npm run assets`)
const hasIcon = fs.existsSync(p('android', 'app', 'src', 'main', 'res', 'drawable-xxhdpi', 'ic_stat_notify.png'));
m = block(
m,
'push',
`${
hasIcon
? ` <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_stat_notify" />\n`
: ''
} <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/werkstatt_brand" />`,
' </application>',
' '
);
write(manifestFile, m);
if (!hasIcon) warnings.push('Android: kein Benachrichtigungssymbol – `npm run assets` ausführen.');
if (!fs.existsSync(p('android', 'app', 'google-services.json')))
warnings.push('Android: android/app/google-services.json fehlt – ohne sie gibt es keine Push-Nachrichten (siehe README).');
}
// ─── iOS ─────────────────────────────────────────────────────────────────────
if (fs.existsSync(p('ios'))) {
const pbx = p('ios', 'App', 'App.xcodeproj', 'project.pbxproj');
let x = read(pbx).replace(/PRODUCT_BUNDLE_IDENTIFIER = [^;]+;/g, `PRODUCT_BUNDLE_IDENTIFIER = ${env.appId};`);
// Entitlements (Push + Associated Domains) dem App-Ziel zuordnen
if (!x.includes('CODE_SIGN_ENTITLEMENTS'))
x = x.replace(/(\n(\t+)INFOPLIST_FILE = App\/Info\.plist;)/g, '\n$2CODE_SIGN_ENTITLEMENTS = App/App.entitlements;$1');
write(pbx, x);
write(
p('ios', 'App', 'App', 'App.entitlements'),
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:${host}</string>
</array>
</dict>
</plist>
`
);
const plistFile = p('ios', 'App', 'App', 'Info.plist');
let pl = read(plistFile);
pl = pl.replace(/(<key>CFBundleDisplayName<\/key>\s*<string>)[^<]*(<\/string>)/, `$1${xmlEsc(env.appName)}$2`);
if (!pl.includes('<key>UIBackgroundModes</key>'))
pl = pl.replace(/<dict>/, '<dict>\n\t<key>UIBackgroundModes</key>\n\t<array>\n\t\t<string>remote-notification</string>\n\t</array>');
write(plistFile, pl);
// Push: Gerätekennung an das Firebase-Plugin weiterreichen (laut Plugin-Anleitung)
const delegate = p('ios', 'App', 'App', 'AppDelegate.swift');
let d = read(delegate);
if (!d.includes('capacitorDidRegisterForRemoteNotifications')) {
d = d.replace(
/\n}\s*$/,
`
// werkstatt:push – Push-Nachrichten (@capacitor-firebase/messaging)
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NotificationCenter.default.post(name: Notification.Name.init("didReceiveRemoteNotification"), object: completionHandler, userInfo: userInfo)
}
}
`
);
write(delegate, d);
}
if (!fs.existsSync(p('ios', 'App', 'App', 'GoogleService-Info.plist')))
warnings.push('iOS: ios/App/App/GoogleService-Info.plist fehlt – ohne sie gibt es keine Push-Nachrichten (siehe README).');
}
console.log(`✔ Vorbereitet${env.kunde ? ` für „${env.kunde}“` : ''}: ${env.appName} (${env.appId}) → ${env.appUrl}`);
for (const w of warnings) console.warn(`⚠ ${w}`);