mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 00:43:15 +00:00
Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e605d0bcab | |||
| 311321dc15 | |||
| f511fe4fcf | |||
| 00e98b8711 | |||
| fa23f94ee8 | |||
| 6c45d16cba | |||
| 857ce49962 | |||
| f7847bf22c | |||
| d5a3404c47 | |||
| 75cc0a4de2 | |||
| c0b28dd4da | |||
| 4d3f7fd355 | |||
| 8335ac45f9 | |||
| 114086f6e2 | |||
| 714fc6beaf | |||
| 8fc7745d59 | |||
| f6437d12cb | |||
| d0cf936bf6 | |||
| 7de6bc39cd | |||
| aa54643713 | |||
| 126dbc4281 | |||
| c05a8a299c |
@@ -1,6 +1,6 @@
|
||||
TREK is a travel planner for the trips you take with other people. Plan the days together, see every place on the map, keep bookings, costs and packing lists in one place, and still have all of it with you when the connection drops.
|
||||
|
||||
TREK is open source and works with a TREK server: one you run yourself, at home or on a rented server, one your organisation provides, or the public demo to try it out. Your trips stay on that server. The makers of TREK receive none of your data.
|
||||
TREK is open source and connects to a TREK server. Use a server you run, connect to one your organisation provides, or try the public demo. Where available, you can subscribe to a managed instance through TREK Cloud. Google Play shows the price and billing period for your storefront before purchase.
|
||||
|
||||
PLAN TOGETHER
|
||||
• Days with places, notes, transports and stays, in order and on the map
|
||||
@@ -17,8 +17,8 @@ ON THE ROAD
|
||||
• A travel journal with photos, and an atlas of the countries you have visited
|
||||
|
||||
YOUR DATA
|
||||
• No account with us, no tracking, no ads
|
||||
• Your trips are stored on the TREK server you choose
|
||||
• Sign in with a password, a passkey or your organisation's single sign-on
|
||||
• Available in 27 languages
|
||||
|
||||
To use the app you need the address of a TREK server. Without one yet, tap "Try the demo" on the first screen, or read how to run your own at github.com/liketrek/TREK.
|
||||
On the first screen you can enter your server address, choose TREK Cloud, or tap "Try the demo". To run your own server, see github.com/liketrek/TREK.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
TREK is a travel planner for the trips you take with other people. Plan the days together, see every place on the map, keep bookings, costs and packing lists in one place, and still have all of it with you when the connection drops.
|
||||
|
||||
TREK is open source and works with a TREK server: one you run yourself, at home or on a rented server, one your organisation provides, or the public demo to try it out. Your trips stay on that server. The makers of TREK receive none of your data.
|
||||
TREK is open source and connects to a TREK server. Use a server you run, connect to one your organisation provides, or try the public demo. Where available, you can subscribe to a managed instance through TREK Cloud. The App Store shows the price and billing period for your storefront before purchase.
|
||||
|
||||
PLAN TOGETHER
|
||||
• Days with places, notes, transports and stays, in order and on the map
|
||||
@@ -17,8 +17,8 @@ ON THE ROAD
|
||||
• A travel journal with photos, and an atlas of the countries you have visited
|
||||
|
||||
YOUR DATA
|
||||
• No account with us, no tracking, no ads
|
||||
• Your trips are stored on the TREK server you choose
|
||||
• Sign in with a password, a passkey or your organisation's single sign-on
|
||||
• Available in 27 languages
|
||||
|
||||
To use the app you need the address of a TREK server. Without one yet, tap "Try the demo" on the first screen, or read how to run your own at github.com/liketrek/TREK.
|
||||
On the first screen you can enter your server address, choose TREK Cloud, or tap "Try the demo". To run your own server, see github.com/liketrek/TREK.
|
||||
|
||||
+95
-37
@@ -7,7 +7,7 @@ import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../
|
||||
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
|
||||
import { pageUnderStatusBar } from '../src/native/appBoot';
|
||||
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
|
||||
import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from '../src/native/cloudOrders';
|
||||
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
|
||||
import {
|
||||
APP_STORE_SUBSCRIPTIONS_URL,
|
||||
@@ -152,6 +152,7 @@ const I = {
|
||||
image:
|
||||
'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM21 15l-5-5L5 21',
|
||||
spark: 'M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z',
|
||||
mail: 'M4 5h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM3 7l9 6 9-6',
|
||||
people:
|
||||
'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75',
|
||||
shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10',
|
||||
@@ -661,13 +662,14 @@ interface CloudPlan {
|
||||
/** Absent while orders are closed: the cloud names its plans but no price leaves it then. */
|
||||
monthlyCents?: number;
|
||||
yearlyCents?: number;
|
||||
currency?: 'EUR' | 'USD';
|
||||
aiDocuments: number;
|
||||
aiDocumentLimit?: 0 | null;
|
||||
aiAssistant?: 'planned' | 'included' | 'unavailable';
|
||||
bookingMailImport?: boolean;
|
||||
storageGb: number;
|
||||
}
|
||||
|
||||
function money(cents: number): string {
|
||||
return new Intl.NumberFormat(locale, { style: 'currency', currency: 'EUR' }).format(cents / 100);
|
||||
}
|
||||
function count(n: number): string {
|
||||
return new Intl.NumberFormat(locale).format(n);
|
||||
}
|
||||
@@ -676,10 +678,28 @@ function count(n: number): string {
|
||||
// during development, so its /api/plans is unreachable from a local build. Never
|
||||
// used in a real build (see the import.meta.env.DEV guard below).
|
||||
const SAMPLE_PLANS: CloudPlan[] = [
|
||||
{ id: 'start', name: 'Start', monthlyCents: 490, yearlyCents: 4900, aiDocuments: 0, storageGb: 10 },
|
||||
{ id: 'basis', name: 'Basis', monthlyCents: 790, yearlyCents: 7900, aiDocuments: 25, storageGb: 10 },
|
||||
{ id: 'plus', name: 'Plus', monthlyCents: 1290, yearlyCents: 12900, aiDocuments: 100, storageGb: 25 },
|
||||
{ id: 'pro', name: 'Pro', monthlyCents: 1990, yearlyCents: 19900, aiDocuments: 150, storageGb: 50 },
|
||||
{
|
||||
id: 'start',
|
||||
name: 'Start',
|
||||
monthlyCents: 499,
|
||||
yearlyCents: 4899,
|
||||
currency: 'USD',
|
||||
aiDocuments: 0,
|
||||
aiDocumentLimit: 0,
|
||||
storageGb: 200,
|
||||
},
|
||||
{
|
||||
id: 'plus',
|
||||
name: 'Plus',
|
||||
monthlyCents: 999,
|
||||
yearlyCents: 9900,
|
||||
currency: 'USD',
|
||||
aiDocuments: 100,
|
||||
aiDocumentLimit: null,
|
||||
aiAssistant: 'planned',
|
||||
bookingMailImport: true,
|
||||
storageGb: 200,
|
||||
},
|
||||
];
|
||||
|
||||
interface CloudPlans {
|
||||
@@ -693,8 +713,8 @@ async function fetchPlans(): Promise<CloudPlans | null> {
|
||||
const res = await get(`${CLOUD_URL}/api/plans`);
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
|
||||
const body = (data ?? {}) as { plans?: CloudPlan[]; ordering?: string };
|
||||
if (Array.isArray(body.plans) && body.plans.length)
|
||||
return { plans: body.plans, closed: body.ordering === 'closed' };
|
||||
const plans = Array.isArray(body.plans) ? body.plans.filter((plan) => isNewCloudPlan(plan.id)) : [];
|
||||
if (plans.length) return { plans, closed: body.ordering === 'closed' };
|
||||
} catch {
|
||||
// Fall through to the preview fallback.
|
||||
}
|
||||
@@ -716,11 +736,16 @@ interface Offer {
|
||||
}
|
||||
|
||||
function offerFor(offer: Offer, plan: CloudPlan, interval: 'month' | 'year'): { label: string; buyable: boolean } {
|
||||
if (!offer.canBuy) return { label: '', buyable: false };
|
||||
if (iap !== fakeIapClient) {
|
||||
const label = offer.storePrices?.get(productIdFor(plan.id, interval)) ?? '';
|
||||
return { label, buyable: label !== '' };
|
||||
}
|
||||
const cents = interval === 'year' ? plan.yearlyCents : plan.monthlyCents;
|
||||
const ours = typeof cents === 'number' ? money(cents) : '';
|
||||
const storePrice = offer.storePrices?.get(productIdFor(plan.id, interval));
|
||||
if (offer.storePrices) return { label: storePrice ?? ours, buyable: offer.canBuy && !!storePrice };
|
||||
return { label: ours, buyable: offer.canBuy && ours !== '' };
|
||||
const currency = plan.currency ?? 'EUR';
|
||||
const label =
|
||||
typeof cents === 'number' ? new Intl.NumberFormat(locale, { style: 'currency', currency }).format(cents / 100) : '';
|
||||
return { label, buyable: label !== '' };
|
||||
}
|
||||
|
||||
async function loadOffer(list: CloudPlans): Promise<Offer> {
|
||||
@@ -771,7 +796,7 @@ let chosenInterval: 'month' | 'year' = 'month';
|
||||
* phone). Found and redeemed: the instance it belongs to opens. Paid but never
|
||||
* set up: the claim screen takes the purchase as it is, so nothing is bought twice.
|
||||
*/
|
||||
function restoreButton(offer: Offer, plans: CloudPlan[]): HTMLButtonElement {
|
||||
function restoreButton(plans: CloudPlan[]): HTMLButtonElement {
|
||||
const restore = el('button', { type: 'button', className: 'link' }, t('native.plans.restore'));
|
||||
const say = (text: string) => {
|
||||
restore.classList.add('msg');
|
||||
@@ -795,13 +820,10 @@ function restoreButton(offer: Offer, plans: CloudPlan[]): HTMLButtonElement {
|
||||
return;
|
||||
}
|
||||
// Paid but never set up (Ask to Buy approved later, the app closed mid-purchase).
|
||||
const unclaimed = redeemed.code === 'email-invalid' || (redeemed.code ?? '').startsWith('slug-');
|
||||
const match = /^cloud\.([a-z0-9-]+)\.(monthly|yearly)$/.exec(purchase.productId);
|
||||
const plan = match ? plans.find((p) => p.id === match[1]) : undefined;
|
||||
if (unclaimed && match && plan) {
|
||||
const interval = match[2] === 'yearly' ? 'year' : 'month';
|
||||
const { label } = offerFor(offer, plan, interval);
|
||||
showClaim(plan, interval, label, { bought: purchase });
|
||||
const unclaimed = planForUnclaimedPurchase(purchase.productId, redeemed.code);
|
||||
if (unclaimed) {
|
||||
const plan = plans.find((candidate) => candidate.id === unclaimed.plan.id) ?? unclaimed.plan;
|
||||
showClaim(plan, unclaimed.interval, '', { bought: purchase });
|
||||
return;
|
||||
}
|
||||
void notify(NotificationType.Error);
|
||||
@@ -901,6 +923,10 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
const plan = selected();
|
||||
if (!plan) return;
|
||||
const index = plans.indexOf(plan);
|
||||
const month = offerFor(offer, plan, 'month');
|
||||
const year = offerFor(offer, plan, 'year');
|
||||
if (interval === 'month' && !month.buyable && year.buyable) interval = 'year';
|
||||
if (interval === 'year' && !year.buyable && month.buyable) interval = 'month';
|
||||
tiers
|
||||
.querySelectorAll<HTMLButtonElement>('button')
|
||||
.forEach((b) => b.setAttribute('aria-checked', String(b.dataset.plan === plan.id)));
|
||||
@@ -917,25 +943,30 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
text.textContent = tripText;
|
||||
text.hidden = !tripText;
|
||||
|
||||
const { label, buyable } = offerFor(offer, plan, interval);
|
||||
const { label, buyable } = interval === 'month' ? month : year;
|
||||
// No price yet (orders not open): the plan shows without one rather than with an empty one.
|
||||
price.hidden = !label;
|
||||
pricePer.textContent = per(interval);
|
||||
if (label) paintPrice(label, animate);
|
||||
const year = offerFor(offer, plan, 'year').label;
|
||||
|
||||
// Without a price in either period (orders not open yet) the switch would choose between nothing.
|
||||
pricebox.hidden = !label && !year;
|
||||
const yearAmount = amountIn(year);
|
||||
pricebox.hidden = !month.label && !year.label;
|
||||
monthBtn.disabled = !month.label;
|
||||
yearBtn.disabled = !year.label;
|
||||
const yearAmount = amountIn(year.label);
|
||||
equals.textContent =
|
||||
!label || !year
|
||||
!label || !year.label
|
||||
? ''
|
||||
: interval === 'month'
|
||||
? t('native.plans.yearlyIs', { price: year })
|
||||
? t('native.plans.yearlyIs', { price: year.label })
|
||||
: yearAmount
|
||||
? t('native.plans.monthlyIs', { price: yearAmount.render(yearAmount.value / 12) })
|
||||
: '';
|
||||
|
||||
const gb = plan.storageGb >= 1000 ? `${count(plan.storageGb / 1000)} TB` : `${count(plan.storageGb)} GB`;
|
||||
const notIncluded = t('native.plans.aiNone');
|
||||
const included = t('native.plans.included');
|
||||
const assistant = plan.aiAssistant === 'included';
|
||||
const tile = (glyph: string, big: string, small: string, off = false) =>
|
||||
el(
|
||||
'span',
|
||||
@@ -944,11 +975,28 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
el('span', {}, el('b', {}, big), el('small', {}, small))
|
||||
);
|
||||
specs.replaceChildren(
|
||||
// About 3 MB a photo, as a phone takes them: a size people can picture.
|
||||
tile(I.image, gb, t('native.plans.photos', { n: count(plan.storageGb * 300) })),
|
||||
tile(I.image, gb, t('native.plans.storageFairUse')),
|
||||
plan.aiDocuments > 0
|
||||
? tile(I.spark, t('native.plans.aiPerMonth', { n: count(plan.aiDocuments) }), t('native.plans.aiLabel'))
|
||||
: tile(I.spark, t('native.plans.aiNone'), t('native.plans.aiLabel'), true),
|
||||
? tile(
|
||||
I.spark,
|
||||
plan.aiDocumentLimit === null
|
||||
? t('native.plans.unlimited')
|
||||
: t('native.plans.aiPerMonth', { n: count(plan.aiDocuments) }),
|
||||
t('native.plans.aiLabel')
|
||||
)
|
||||
: tile(I.spark, notIncluded, t('native.plans.aiLabel'), true),
|
||||
tile(
|
||||
I.spark,
|
||||
assistant ? included : plan.aiAssistant === 'planned' ? t('native.plans.planned') : notIncluded,
|
||||
t('native.plans.assistant'),
|
||||
!assistant
|
||||
),
|
||||
tile(
|
||||
I.mail,
|
||||
plan.bookingMailImport ? included : notIncluded,
|
||||
t('native.plans.mailImport'),
|
||||
!plan.bookingMailImport
|
||||
),
|
||||
el(
|
||||
'span',
|
||||
{ className: 'spec wide' },
|
||||
@@ -982,6 +1030,9 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
choose.addEventListener('click', async () => {
|
||||
const plan = selected();
|
||||
if (!plan) return;
|
||||
const selectedInterval = interval;
|
||||
const price = offerFor(offer, plan, selectedInterval);
|
||||
if (!price.buyable) return;
|
||||
void tap(ImpactStyle.Medium);
|
||||
// A store account with a running subscription buys nothing more: say so before the form.
|
||||
choose.disabled = true;
|
||||
@@ -991,7 +1042,7 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
showSubscribed();
|
||||
return;
|
||||
}
|
||||
showClaim(plan, interval, offerFor(offer, plan, interval).label);
|
||||
showClaim(plan, selectedInterval, price.label);
|
||||
});
|
||||
|
||||
const load = async () => {
|
||||
@@ -1041,8 +1092,8 @@ function showPlans(opts: { back?: boolean } = {}): void {
|
||||
externalLink(t('native.plans.privacyShort'), PRIVACY_URL)
|
||||
)
|
||||
);
|
||||
dock.append(restoreButton(offer, plans));
|
||||
}
|
||||
if (offer.canBuy || offer.opensSoon) dock.append(restoreButton(plans));
|
||||
foot.hidden = false;
|
||||
paint(true);
|
||||
};
|
||||
@@ -1077,6 +1128,7 @@ async function fetchConsent(): Promise<DeviationsConsent | null> {
|
||||
try {
|
||||
const res = await CapacitorHttp.get({
|
||||
url: `${CLOUD_URL}/api/iap/consent`,
|
||||
params: { lang: locale === 'de' ? 'de' : 'en' },
|
||||
connectTimeout: PROBE_TIMEOUT_MS,
|
||||
readTimeout: PROBE_TIMEOUT_MS,
|
||||
});
|
||||
@@ -1140,7 +1192,7 @@ async function redeemPurchase(
|
||||
}
|
||||
|
||||
function showClaim(
|
||||
plan: CloudPlan,
|
||||
plan: Pick<CloudPlan, 'id' | 'name'>,
|
||||
interval: 'month' | 'year',
|
||||
priceLabel: string,
|
||||
opts: { back?: boolean; bought?: Purchase } = {}
|
||||
@@ -1247,7 +1299,8 @@ function showClaim(
|
||||
};
|
||||
void loadConsent();
|
||||
|
||||
const subscribeLabel = () => t('native.claim.subscribe', { price: priceLabel });
|
||||
const subscribeLabel = () =>
|
||||
bought ? t('native.claim.completeSetup') : t('native.claim.subscribe', { price: priceLabel });
|
||||
const submit = el('button', { type: 'button', className: 'cta' }, subscribeLabel());
|
||||
// What is about to be bought, so nobody pays for a plan they did not mean.
|
||||
const change = el('button', { type: 'button' }, t('native.claim.change'));
|
||||
@@ -1258,7 +1311,12 @@ function showClaim(
|
||||
const planRow = el(
|
||||
'div',
|
||||
{ className: 'plan-row' },
|
||||
el('span', {}, el('b', {}, plan.name), el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`)),
|
||||
el(
|
||||
'span',
|
||||
{},
|
||||
el('b', {}, plan.name),
|
||||
...(priceLabel ? [el('small', { dir: 'ltr' }, `${priceLabel} ${per(interval)}`)] : [])
|
||||
),
|
||||
// A purchase already made is not a choice any more.
|
||||
...(bought ? [] : [change])
|
||||
);
|
||||
|
||||
+11
-11
@@ -55,13 +55,13 @@
|
||||
"dependencies": {
|
||||
"@assistant-ui/react": "0.15.38",
|
||||
"@capacitor/action-sheet": "^8.1.1",
|
||||
"@capacitor/android": "^8.6.3",
|
||||
"@capacitor/android": "^8.6.2",
|
||||
"@capacitor/app": "^8.1.1",
|
||||
"@capacitor/core": "^8.6.3",
|
||||
"@capacitor/core": "^8.6.2",
|
||||
"@capacitor/dialog": "^8.0.1",
|
||||
"@capacitor/filesystem": "^8.1.6",
|
||||
"@capacitor/filesystem": "^8.1.3",
|
||||
"@capacitor/haptics": "^8.0.2",
|
||||
"@capacitor/ios": "^8.6.3",
|
||||
"@capacitor/ios": "^8.6.2",
|
||||
"@capacitor/keyboard": "^8.0.5",
|
||||
"@capacitor/share": "^8.0.1",
|
||||
"@capacitor/splash-screen": "^8.0.2",
|
||||
@@ -114,7 +114,7 @@
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.577.0",
|
||||
"mapbox-gl": "3.32.0",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"maplibre-gl": "6.19.0",
|
||||
"modern-screenshot": "4.7.0",
|
||||
"plyr": "^3.8.5",
|
||||
"react": "^19.3.1",
|
||||
@@ -133,12 +133,12 @@
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@capacitor/cli": "^8.6.3",
|
||||
"@capacitor/cli": "^8.6.2",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@jscpd/core": "^4.2.5",
|
||||
"@jscpd/tokenizer": "^4.2.6",
|
||||
"@playwright/test": "^1.65.1",
|
||||
"@testing-library/dom": "^10.4.2",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^8.0.0",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
@@ -146,7 +146,7 @@
|
||||
"@types/geojson": "^7946.0.16",
|
||||
"@types/leaflet": "^1.9.23",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.3",
|
||||
"@types/react": "^19.3.2",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/topojson-client": "^3.1.5",
|
||||
"@types/topojson-specification": "^1.0.5",
|
||||
@@ -155,13 +155,13 @@
|
||||
"autoprefixer": "^10.7.0",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
"eslint-config-prettier": "^10.1.9",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.8",
|
||||
"fake-indexeddb": "^6.2.7",
|
||||
"jsdom": "^29.1.1",
|
||||
"msw": "^3.0.8",
|
||||
"postcss": "^8.5.34",
|
||||
"postcss": "^8.5.33",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
@@ -170,7 +170,7 @@
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.74.0",
|
||||
"vite": "8.4.0",
|
||||
"vite": "8.3.8",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^5.1.2"
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 484,
|
||||
"@typescript-eslint/no-non-null-assertion": 1849,
|
||||
"@typescript-eslint/no-non-null-assertion": 1848,
|
||||
"@typescript-eslint/no-misused-promises": 22,
|
||||
"@typescript-eslint/no-unused-vars": 48,
|
||||
"@typescript-eslint/no-floating-promises": 33,
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
"src/components/Studio/countryShapes.ts": 2595,
|
||||
"src/index.css": 1636,
|
||||
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 3886,
|
||||
"src/pages/JourneyDetailPage.test.tsx": 3880,
|
||||
"src/pages/LoginPage.tsx": 1273,
|
||||
"src/pages/TripPlannerPage.tsx": 1127,
|
||||
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
"components/Journey/JourneyDetailPageGalleryView.tsx": 15,
|
||||
"components/Journey/JourneyDetailPageMapView.tsx": 50,
|
||||
"components/Journey/JourneyDetailPagePhotoGrid.tsx": 6,
|
||||
"components/Journey/JourneyDetailPageProviderPicker.tsx": 163,
|
||||
"components/Journey/JourneyDetailPageProviderPicker.tsx": 161,
|
||||
"components/Journey/JourneyDetailPageScrollTrigger.tsx": 4,
|
||||
"components/Journey/JourneyDetailPageVerdictSection.tsx": 51,
|
||||
"components/Journey/JourneyEntryCover.tsx": 13,
|
||||
@@ -182,7 +182,7 @@
|
||||
"mobile/screens/journey/MJourney.tsx": 10,
|
||||
"mobile/screens/journey/MJourneyCreateSheet.tsx": 7,
|
||||
"mobile/screens/journey/MJourneyDetail.tsx": 6,
|
||||
"mobile/screens/journey/MJourneyEntrySheet.tsx": 48,
|
||||
"mobile/screens/journey/MJourneyEntrySheet.tsx": 46,
|
||||
"mobile/screens/journey/MJourneySettingsSheet.tsx": 2,
|
||||
"mobile/screens/journey/mobileJourneyMeta.ts": 4,
|
||||
"mobile/screens/notifications/MNotificationRow.tsx": 4,
|
||||
@@ -282,7 +282,7 @@
|
||||
"pages/ForgotPasswordPage.tsx": 18,
|
||||
"pages/HelpPage.tsx": 21,
|
||||
"pages/JoinTripPage.tsx": 4,
|
||||
"pages/JourneyDetailPage.tsx": 53,
|
||||
"pages/JourneyDetailPage.tsx": 52,
|
||||
"pages/JourneyPage.tsx": 64,
|
||||
"pages/JourneyPublicPage.tsx": 113,
|
||||
"pages/LoginPage.tsx": 54,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
|
||||
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { aiRoutesOpen, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
|
||||
/**
|
||||
* Asks for the assistant's status when a view of it mounts, and again when
|
||||
@@ -13,7 +14,8 @@ import { aiRoutesOpen, useAssistantStore } from '../../store/assistantStore';
|
||||
*/
|
||||
export function useAssistantStatus(): void {
|
||||
const loadStatus = useAssistantStore((s) => s.loadStatus);
|
||||
const routesOpen = useAddonStore(aiRoutesOpen);
|
||||
const managed = useAuthStore((s) => s.managed);
|
||||
const routesOpen = useAddonStore((s) => aiRoutesOpen(s, managed));
|
||||
const assistantOn = useAddonStore((s) => s.isEnabled('ai_assistant'));
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -37,7 +37,6 @@ export default function DawarichDayDialog({
|
||||
onClose={onClose}
|
||||
labelledBy={labelId}
|
||||
width="detail"
|
||||
align="top"
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={
|
||||
|
||||
@@ -154,7 +154,7 @@ export default function JourneyDayRecordingButton({
|
||||
className={ROUND}
|
||||
style={{ background: 'var(--vg-surf2)' }}
|
||||
>
|
||||
<DawarichIcon size={15} />
|
||||
<DawarichIcon className="size-3.5 rounded-full" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ContextMenu menu={menu.menu} onClose={menu.close} />
|
||||
|
||||
@@ -469,7 +469,7 @@ describe('EntryEditor', () => {
|
||||
await user.click(screen.getByRole('button', { name: /Upload photos/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'External photos' }))
|
||||
|
||||
expect(await screen.findByTestId('journey-external-provider-immich')).toBeInTheDocument()
|
||||
expect(await screen.findByRole('dialog', { name: 'Immich' })).toBeVisible()
|
||||
})
|
||||
|
||||
it('FE-JRN-EDITOR-020: queues photos picked from a connected provider and clears them again', async () => {
|
||||
@@ -478,8 +478,11 @@ describe('EntryEditor', () => {
|
||||
mountEditor(buildEntry({ id: 10, location_lat: 41.9, location_lng: 12.5, location_name: 'Rome' }))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'External photos' }))
|
||||
expect(await screen.findByTestId('journey-external-provider-immich')).toBeInTheDocument()
|
||||
expect(screen.getByText('Nearby photos first: Rome')).toBeInTheDocument()
|
||||
const picker = await screen.findByRole('dialog', { name: 'Immich' })
|
||||
expect(picker).toHaveClass('h-full')
|
||||
expect(screen.getByRole('button', { name: 'Cancel' })).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
|
||||
expect(picker).toHaveTextContent('Nearby photos first Rome')
|
||||
expect(screen.getByText('Photos for Mar 15, 2026')).toBeInTheDocument()
|
||||
|
||||
await user.click(await screen.findByAltText(''))
|
||||
@@ -720,13 +723,15 @@ describe('EntryEditor', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Add (1)' }))
|
||||
await screen.findByRole('button', { name: /1 queued Clear/ })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'External photos' }))
|
||||
await user.click(screen.getByTestId('journey-external-provider-photoprism'))
|
||||
expect(screen.getByTestId('journey-external-provider-photoprism').className).toContain('bg-accent')
|
||||
expect(screen.getByTestId('journey-external-provider-photoprism')).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
// The picker's own cancel drops back to the first available provider.
|
||||
await user.click(screen.getAllByRole('button', { name: 'Cancel' })[0])
|
||||
expect(screen.getByTestId('journey-external-provider-photoprism').className).not.toContain('bg-accent')
|
||||
await user.keyboard('{Escape}')
|
||||
expect(screen.queryByRole('dialog', { name: 'PhotoPrism' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /1 queued Clear/ })).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'External photos' }))
|
||||
expect(screen.getByTestId('journey-external-provider-immich')).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
it('FE-JRN-EDITOR-033: merges a second pick into the already queued group', async () => {
|
||||
@@ -755,12 +760,14 @@ describe('EntryEditor', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Add (1)' }))
|
||||
await screen.findByRole('button', { name: /1 queued Clear/ })
|
||||
|
||||
// The first asset stays selected but is now greyed out, so the second Add
|
||||
// re-sends it and the merge has to skip the duplicate.
|
||||
const remaining = screen.getAllByAltText('').find(img => !img.parentElement!.className.includes('opacity-40'))!
|
||||
// The first asset is already queued, so it remains unavailable on reopening.
|
||||
await user.click(screen.getByRole('button', { name: 'External photos' }))
|
||||
const reopened = await screen.findAllByAltText('')
|
||||
expect(reopened.find(img => assetIdOf(img) === firstId)?.parentElement).toBeDisabled()
|
||||
const remaining = reopened.find(img => assetIdOf(img) !== firstId)!
|
||||
const secondId = assetIdOf(remaining)
|
||||
await user.click(remaining)
|
||||
await user.click(screen.getByRole('button', { name: 'Add (2)' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Add (1)' }))
|
||||
expect(await screen.findByRole('button', { name: /2 queued Clear/ })).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
@@ -782,7 +789,7 @@ describe('EntryEditor', () => {
|
||||
}))
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'External photos' }))
|
||||
await screen.findByTestId('journey-external-provider-immich')
|
||||
await screen.findByRole('dialog', { name: 'Immich' })
|
||||
|
||||
await waitFor(() => expect(document.querySelector('.opacity-40')).toBeInTheDocument())
|
||||
expect(screen.queryByRole('button', { name: /Select all/ })).not.toBeInTheDocument()
|
||||
@@ -796,7 +803,7 @@ describe('EntryEditor', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'External photos' }))
|
||||
|
||||
expect(await screen.findByText('All photos from this day')).toBeInTheDocument()
|
||||
expect(await screen.findByTestId('journey-external-provider-immich')).toBeInTheDocument()
|
||||
expect(await screen.findByRole('dialog', { name: 'Immich' })).toBeVisible()
|
||||
})
|
||||
|
||||
it('FE-JRN-EDITOR-040: ignores a link call that comes back without a photo', async () => {
|
||||
|
||||
@@ -26,7 +26,7 @@ const CHIP_OFF = 'border-edge-faint bg-surface-card text-content-muted hover:tex
|
||||
const SOURCE = 'flex items-center justify-center gap-1.5 rounded-[12px] border py-4 font-medium disabled:cursor-default disabled:opacity-50'
|
||||
const SOURCE_OFF = 'border-dashed border-edge text-content-muted hover:border-content-faint hover:bg-surface-secondary hover:text-content'
|
||||
const SOURCE_ON = 'border-content bg-surface-secondary text-content'
|
||||
/** The panel a photo source opens under the buttons: the gallery grid, the provider browser. */
|
||||
/** The gallery grid under the source buttons. */
|
||||
const PHOTO_PANEL = 'mt-2 rounded-[12px] border border-edge-faint bg-surface-secondary'
|
||||
/** A control laid over a photo tile, raised on the card colour so it reads on any picture. */
|
||||
const ON_PHOTO = 'bg-surface-card text-content shadow-sm'
|
||||
@@ -148,7 +148,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
|
||||
mood, setMood, weather, setWeather, statsExcluded, setStatsExcluded, tripSuggestion, isDraft, setIsDraft,
|
||||
pros, setPros, cons, setCons, tags, setTags, tagInput, setTagInput, addTag, saving, uploadProgress, photos, photoOrder, canReorder,
|
||||
pendingFiles, setPendingFiles, pendingPreviews: pendingUrls,
|
||||
pendingProviderGroups, setPendingProviderGroups, showGalleryPick, setShowGalleryPick, isDirty,
|
||||
queuedProviderPhotos, setPendingProviderGroups, queueProviderPhotos, showGalleryPick, setShowGalleryPick, isDirty,
|
||||
availableGalleryPhotos, providerAssetIds, contextLocation, offersStatsToggle, addVerdictRow, verdictRowRef,
|
||||
handleSave, handleFileChange, pickGalleryPhoto, removePhoto, searchLocation, pickLocation, handleUseCurrentLocation,
|
||||
} = useJourneyEntryForm({
|
||||
@@ -193,6 +193,11 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
|
||||
|
||||
const activeExternalProvider = externalProvider || availableProviders[0]?.id || null
|
||||
const providerExistingAssetIds = providerAssetIds(activeExternalProvider)
|
||||
const providerPickerOpen = photoTab === 'external' && photoProvidersOn && !!activeExternalProvider
|
||||
const closeProviderPicker = () => {
|
||||
setPhotoTab('upload')
|
||||
setExternalProvider(null)
|
||||
}
|
||||
|
||||
// Every way out (Cancel, the close button, Escape, the dimmed backdrop) comes
|
||||
// through here, so none of them drops an edit without asking first.
|
||||
@@ -232,9 +237,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Pinned at the top: the photo panels, the verdict rows and the photo
|
||||
strip all change the body's height while an entry is being written. */}
|
||||
<DialogShell onClose={handleClose} labelledBy={labelId} width="wide" align="top" blocked={confirmDiscard} header={header} footer={footer}>
|
||||
<DialogShell onClose={handleClose} labelledBy={labelId} width="wide" blocked={confirmDiscard} covered={providerPickerOpen} header={header} footer={footer}>
|
||||
<div className="grid grid-cols-1 items-stretch gap-x-6 gap-y-5 md:grid-cols-2">
|
||||
<div className="flex min-w-0 flex-col gap-5">
|
||||
<div>
|
||||
@@ -319,86 +322,18 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{photoTab === 'external' && photoProvidersOn && (
|
||||
<div className={`${PHOTO_PANEL} flex flex-col overflow-hidden`} style={{ height: 'min(56vh, 520px)' }}>
|
||||
<div className="flex items-center justify-between gap-2 border-b border-edge-faint px-3 py-2">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-semibold text-content" style={fs(11.5)}>
|
||||
{t('journey.editor.externalPhotosFor', { date: new Date(entryDate + 'T00:00:00').toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) })}
|
||||
</p>
|
||||
<p className="truncate text-content-faint" style={fs(10.5)}>
|
||||
{contextLocation?.name
|
||||
? `${t('journey.editor.externalPhotosNearby') || 'Nearby photos first'}: ${contextLocation.name}`
|
||||
: (t('journey.editor.externalPhotosNoLocation') || 'All photos from this day')}
|
||||
</p>
|
||||
</div>
|
||||
{pendingProviderGroups.length > 0 && (
|
||||
<button type="button" onClick={() => setPendingProviderGroups([])} className="inline-flex items-center gap-1.5 whitespace-nowrap text-content-muted hover:text-content" style={fs(10.5)}>
|
||||
<span>{pendingProviderGroups.reduce((sum, group) => sum + group.assetIds.length, 0)} {t('journey.editor.externalPhotosQueued') || 'queued'}</span>{' '}
|
||||
<span className="font-semibold text-content">{t('common.clear') || 'Clear'}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{providersLoading ? (
|
||||
<div className="flex justify-center py-8"><Loader2 size={20} className="animate-spin text-content-faint" /></div>
|
||||
) : availableProviders.length === 0 ? (
|
||||
<div className="px-4 py-10 text-center text-content-muted" style={fs(12, 'body')}>{t('journey.editor.externalPhotosUnavailable') || 'No connected photo providers are available.'}</div>
|
||||
) : (
|
||||
<div className="flex h-full min-h-0 flex-col">
|
||||
<div className="flex gap-1 overflow-x-auto border-b border-edge-faint px-3 py-2" style={fs(11.5)}>
|
||||
{availableProviders.map(provider => (
|
||||
<button type="button"
|
||||
key={provider.id}
|
||||
data-testid={`journey-external-provider-${provider.id}`}
|
||||
onClick={() => setExternalProvider(provider.id)}
|
||||
aria-pressed={externalProvider === provider.id}
|
||||
className={`whitespace-nowrap rounded-[8px] px-2.5 py-1 font-medium ${externalProvider === provider.id ? 'bg-accent text-accent-text' : 'text-content-muted hover:bg-surface-hover hover:text-content'}`}
|
||||
>
|
||||
{provider.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{activeExternalProvider && (
|
||||
<div className="min-h-0 flex-1">
|
||||
<ProviderPicker
|
||||
key={`${activeExternalProvider}-${entryDate}`}
|
||||
provider={activeExternalProvider}
|
||||
userId={userId}
|
||||
entries={[entry]}
|
||||
trips={trips}
|
||||
existingAssetIds={providerExistingAssetIds}
|
||||
initialDate={entryDate}
|
||||
contextLocation={contextLocation}
|
||||
initialEntryId={entry.id || null}
|
||||
embedded
|
||||
onClose={() => setExternalProvider(null)}
|
||||
onAdd={async groups => {
|
||||
setPendingProviderGroups(previous => {
|
||||
const next = [...previous]
|
||||
for (const group of groups) {
|
||||
const existing = next.find(item => item.provider === activeExternalProvider && item.passphrase === group.passphrase)
|
||||
if (existing) {
|
||||
const seen = new Set(existing.assetIds)
|
||||
group.assetIds.forEach((assetId, index) => {
|
||||
if (seen.has(assetId)) return
|
||||
seen.add(assetId)
|
||||
existing.assetIds.push(assetId)
|
||||
existing.mediaTypes?.push(group.mediaTypes?.[index] || 'image')
|
||||
})
|
||||
} else {
|
||||
next.push({ ...group, provider: activeExternalProvider })
|
||||
}
|
||||
}
|
||||
return next
|
||||
})
|
||||
setExternalProvider(null)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{photoTab === 'external' && photoProvidersOn && !activeExternalProvider && (
|
||||
providersLoading ? (
|
||||
<div className="flex justify-center py-4"><Loader2 size={20} className="animate-spin text-content-faint" /></div>
|
||||
) : (
|
||||
<div className="py-3 text-center text-caption text-content-muted">{t('journey.editor.externalPhotosUnavailable')}</div>
|
||||
)
|
||||
)}
|
||||
{queuedProviderPhotos > 0 && (
|
||||
<button type="button" onClick={() => setPendingProviderGroups([])} className="mt-2 inline-flex items-center gap-1.5 whitespace-nowrap text-caption text-content-muted hover:text-content">
|
||||
<span>{queuedProviderPhotos} {t('journey.editor.externalPhotosQueued')}</span>{' '}
|
||||
<span className="font-semibold text-content">{t('common.clear')}</span>
|
||||
</button>
|
||||
)}
|
||||
{(photos.length > 0 || pendingFiles.length > 0) && (
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
@@ -690,6 +625,26 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
|
||||
</div>
|
||||
</DialogShell>
|
||||
|
||||
{providerPickerOpen && activeExternalProvider && (
|
||||
<ProviderPicker
|
||||
key={`${activeExternalProvider}-${entryDate}`}
|
||||
provider={activeExternalProvider}
|
||||
userId={userId}
|
||||
entries={[entry]}
|
||||
trips={trips}
|
||||
existingAssetIds={providerExistingAssetIds}
|
||||
initialDate={entryDate}
|
||||
contextLocation={contextLocation}
|
||||
initialEntryId={entry.id || null}
|
||||
entryPicker={{ providers: availableProviders, onSelectProvider: setExternalProvider }}
|
||||
onClose={closeProviderPicker}
|
||||
onAdd={async groups => {
|
||||
queueProviderPhotos(activeExternalProvider, groups)
|
||||
closeProviderPicker()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Mounted only while asked, over the editor, which ignores Escape and its
|
||||
backdrop until the question is answered. */}
|
||||
{confirmDiscard && (
|
||||
|
||||
@@ -69,11 +69,6 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, canEdi
|
||||
// Deleting is final on the server and takes the photo out of every entry that
|
||||
// uses it too, so the tile only asks; the dialog does the deleting (#2593).
|
||||
const [deleteTarget, setDeleteTarget] = useState<GalleryPhoto | null>(null)
|
||||
const [showFromPhotos, setShowFromPhotos] = useState(false)
|
||||
const coverOf = (galleryPhotoId: number) => {
|
||||
const photo = allPhotos.find(p => p.id === galleryPhotoId)
|
||||
return photo && !posterlessVideo(photo) ? photoUrl(photo, 'thumbnail') : null
|
||||
}
|
||||
|
||||
const handleDeletePhoto = async (galleryPhotoId: number) => {
|
||||
const store = useJourneyStore.getState()
|
||||
@@ -90,31 +85,11 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, canEdi
|
||||
<div>
|
||||
<input ref={galleryFileRef} type="file" accept="image/*,video/*" multiple onChange={handleGalleryUpload} className="hidden" />
|
||||
|
||||
{/* Header — the provider buttons live in the page header next to Upload */}
|
||||
<div className="flex items-center justify-between mb-4 flex-wrap gap-2">
|
||||
<div className="mb-4">
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-[0.07em]" style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}>
|
||||
<Camera size={11} /> {allPhotos.length} {t('journey.detail.photos', { count: allPhotos.length })}
|
||||
</span>
|
||||
{/* #1920: the gallery's loose photos as drafts, grouped by day and place. */}
|
||||
{canEdit && allPhotos.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowFromPhotos(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-caption font-semibold transition-colors hover:bg-surface-hover"
|
||||
style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<NotebookPen size={13} /> {t('journey.fromPhotos.title')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{showFromPhotos && (
|
||||
<JourneyFromPhotosDialog
|
||||
journeyId={journeyId}
|
||||
coverOf={coverOf}
|
||||
onCreated={onRefresh}
|
||||
onClose={() => setShowFromPhotos(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{allPhotos.length === 0 ? (
|
||||
<EmptyState scene="journey" title={t('journey.detail.noPhotos')} />
|
||||
@@ -212,3 +187,38 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, canEdi
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CreateEntriesFromPhotosButton({ journeyId, gallery, onCreated, className }: {
|
||||
journeyId: number
|
||||
gallery: GalleryPhoto[]
|
||||
onCreated: () => void
|
||||
className: string
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
className={className}
|
||||
style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<NotebookPen size={16} strokeWidth={2.4} />
|
||||
{t('journey.fromPhotos.title')}
|
||||
</button>
|
||||
{open && (
|
||||
<JourneyFromPhotosDialog
|
||||
journeyId={journeyId}
|
||||
coverOf={galleryPhotoId => {
|
||||
const photo = gallery.find(p => p.id === galleryPhotoId)
|
||||
return photo && !posterlessVideo(photo) ? photoUrl(photo, 'thumbnail') : null
|
||||
}}
|
||||
onCreated={onCreated}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -392,11 +392,10 @@ describe('ProviderPicker', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-JRN-PICKER-018: the embedded variant drops the header, the add-to bar and the date captions', async () => {
|
||||
mountPicker({ embedded: true, initialDate: '2026-03-15' })
|
||||
it('FE-JRN-PICKER-018: entry mode opens a taller picker and keeps the entry as its target', async () => {
|
||||
mountPicker({ entryPicker: { providers: [{ id: 'immich', name: 'Immich' }], onSelectProvider: vi.fn() }, initialDate: '2026-03-15' })
|
||||
|
||||
expect(await screen.findByTestId('journey-provider-picker-embedded')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: 'Immich' })).not.toBeInTheDocument()
|
||||
expect(await screen.findByRole('dialog', { name: 'Immich' })).toHaveClass('h-full')
|
||||
expect(screen.queryByText('Add to')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('March 15, 2026')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ArrowRight, Calendar, Camera, Check, ChevronRight, Images, Loader2, Play, X } from 'lucide-react';
|
||||
import { useEffect, useId, useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useId, useMemo, useRef, useState, type ComponentType, type ReactNode } from 'react';
|
||||
import { memoriesApi } from '../../api/client';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useIsPhone } from '../../mobile/useIsPhone';
|
||||
@@ -20,9 +20,18 @@ import type { JourneyEntry, JourneyTrip } from '../../store/journeyStore';
|
||||
import { DatePicker } from './JourneyDetailPageDatePicker';
|
||||
import { ScrollTrigger } from './JourneyDetailPageScrollTrigger';
|
||||
import { providerAssetUrl } from './providerAssetUrl';
|
||||
import type { ConnectedPhotoProvider } from './useConnectedPhotoProviders';
|
||||
|
||||
export type ProviderPhotoGroup = { assetIds: string[]; passphrase?: string; mediaTypes?: string[] };
|
||||
|
||||
export interface EntryPhotoPickerFrameProps {
|
||||
title: string;
|
||||
subtitle: ReactNode;
|
||||
onClose: () => void;
|
||||
footer: ReactNode;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** A tile as the search and album routes answer it; only what a pick needs is spelled out. */
|
||||
type PickerAsset = ProviderPhotoAsset & { mediaType?: string };
|
||||
|
||||
@@ -50,7 +59,7 @@ export function ProviderPicker({
|
||||
initialDate,
|
||||
contextLocation,
|
||||
initialEntryId,
|
||||
embedded = false,
|
||||
entryPicker,
|
||||
}: {
|
||||
provider: string;
|
||||
userId: number;
|
||||
@@ -62,9 +71,13 @@ export function ProviderPicker({
|
||||
initialDate?: string;
|
||||
contextLocation?: (GeoPoint & { name?: string }) | null;
|
||||
initialEntryId?: number | null;
|
||||
embedded?: boolean;
|
||||
entryPicker?: {
|
||||
providers: ConnectedPhotoProvider[];
|
||||
onSelectProvider: (provider: string) => void;
|
||||
Frame?: ComponentType<EntryPhotoPickerFrameProps>;
|
||||
};
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { t, locale } = useTranslation();
|
||||
const phone = useIsPhone();
|
||||
const labelId = useId();
|
||||
const [filter, setFilter] = useState<'day' | 'trip' | 'custom' | 'all' | 'album'>(initialDate ? 'day' : 'trip');
|
||||
@@ -329,7 +342,8 @@ export function ProviderPicker({
|
||||
t('journey.stats.entries')
|
||||
: t('journey.picker.newGallery');
|
||||
|
||||
const providerName = provider === 'immich' ? 'Immich' : provider === 'synologyphotos' ? 'Synology Photos' : provider;
|
||||
const providerName = entryPicker?.providers.find((source) => source.id === provider)?.name ??
|
||||
(provider === 'immich' ? 'Immich' : provider === 'synologyphotos' ? 'Synology Photos' : provider);
|
||||
|
||||
const addSelection = async () => {
|
||||
if (adding) return;
|
||||
@@ -357,15 +371,47 @@ export function ProviderPicker({
|
||||
}
|
||||
};
|
||||
|
||||
// Everything between the head and the foot, the same in all three frames below.
|
||||
const subtitle = entryPicker && (
|
||||
<>
|
||||
{initialDate && (
|
||||
<div>{t('journey.editor.externalPhotosFor', {
|
||||
date: new Date(`${initialDate}T00:00:00`).toLocaleDateString(locale, {
|
||||
year: 'numeric', month: 'short', day: 'numeric',
|
||||
}),
|
||||
})}</div>
|
||||
)}
|
||||
<div>
|
||||
{contextLocation?.name
|
||||
? <>{t('journey.editor.externalPhotosNearby')} <bdi>{contextLocation.name}</bdi></>
|
||||
: t('journey.editor.externalPhotosNoLocation')}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
// The filters and selection are the same in each frame.
|
||||
const content = (
|
||||
<>
|
||||
{/* Filter bar. Embedded in the entry editor this sits in a panel a few hundred
|
||||
pixels tall, so its padding is the difference between three rows of
|
||||
thumbnails and two. */}
|
||||
<div className={`flex-shrink-0 border-b border-zinc-200 dark:border-zinc-700 ${embedded ? 'px-3 py-2' : 'px-6 py-3'}`}>
|
||||
<div className={`flex-shrink-0 border-b border-zinc-200 dark:border-zinc-700 ${entryPicker ? 'px-3 py-2' : 'px-6 py-3'}`}>
|
||||
{entryPicker && entryPicker.providers.length > 1 && (
|
||||
<div className="mb-2 flex gap-1 overflow-x-auto" role="group" aria-label={t('journey.editor.externalPhotos')}>
|
||||
{entryPicker.providers.map((source) => (
|
||||
<button
|
||||
type="button"
|
||||
key={source.id}
|
||||
data-testid={`journey-external-provider-${source.id}`}
|
||||
aria-pressed={provider === source.id}
|
||||
onClick={() => entryPicker.onSelectProvider(source.id)}
|
||||
className={`shrink-0 rounded-lg px-2.5 py-1 text-caption font-medium ${provider === source.id
|
||||
? 'bg-accent text-accent-text'
|
||||
: 'text-content-muted hover:bg-surface-hover hover:text-content'}`}
|
||||
>
|
||||
{source.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{/* Tabs */}
|
||||
<div className={`flex gap-1.5 ${embedded && filter === 'day' ? '' : 'mb-3'}`}>
|
||||
<div className={`flex gap-1.5 ${entryPicker ? 'overflow-x-auto' : ''} ${entryPicker && filter === 'day' ? '' : 'mb-3'}`}>
|
||||
{[
|
||||
...(initialDate ? [{ id: 'day' as const, label: t('journey.picker.day') || 'This day' }] : []),
|
||||
{ id: 'trip' as const, label: t('journey.picker.tripPeriod') },
|
||||
@@ -377,7 +423,7 @@ export function ProviderPicker({
|
||||
type="button"
|
||||
key={f.id}
|
||||
onClick={() => switchTab(f.id)}
|
||||
className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${
|
||||
className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${entryPicker ? 'shrink-0 whitespace-nowrap' : ''} ${
|
||||
filter === f.id
|
||||
? 'bg-zinc-900 text-white dark:bg-white dark:text-zinc-900'
|
||||
: 'text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800'
|
||||
@@ -396,7 +442,7 @@ export function ProviderPicker({
|
||||
</div>
|
||||
|
||||
{/* Filter content — always visible row */}
|
||||
{(!embedded || filter !== 'day') && (
|
||||
{(!entryPicker || filter !== 'day') && (
|
||||
<div className="flex min-h-[36px] items-center">
|
||||
{filter === 'day' && initialDate && (
|
||||
<div className="flex items-center gap-2 text-[12px] text-zinc-500">
|
||||
@@ -531,7 +577,7 @@ export function ProviderPicker({
|
||||
</div>
|
||||
|
||||
{/* Add-to entry selector */}
|
||||
{!embedded && (
|
||||
{!entryPicker && (
|
||||
<div className="flex-shrink-0 border-b border-zinc-200 bg-zinc-50 px-6 py-2.5 dark:border-zinc-700 dark:bg-zinc-800/50">
|
||||
<div className="relative flex items-center gap-2">
|
||||
<span className="text-[10px] font-semibold tracking-[0.12em] text-zinc-500 uppercase">
|
||||
@@ -666,7 +712,7 @@ export function ProviderPicker({
|
||||
<div>
|
||||
{groupPhotosByDate(sortedPhotos).map((group) => (
|
||||
<div key={group.date}>
|
||||
{(!embedded || filter !== 'day') && (
|
||||
{(!entryPicker || filter !== 'day') && (
|
||||
<p className="mt-4 mb-2 text-[11px] font-medium text-zinc-500 first:mt-0 dark:text-zinc-400">
|
||||
{group.label}
|
||||
</p>
|
||||
@@ -741,9 +787,31 @@ export function ProviderPicker({
|
||||
</>
|
||||
);
|
||||
|
||||
// The desktop draws the standalone picker in the planner's dialog frame. The
|
||||
// phone keeps its sheet below, and the embedded picker has no frame at all.
|
||||
if (!embedded && !phone) {
|
||||
const footer = (
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
onClick={() => void addSelection()}
|
||||
disabled={addDisabled}
|
||||
icon={adding ? <Loader2 size={14} className="animate-spin" /> : undefined}
|
||||
>
|
||||
{t('common.add')} {selected.size > 0 ? `(${selected.size})` : ''}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
);
|
||||
|
||||
const EntryFrame = entryPicker?.Frame;
|
||||
if (EntryFrame) {
|
||||
return (
|
||||
<EntryFrame title={providerName} subtitle={subtitle} onClose={onClose} footer={footer}>
|
||||
{content}
|
||||
</EntryFrame>
|
||||
);
|
||||
}
|
||||
|
||||
if (entryPicker || !phone) {
|
||||
return (
|
||||
<DialogShell
|
||||
// With the add-to menu open, Escape and a click beside the dialog close
|
||||
@@ -754,8 +822,9 @@ export function ProviderPicker({
|
||||
}}
|
||||
labelledBy={labelId}
|
||||
width="wide"
|
||||
fillHeight={!!entryPicker}
|
||||
// The tabs change how much the grid holds, so the upper edge stays put.
|
||||
align="top"
|
||||
align={entryPicker ? 'center' : 'top'}
|
||||
header={(
|
||||
<DialogHeader
|
||||
tile={<DialogTile><Images size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
|
||||
@@ -763,24 +832,12 @@ export function ProviderPicker({
|
||||
labelId={labelId}
|
||||
onClose={onClose}
|
||||
title={providerName}
|
||||
sub={subtitle}
|
||||
/>
|
||||
)}
|
||||
// The bars stay pinned above the grid, which scrolls on its own.
|
||||
bodyClassName="flex min-h-0 flex-1 flex-col"
|
||||
footer={(
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
onClick={() => void addSelection()}
|
||||
disabled={addDisabled}
|
||||
icon={adding ? <Loader2 size={14} className="animate-spin" /> : undefined}
|
||||
>
|
||||
{t('common.add')} {selected.size > 0 ? `(${selected.size})` : ''}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
)}
|
||||
footer={footer}
|
||||
>
|
||||
{content}
|
||||
</DialogShell>
|
||||
@@ -789,51 +846,36 @@ export function ProviderPicker({
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid={embedded ? 'journey-provider-picker-embedded' : undefined}
|
||||
className={
|
||||
embedded
|
||||
? 'flex h-full min-h-0 w-full flex-col overflow-hidden'
|
||||
: 'fixed inset-0 z-[9999] flex items-end justify-center overscroll-none bg-[rgba(9,9,11,0.75)] md:items-center md:p-5'
|
||||
}
|
||||
className="fixed inset-0 z-[9999] flex items-end justify-center overscroll-none bg-[rgba(9,9,11,0.75)] md:items-center md:p-5"
|
||||
role="presentation"
|
||||
onClick={embedded ? undefined : onClose}
|
||||
onClick={onClose}
|
||||
onTouchMove={(e) => {
|
||||
if (!embedded && e.target === e.currentTarget) e.preventDefault();
|
||||
if (e.target === e.currentTarget) e.preventDefault();
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={
|
||||
embedded
|
||||
? 'flex h-full w-full flex-col overflow-hidden bg-white dark:bg-zinc-900'
|
||||
: 'flex max-h-[calc(100dvh-var(--bottom-nav-h)-20px)] w-full max-w-[720px] flex-col overflow-hidden rounded-t-2xl bg-white shadow-[0_20px_40px_rgba(0,0,0,0.2)] md:max-h-[85vh] md:max-w-[960px] md:rounded-2xl dark:bg-zinc-900'
|
||||
}
|
||||
className="flex max-h-[calc(100dvh-var(--bottom-nav-h)-20px)] w-full max-w-[720px] flex-col overflow-hidden rounded-t-2xl bg-white shadow-[0_20px_40px_rgba(0,0,0,0.2)] md:max-h-[85vh] md:max-w-[960px] md:rounded-2xl dark:bg-zinc-900"
|
||||
style={{ paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}
|
||||
role="presentation"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
{!embedded && (
|
||||
<div className="flex flex-shrink-0 items-center justify-between border-b border-zinc-200 px-6 py-4 dark:border-zinc-700">
|
||||
<h2 className="text-[16px] font-bold text-zinc-900 dark:text-white">
|
||||
{providerName}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="flex h-8 w-8 items-center justify-center rounded-lg text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-shrink-0 items-center justify-between border-b border-zinc-200 px-6 py-4 dark:border-zinc-700">
|
||||
<h2 className="text-[16px] font-bold text-zinc-900 dark:text-white">
|
||||
{providerName}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="flex h-8 w-8 items-center justify-center rounded-lg text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{content}
|
||||
|
||||
{/* Footer. The count used to sit here as its own pill as well as on the Add
|
||||
button; one of the two was always saying it twice, and inside the entry
|
||||
editor the row it took cost the grid a row of thumbnails (discussion
|
||||
#2299). Embedded, the whole bar is tighter for the same reason. */}
|
||||
<div className={`flex flex-shrink-0 items-center justify-end border-t border-zinc-200 bg-zinc-50 dark:border-zinc-700 dark:bg-zinc-800/50 ${embedded ? 'px-3 py-2' : 'px-6 py-4'}`}>
|
||||
<div className="flex flex-shrink-0 items-center justify-end border-t border-zinc-200 bg-zinc-50 px-6 py-4 dark:border-zinc-700 dark:bg-zinc-800/50">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -278,7 +278,7 @@ export default function JourneyMapLayerControl({
|
||||
style={FROSTED_SHELL}
|
||||
role="group"
|
||||
aria-label={t('journey.map.layers')}
|
||||
className="max-w-full gap-0.5 overflow-x-auto"
|
||||
className="max-w-full gap-1 overflow-x-auto"
|
||||
>
|
||||
{layers.controls.map((control) => (
|
||||
<LayerToggle
|
||||
@@ -289,7 +289,7 @@ export default function JourneyMapLayerControl({
|
||||
compact={compact}
|
||||
/>
|
||||
))}
|
||||
<span aria-hidden className="mx-0.5 h-5 w-px flex-none bg-edge" />
|
||||
<span aria-hidden className="h-5 w-px flex-none bg-edge" />
|
||||
<KeyButton />
|
||||
<span role="status" aria-live="polite" className="sr-only">
|
||||
{live}
|
||||
|
||||
@@ -181,6 +181,26 @@ export function useJourneyEntryForm({
|
||||
const availableGalleryPhotos = galleryPhotos.filter((gp) => !photos.some((p) => p.id === gp.id));
|
||||
const queuedProviderPhotos = pendingProviderGroups.reduce((sum, group) => sum + group.assetIds.length, 0);
|
||||
|
||||
const queueProviderPhotos = (provider: string, groups: ProviderPhotoGroup[]) => {
|
||||
setPendingProviderGroups((previous) => {
|
||||
const next = [...previous];
|
||||
for (const group of groups) {
|
||||
const index = next.findIndex((pick) => pick.provider === provider && pick.passphrase === group.passphrase);
|
||||
const existing = next[index];
|
||||
if (!existing) {
|
||||
next.push({ ...group, provider });
|
||||
continue;
|
||||
}
|
||||
const assets = new Map(existing.assetIds.map((id, i) => [id, existing.mediaTypes?.[i] ?? 'image']));
|
||||
group.assetIds.forEach((id, i) => {
|
||||
if (!assets.has(id)) assets.set(id, group.mediaTypes?.[i] ?? 'image');
|
||||
});
|
||||
next[index] = { ...existing, assetIds: [...assets.keys()], mediaTypes: [...assets.values()] };
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
/** The provider assets already on the entry or queued for it, so the picker can mark them. */
|
||||
const providerAssetIds = (provider: string | null): Set<string> => {
|
||||
const ids = new Set<string>();
|
||||
@@ -625,6 +645,7 @@ export function useJourneyEntryForm({
|
||||
pendingPreviews,
|
||||
pendingProviderGroups,
|
||||
setPendingProviderGroups,
|
||||
queueProviderPhotos,
|
||||
showGalleryPick,
|
||||
setShowGalleryPick,
|
||||
isDirty,
|
||||
|
||||
@@ -102,6 +102,23 @@ describe('TerminalStop', () => {
|
||||
expect(screen.getByText('HAM')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-BOOKINGROWS-001d: a place the booking is driven through reads the place, not the booking', () => {
|
||||
// The booking's name belongs on the desks, where the car changes hands. On a place
|
||||
// the drive only passes through, it says the same thing twice and names no place:
|
||||
// a car taken Hanover → Osnabrück → Bremen read "Weird Roadtrip" where Osnabrück goes.
|
||||
wrap(
|
||||
<TerminalStop
|
||||
stop={stop({ name: 'Osnabrück', carrier: carrier({ type: 'car', role: 'stop', code: null }) })}
|
||||
booking={booking({ id: 7, type: 'car', title: 'Weird Roadtrip' })}
|
||||
entry={entry()}
|
||||
late={[]}
|
||||
continues
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Osnabrück')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Weird Roadtrip')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-BOOKINGROWS-001c: a check-in the drive cannot make takes no pill on the card, neither the check-in nor that it is missed', () => {
|
||||
wrap(
|
||||
<TerminalStop
|
||||
|
||||
@@ -41,10 +41,16 @@ export function TerminalStop({ stop, booking, entry, late, continues, starts, on
|
||||
const { t } = useTranslation()
|
||||
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||
const { end, desk, checkIn } = terminalReading(stop, entry, late, t, is12h)
|
||||
// Only ever called for a stop a booking put on the day, which is what carries one.
|
||||
const carrier = stop.carrier!
|
||||
// A place the booking is driven through is that place. The booking's own name belongs
|
||||
// on the desks, where the car changes hands and the name is what the traveller asks
|
||||
// for; on the road between them it says the same thing twice and names no place.
|
||||
const title = carrier.role === 'stop' ? end.place : (booking?.title ?? end.place)
|
||||
return (
|
||||
<TransportCard
|
||||
type={booking?.type ?? stop.carrier!.type}
|
||||
title={booking?.title ?? end.place}
|
||||
type={booking?.type ?? carrier.type}
|
||||
title={title}
|
||||
clock={end.clock ? <TimetableClock end={end} /> : entry?.arrival ? <Arrival entry={entry} /> : null}
|
||||
checkIn={checkIn?.state === 'ok' ? checkIn : null}
|
||||
starts={starts}
|
||||
|
||||
@@ -122,7 +122,7 @@ function rideEnd(stop: RoadtripStop, entry: ScheduleEntry | undefined, t: Transl
|
||||
placeLine: carrier.code && carrier.code !== place ? place : null,
|
||||
clock,
|
||||
dayOffset: entry?.dayOffset ?? 0,
|
||||
label: clock ? t(key, { time: clock }) : null,
|
||||
label: clock && carrier.role !== 'stop' ? t(key, { time: clock }) : null,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1146,6 +1146,99 @@ describe('a booking the traveller rides (#2428)', () => {
|
||||
expect(result.current.totalStops).toBe(2)
|
||||
expect(result.current.lines).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-ROUTES-069: the drive to the return desk runs over the stops the booking names', async () => {
|
||||
// Reported on a hire car booked with a stop in the middle: the day plan routed over
|
||||
// that stop and the road trip drew the short way round, which is a different
|
||||
// journey from the one booked.
|
||||
calculateRouteWithLegs.mockImplementation(async (points: { lat: number; lng: number }[]) => hourly(points))
|
||||
const viaBerlin = flight({
|
||||
id: 72,
|
||||
type: 'car',
|
||||
title: 'Sixt Hamburg',
|
||||
reservation_time: '09:00',
|
||||
reservation_end_time: '18:00',
|
||||
endpoints: [
|
||||
{ role: 'from', sequence: 0, name: 'Hamburg', code: null, lat: HAMBURG[0], lng: HAMBURG[1], timezone: null, local_time: null, local_date: null },
|
||||
{ role: 'stop', sequence: 1, name: 'Lüneburg', code: null, lat: LUENEBURG[0], lng: LUENEBURG[1], timezone: null, local_time: null, local_date: null },
|
||||
{ role: 'to', sequence: 2, name: 'Berlin', code: null, lat: BERLIN[0], lng: BERLIN[1], timezone: null, local_time: null, local_date: null },
|
||||
],
|
||||
})
|
||||
const { result } = renderHook(() => useRoadtripRoutes(7, [day(1, 1)], map(1, []), 'driving', {}, [], [], [viaBerlin]))
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
|
||||
// Two desks with the place it is driven through standing between them as a stop of
|
||||
// the drive, and the road asked for runs over it.
|
||||
expect(result.current.days[0].stops.map(s => `${s.carrier?.role}:${s.name}`))
|
||||
.toEqual(['pickup:Hamburg', 'stop:Lüneburg', 'return:Berlin'])
|
||||
// Driven through and nothing more: it holds the drive up by no minutes at all.
|
||||
expect(result.current.days[0].stops[1]).toMatchObject({ dwellMinutes: 0, time: null })
|
||||
const asked = calculateRouteWithLegs.mock.calls.map(c => c[0].map((p: { lat: number }) => p.lat))
|
||||
expect(asked).toEqual([[HAMBURG[0], LUENEBURG[0], BERLIN[0]]])
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-ROUTES-070: the destination standing on the day as well keeps the road on the booking', async () => {
|
||||
// The usual shape: the car goes back to a desk at the destination, and the destination
|
||||
// is on the day as a place too (a stay seats it there, a clock here), so the run holds
|
||||
// a stop of the day's own between the two desks. The booking's own stop keeps its
|
||||
// place behind the pick-up, and the drive still passes through it first.
|
||||
calculateRouteWithLegs.mockImplementation(async (points: { lat: number; lng: number }[]) => hourly(points))
|
||||
const viaBerlin = flight({
|
||||
id: 72,
|
||||
type: 'car',
|
||||
title: 'Sixt Hamburg',
|
||||
reservation_time: '09:00',
|
||||
reservation_end_time: '18:00',
|
||||
endpoints: [
|
||||
{ role: 'from', sequence: 0, name: 'Hamburg', code: null, lat: HAMBURG[0], lng: HAMBURG[1], timezone: null, local_time: null, local_date: null },
|
||||
{ role: 'stop', sequence: 1, name: 'Lüneburg', code: null, lat: LUENEBURG[0], lng: LUENEBURG[1], timezone: null, local_time: null, local_date: null },
|
||||
{ role: 'to', sequence: 2, name: 'Berlin', code: null, lat: BERLIN[0], lng: BERLIN[1], timezone: null, local_time: null, local_date: null },
|
||||
],
|
||||
})
|
||||
const berlinOnTheDay = map(1, [{ id: 1, at: BERLIN, time: '17:00' }])
|
||||
const { result } = renderHook(() => useRoadtripRoutes(7, [day(1, 1)], berlinOnTheDay, 'driving', {}, [], [], [viaBerlin]))
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
|
||||
expect(result.current.days[0].stops.map(s => s.carrier?.role ?? 'day')).toEqual(['pickup', 'stop', 'day', 'return'])
|
||||
const asked = calculateRouteWithLegs.mock.calls.map(c => c[0].map((p: { lat: number }) => p.lat))
|
||||
// Hamburg → Lüneburg → the day's Berlin stop → the desk there, not Hamburg → Berlin.
|
||||
expect(asked).toEqual([[HAMBURG[0], LUENEBURG[0], BERLIN[0], BERLIN[0]]])
|
||||
})
|
||||
|
||||
it('FE-ROADTRIP-ROUTES-071: the drive back to the desk is asked for across midnight without one continuous drive', async () => {
|
||||
// A car taken out in the morning and handed back at 02:00 the next day. The road to
|
||||
// the desk is the booking's own, not the gap a day-at-a-time routing leaves between
|
||||
// two cards, so it is asked for with "one continuous drive" off, as it is here.
|
||||
calculateRouteWithLegs.mockImplementation(async (points: { lat: number; lng: number }[]) => hourly(points))
|
||||
const overnight = flight({
|
||||
id: 73,
|
||||
type: 'car',
|
||||
title: 'Sixt Hamburg',
|
||||
day_id: 1,
|
||||
end_day_id: 2,
|
||||
reservation_time: '06:00',
|
||||
reservation_end_time: '02:00',
|
||||
endpoints: [
|
||||
{ role: 'from', sequence: 0, name: 'Hamburg', code: null, lat: HAMBURG[0], lng: HAMBURG[1], timezone: null, local_time: null, local_date: null },
|
||||
{ role: 'stop', sequence: 1, name: 'Lüneburg', code: null, lat: LUENEBURG[0], lng: LUENEBURG[1], timezone: null, local_time: null, local_date: null },
|
||||
{ role: 'to', sequence: 2, name: 'Berlin', code: null, lat: BERLIN[0], lng: BERLIN[1], timezone: null, local_time: null, local_date: null },
|
||||
],
|
||||
})
|
||||
const days = [day(1, 1), day(2, 2)]
|
||||
const { result } = renderHook(() => useRoadtripRoutes(7, days, map(1, []), 'driving', {}, [], [], [overnight]))
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
|
||||
// A desk on each day, and the place it is driven through on the day it set out.
|
||||
expect(result.current.days.map(d => d.stops.map(s => `${s.carrier?.role}:${s.name}`))).toEqual([
|
||||
['pickup:Hamburg', 'stop:Lüneburg'],
|
||||
['return:Berlin'],
|
||||
])
|
||||
await waitFor(() => {
|
||||
const asked = calculateRouteWithLegs.mock.calls.map(c => c[0].map((p: { lat: number }) => p.lat))
|
||||
// The day's own road, then the one leading to the desk it goes back to.
|
||||
expect(asked).toEqual([[HAMBURG[0], LUENEBURG[0]], [LUENEBURG[0], BERLIN[0]]])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
|
||||
import { assembleRoadtrip, bookendStaysOf, carrierLegsFor, carrierSeam, foldRouteRun, hotelBookendsOn, isCarrierMode, isStationaryJoin, mergeRouteSegments, oneNightPerStay, seatCarrierStops, seatNightBookends, standsAsDay, terminalAssignmentId, viasOnLeg, type CarrierSeam, type RoadtripStop, type RoadtripRoutes, type PlanDay, type QuietDay, type RoutedLeg } from '@trek/shared/roadtrip'
|
||||
import { assembleRoadtrip, bookendStaysOf, carrierLegsFor, carrierSeam, foldRouteRun, hotelBookendsOn, incomingDayJoin, isCarrierMode, isStationaryJoin, mergeRouteSegments, oneNightPerStay, seatCarrierStops, seatNightBookends, standsAsDay, terminalAssignmentId, viasOnLeg, type CarrierSeam, type RoadtripStop, type RoadtripRoutes, type PlanDay, type QuietDay, type RoutedLeg } from '@trek/shared/roadtrip'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { avoidedClasses, calculateRouteWithLegs, routeEngineFor, RoutingRefusedError } from '../Map/RouteCalculator'
|
||||
import { routerAsks } from '../Map/routerAsks'
|
||||
@@ -693,14 +693,13 @@ export function useRoadtripRoutes(
|
||||
want(from, to, chain.dayId)
|
||||
}
|
||||
}
|
||||
// And, when the traveller asks for one continuous drive, the road from each card's
|
||||
// last stop to the next card's first — the one gap a day-at-a-time routing leaves.
|
||||
if (connectDays) {
|
||||
for (let d = 0; d < routingChains.length - 1; d++) {
|
||||
const from = routingChains[d].stops[routingChains[d].stops.length - 1]
|
||||
const to = routingChains[d + 1].stops[0]
|
||||
if (from && to) want(from, to, routingChains[d + 1].dayId)
|
||||
}
|
||||
for (let d = 1; d < routingChains.length; d++) {
|
||||
const previous = routingChains[d - 1]
|
||||
const chain = routingChains[d]
|
||||
if (!previous || !chain) continue
|
||||
const to = chain.stops[0]
|
||||
const from = incomingDayJoin(previous.stops, chain.stops, connectDays)
|
||||
if (from && to) want(from, to, chain.dayId)
|
||||
}
|
||||
return { seams: out, seamMisses: misses }
|
||||
}, [chains, plan, quietDays, window, legsByDay, seamLegs, rideLegs, viasByDay, connectDays, legModeOf, avoidKey, distanceUnit])
|
||||
|
||||
@@ -161,9 +161,11 @@ ${singleRule(input)}
|
||||
.bx-book { display: flex; flex-direction: column; align-items: center; gap: 16px; padding: 16px 0; }
|
||||
.bx-sheet { box-shadow: 0 2px 12px rgba(0,0,0,0.35); }
|
||||
@media print {
|
||||
html, body { background: ${PAPER}; }
|
||||
/* Undo the copied app scroll bounds so the printer can paginate the whole book. */
|
||||
html, body { height: auto; overflow: visible; background: ${PAPER}; }
|
||||
.bx-book { display: block; gap: 0; padding: 0; }
|
||||
.bx-sheet { box-shadow: none; }
|
||||
/* A clipped half-spread must not widen the sheet when Chromium fits it to paper. */
|
||||
.bx-sheet { contain: strict; box-shadow: none; }
|
||||
/* Photographs are the point. Without this the browser drops backgrounds
|
||||
and colour-managed fills to save toner, which is right for a web page
|
||||
and wrong for a photo book. */
|
||||
|
||||
@@ -379,6 +379,7 @@ describe('TripFormModal', () => {
|
||||
await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Alpine Trip');
|
||||
await user.type(screen.getByPlaceholderText('Search destination photos'), 'alps');
|
||||
await user.click(screen.getByRole('button', { name: /Search Unsplash/i }));
|
||||
expect(await screen.findByAltText('Mountain lake')).toHaveAttribute('title', 'Mountain lake');
|
||||
await user.click(await screen.findByRole('button', { name: /Use Unsplash photo by Alice/i }));
|
||||
|
||||
const submitBtn = screen.getAllByText('Create New Trip').find(el => el.closest('button'))!;
|
||||
@@ -777,6 +778,7 @@ describe('TripFormModal', () => {
|
||||
|
||||
const photoBtn = await screen.findByRole('button', { name: 'Use Unsplash photo by Unsplash' });
|
||||
expect(photoBtn.querySelector('img')).toHaveAttribute('alt', '');
|
||||
expect(photoBtn.querySelector('img')).not.toHaveAttribute('title');
|
||||
expect(photoBtn.querySelector('span')).toBeNull();
|
||||
|
||||
// An empty url is not selectable — nothing is staged.
|
||||
|
||||
@@ -494,6 +494,7 @@ export default function TripFormModal({
|
||||
<img
|
||||
src={photo.thumb}
|
||||
alt={photo.description || ''}
|
||||
title={photo.description || undefined}
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
|
||||
@@ -26,10 +26,14 @@ export interface DialogShellProps {
|
||||
labelledBy: string
|
||||
/** 520 px for a single question, 600 px for a detail, 720 px for an editor, 960 px for one in two columns. */
|
||||
width?: keyof typeof PANEL_WIDTH
|
||||
/** Fill the available height when the body is a browser with its own scrolling area. */
|
||||
fillHeight?: boolean
|
||||
/** 'top' pins the upper edge, so a dialog whose content changes height does not jump. */
|
||||
align?: 'center' | 'top'
|
||||
/** True while a question opened from here is being answered: Escape and the backdrop leave the dialog alone. */
|
||||
blocked?: boolean
|
||||
/** A separate dialog is open in front of this one. */
|
||||
covered?: boolean
|
||||
header: ReactNode
|
||||
footer?: ReactNode
|
||||
/** Makes the scrolling body a form. */
|
||||
@@ -86,7 +90,7 @@ export function DialogShell({ open = true, ...frame }: DialogShellProps) {
|
||||
return open ? <DialogFrame {...frame} /> : null
|
||||
}
|
||||
|
||||
function DialogFrame({ onClose, labelledBy, width = 'detail', align = 'center', blocked = false, header, footer, onSubmit, children, bodyClassName, onPaste, discardGuard }: Omit<DialogShellProps, 'open'>) {
|
||||
function DialogFrame({ onClose, labelledBy, width = 'detail', fillHeight = false, align = 'center', blocked = false, covered = false, header, footer, onSubmit, children, bodyClassName, onPaste, discardGuard }: Omit<DialogShellProps, 'open'>) {
|
||||
const { t } = useTranslation()
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const pressedOn = useRef<EventTarget | null>(null)
|
||||
@@ -95,7 +99,7 @@ function DialogFrame({ onClose, labelledBy, width = 'detail', align = 'center',
|
||||
// The unsaved-changes question (#2253). The backdrop and Escape are the two
|
||||
// ways out a hand can take by accident; both go through requestClose.
|
||||
const { asking, markStart, requestClose, keepEditing, discard } = useDiscardGuard(discardGuard, onClose)
|
||||
const held = blocked || asking
|
||||
const held = blocked || covered || asking
|
||||
|
||||
useEffect(() => {
|
||||
if (held) return
|
||||
@@ -133,6 +137,8 @@ function DialogFrame({ onClose, labelledBy, width = 'detail', align = 'center',
|
||||
return createPortal(
|
||||
<div
|
||||
role="presentation"
|
||||
aria-hidden={covered || undefined}
|
||||
inert={covered || undefined}
|
||||
className={`${BACKDROP} ${align === 'top' ? 'items-start' : 'items-center'}`}
|
||||
style={{ paddingTop: 40, paddingBottom: 'calc(40px + var(--bottom-nav-h, 0px))' }}
|
||||
// Only a press that starts and ends on the backdrop closes: a selection
|
||||
@@ -157,7 +163,7 @@ function DialogFrame({ onClose, labelledBy, width = 'detail', align = 'center',
|
||||
}}
|
||||
onPointerDownCapture={markStart}
|
||||
onKeyDown={e => { if (panelRef.current) trapTab(e, panelRef.current) }}
|
||||
className={`trek-modal-enter relative flex max-h-full w-full ${PANEL_WIDTH[width]} flex-col overflow-hidden rounded-[22px] bg-surface-card shadow-2xl outline-none`}
|
||||
className={`trek-modal-enter relative flex max-h-full w-full ${PANEL_WIDTH[width]} flex-col overflow-hidden rounded-[22px] bg-surface-card shadow-2xl outline-none${fillHeight ? ' h-full' : ''}`}
|
||||
>
|
||||
{header}
|
||||
{body}
|
||||
|
||||
@@ -9,13 +9,13 @@ import { useOverlay } from '../overlayStack'
|
||||
import { tickHaptic } from '../../native/haptics'
|
||||
import { useNativeQuestion } from '../../native/useNativeQuestion'
|
||||
|
||||
export type MSheetVariant = 'card' | 'bottom' | 'drawer'
|
||||
export type MSheetVariant = 'card' | 'bottom' | 'drawer' | 'fullscreen'
|
||||
export type MSheetMaterial = 'glass' | 'bar-glass' | 'opaque'
|
||||
|
||||
interface MSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
/** card = centred floating card, bottom = docked panel above the nav, drawer = left drawer */
|
||||
/** card = centred card, bottom = docked above the nav, drawer = side drawer, fullscreen = fills the window */
|
||||
variant?: MSheetVariant
|
||||
/**
|
||||
* @deprecated Every sheet stands on the one opaque surface now (--m-sheetop),
|
||||
@@ -31,6 +31,8 @@ interface MSheetProps {
|
||||
*/
|
||||
dimTransparent?: boolean
|
||||
ariaLabel?: string
|
||||
/** A separate sheet is open in front of this one. */
|
||||
covered?: boolean
|
||||
className?: string
|
||||
children?: ReactNode
|
||||
/**
|
||||
@@ -92,6 +94,7 @@ const REGION: Record<MSheetVariant, string> = {
|
||||
bottom:
|
||||
'inset-x-4 top-[calc(var(--m-safe-top,12px)+56px)] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
|
||||
drawer: 'start-0 top-0 bottom-0 w-[78%] max-w-[320px]',
|
||||
fullscreen: 'inset-0',
|
||||
}
|
||||
|
||||
// On a wide window (hooks/sizeClass.ts) a docked or floating sheet becomes
|
||||
@@ -115,7 +118,7 @@ const SHORT_FORM_BOX = 'short:max-w-[640px] short:flex-1'
|
||||
/** The region the sheet stands in, on a phone and on a wide window. */
|
||||
function regionClass(variant: MSheetVariant, anchor: MSheetWideAnchor = 'center', form = false): string {
|
||||
const base = 'pointer-events-none absolute flex flex-col'
|
||||
if (variant === 'drawer') return `${base} ${REGION.drawer}`
|
||||
if (variant === 'drawer' || variant === 'fullscreen') return `${base} ${REGION[variant]}`
|
||||
// m-safe-trail: on a wide window the sheet keeps off the trailing side's safe area (a Duo's status capsule).
|
||||
return `${base} m-safe-trail ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
|
||||
}
|
||||
@@ -123,13 +126,13 @@ function regionClass(variant: MSheetVariant, anchor: MSheetWideAnchor = 'center'
|
||||
/** The sheet's own box inside the region: its width, and the arrow when it has one. */
|
||||
function boxClass(variant: MSheetVariant, width: MSheetWidth = 'regular', form = false): string {
|
||||
const base = 'pointer-events-auto relative flex min-h-0 w-full flex-col'
|
||||
if (variant === 'drawer') return `${base} h-full`
|
||||
if (variant === 'drawer' || variant === 'fullscreen') return `${base} h-full`
|
||||
return `${base} max-h-full ${WIDE_WIDTH[width]}${form ? ` ${SHORT_FORM_BOX}` : ''}`
|
||||
}
|
||||
|
||||
/** The popover's arrow, pointing at the More button at the foot of the rail (wide windows only). */
|
||||
function PopoverArrow({ variant, anchor }: { variant: MSheetVariant; anchor?: MSheetWideAnchor }) {
|
||||
if (anchor !== 'rail-foot' || variant === 'drawer') return null
|
||||
if (anchor !== 'rail-foot' || variant === 'drawer' || variant === 'fullscreen') return null
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
@@ -145,6 +148,7 @@ const SHAPE: Record<MSheetVariant, string> = {
|
||||
bottom:
|
||||
'[--m-sheet-r:26px] max-h-full shadow-[0_-8px_40px_-14px_rgba(0,0,0,.45)] wide:[--m-sheet-r:28px] wide:shadow-[0_30px_80px_-24px_rgba(0,0,0,.6)]',
|
||||
drawer: '[--m-sheet-r:0px] h-full shadow-[0_0_60px_-10px_rgba(0,0,0,.5)]',
|
||||
fullscreen: '[--m-sheet-r:0px] h-full border-0 pt-[var(--m-safe-t)] pb-[env(safe-area-inset-bottom,0px)]',
|
||||
}
|
||||
|
||||
// The full-height form on a short window: square at the foot, where it meets
|
||||
@@ -162,8 +166,8 @@ const SURFACE = 'bg-[color:var(--m-sheetop)] border border-[color:var(--m-shbr)]
|
||||
|
||||
// The docked sheet rises from below the screen edge like a native sheet; the
|
||||
// card pops in place like an alert; the drawer slides from the side.
|
||||
const ENTER: Record<MSheetVariant, string> = { card: 'm-sheet-in', bottom: 'm-sheet-up', drawer: 'm-drawer-in' }
|
||||
const EXIT: Record<MSheetVariant, string> = { card: 'm-sheet-out', bottom: 'm-sheet-down', drawer: 'm-drawer-out' }
|
||||
const ENTER: Record<MSheetVariant, string> = { card: 'm-sheet-in', bottom: 'm-sheet-up', drawer: 'm-drawer-in', fullscreen: 'm-fade-in' }
|
||||
const EXIT: Record<MSheetVariant, string> = { card: 'm-sheet-out', bottom: 'm-sheet-down', drawer: 'm-drawer-out', fullscreen: 'm-fade-out' }
|
||||
|
||||
function sheetRoot(): HTMLElement {
|
||||
return document.getElementById('m-sheet-root') ?? document.body
|
||||
@@ -181,6 +185,7 @@ export default function MSheet({
|
||||
variant = 'card',
|
||||
dimTransparent = false,
|
||||
ariaLabel,
|
||||
covered,
|
||||
className = '',
|
||||
children,
|
||||
discardGuard,
|
||||
@@ -289,6 +294,8 @@ export default function MSheet({
|
||||
<div
|
||||
className="m-root fixed inset-0 z-[60]"
|
||||
role="presentation"
|
||||
aria-hidden={covered}
|
||||
inert={covered}
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) requestClose()
|
||||
}}
|
||||
|
||||
@@ -440,7 +440,13 @@ function CoverField({ cover, title }: { cover: ReturnType<typeof useTripCoverPic
|
||||
coverPreview === photo.url ? 'border-[color:var(--m-act)]' : 'border-[color:var(--m-rowbr)]'
|
||||
}`}
|
||||
>
|
||||
<img src={photo.thumb} alt={photo.description || ''} loading="lazy" className="h-full w-full object-cover" />
|
||||
<img
|
||||
src={photo.thumb}
|
||||
alt={photo.description || ''}
|
||||
title={photo.description || undefined}
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
{photo.photographer && (
|
||||
<span className="absolute inset-x-0 bottom-0 truncate bg-black/55 px-[6px] py-1 text-start font-geist text-[0.625rem] text-white">
|
||||
{photo.photographer}
|
||||
|
||||
@@ -8,7 +8,7 @@ import MSheet from '../../components/MSheet'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import { SHEET_PRIMARY, SHEET_SECONDARY } from '../trip/sheets/MTripSheetUi'
|
||||
import { FormSheetBody, SheetDateField } from '../trip/sheets/PlSheetChrome'
|
||||
import { FormSheetBody, FormSheetHeader, SheetDateField } from '../trip/sheets/PlSheetChrome'
|
||||
import { useAutoGrow } from '../../../hooks/useAutoGrow'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import CustomTimePicker from '../../../components/shared/CustomTimePicker'
|
||||
@@ -17,12 +17,23 @@ import type { ResilientResult, UploadProgress } from '../../../utils/uploadQueue
|
||||
import type { JourneyEntry, JourneyPhoto, GalleryPhoto, JourneyTrip } from '../../../store/journeyStore'
|
||||
import { photoUrl, posterlessVideo } from '../../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import JournalBody from '../../../components/Journey/JournalBody'
|
||||
import { ProviderPicker } from '../../../components/Journey/JourneyDetailPageProviderPicker'
|
||||
import { ProviderPicker, type EntryPhotoPickerFrameProps } from '../../../components/Journey/JourneyDetailPageProviderPicker'
|
||||
import { MOBILE_MOODS, MOBILE_WEATHERS } from './mobileJourneyMeta'
|
||||
import { useJourneyEntryForm, type PendingProviderGroup } from '../../../components/Journey/useJourneyEntryForm'
|
||||
|
||||
const NO_PROVIDERS: { id: string; name: string }[] = []
|
||||
|
||||
function EntryPhotoPickerSheet({ title, subtitle, onClose, footer, children }: EntryPhotoPickerFrameProps) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<MSheet open onClose={onClose} variant="fullscreen" ariaLabel={title}>
|
||||
<FormSheetHeader icon={Images} title={title} subtitle={subtitle} onClose={onClose} closeLabel={t('common.close')} />
|
||||
<div className="flex min-h-0 flex-1 flex-col">{children}</div>
|
||||
{footer}
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A picked mood chip: its colour as the frame and the label, a light wash of it
|
||||
* behind. The frame is the full colour because a tint alone left the grey neutral
|
||||
@@ -107,7 +118,7 @@ export default function MJourneyEntrySheet({
|
||||
locationName, locationLat, locationQuery, locationResults, showLocationResults, setShowLocationResults,
|
||||
locating, locationError, mood, setMood, weather, setWeather, statsExcluded, setStatsExcluded, tripSuggestion,
|
||||
isDraft, setIsDraft, pros, setPros, cons, setCons, tags, setTags, tagInput, setTagInput, saving, uploadProgress,
|
||||
photos, photoOrder, canReorder, pendingFiles, setPendingFiles, pendingPreviews, setPendingProviderGroups,
|
||||
photos, photoOrder, canReorder, pendingFiles, setPendingFiles, pendingPreviews, setPendingProviderGroups, queueProviderPhotos,
|
||||
showGalleryPick, setShowGalleryPick, isDirty, availableGalleryPhotos, queuedProviderPhotos, providerAssetIds,
|
||||
contextLocation, offersStatsToggle, addVerdictRow, verdictRowRef, addTag, handleSave, handleFileChange,
|
||||
pickGalleryPhoto, removePhoto, searchLocation, pickLocation, handleUseCurrentLocation,
|
||||
@@ -131,6 +142,8 @@ export default function MJourneyEntrySheet({
|
||||
|
||||
const activeProvider = externalProvider || providers[0]?.id || null
|
||||
const providerExistingAssetIds = providerAssetIds(activeProvider)
|
||||
const providerPickerOpen = !readOnly && !captureOnly && showExternal && !!activeProvider
|
||||
const closeProviderPicker = () => setShowExternal(false)
|
||||
|
||||
const handleClose = () => {
|
||||
if (!captureOnly && !readOnly && isDirty && !window.confirm(t('journey.editor.discardChangesConfirm'))) return
|
||||
@@ -154,13 +167,14 @@ export default function MJourneyEntrySheet({
|
||||
const eyebrow = 'font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-faint'
|
||||
const fieldShell = 'rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'
|
||||
|
||||
return (
|
||||
const editor = (
|
||||
<MSheet
|
||||
open
|
||||
onClose={handleClose}
|
||||
variant="card"
|
||||
form
|
||||
ariaLabel={heading}
|
||||
covered={providerPickerOpen}
|
||||
>
|
||||
{/* FormSheetHeader's shape, with the move buttons between the title and the close. */}
|
||||
<div className="m-fs-head flex flex-none items-center gap-3 px-[18px] pb-2 pt-4">
|
||||
@@ -212,22 +226,22 @@ export default function MJourneyEntrySheet({
|
||||
<>
|
||||
<input ref={cameraRef} type="file" accept="image/*" capture="environment" className="hidden" onChange={handleFileChange} onClick={e => { (e.target as HTMLInputElement).value = '' }} />
|
||||
<input ref={fileRef} type="file" accept="image/*,video/*" multiple className="hidden" onChange={handleFileChange} onClick={e => { (e.target as HTMLInputElement).value = '' }} />
|
||||
<div className="flex gap-2">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (captureOnly ? cameraRef : fileRef).current?.click()}
|
||||
disabled={saving}
|
||||
className="flex min-w-0 flex-1 items-center justify-center gap-[6px] rounded-[14px] border-[1.5px] border-dashed border-[color:var(--m-rowbr)] p-3 text-center text-[0.75rem] font-semibold text-m-muted disabled:opacity-50"
|
||||
className="flex min-w-0 flex-[1_1_7rem] items-center justify-center gap-[6px] rounded-[14px] border-[1.5px] border-dashed border-[color:var(--m-rowbr)] p-3 text-center text-[0.75rem] font-semibold text-m-muted disabled:opacity-50"
|
||||
>
|
||||
{uploadProgress ? (
|
||||
<>
|
||||
<span className="h-[14px] w-[14px] shrink-0 animate-spin rounded-full border-2 border-[color:var(--m-rowbr)] border-t-m-muted" />
|
||||
<span className="truncate">{t('journey.editor.uploadingProgress', { done: String(uploadProgress.done), total: String(uploadProgress.total) })}</span>
|
||||
<span className="min-w-0 break-words">{t('journey.editor.uploadingProgress', { done: String(uploadProgress.done), total: String(uploadProgress.total) })}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{captureOnly ? <Camera size={14} strokeWidth={2.2} className="shrink-0" /> : <Plus size={14} strokeWidth={2.2} className="shrink-0" />}
|
||||
<span className="truncate">{captureOnly ? t('journey.photo.add') : t('journey.editor.uploadPhotos')}</span>
|
||||
<span className="min-w-0 break-words">{captureOnly ? t('journey.photo.add') : t('journey.editor.uploadPhotos')}</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
@@ -239,120 +253,42 @@ export default function MJourneyEntrySheet({
|
||||
setShowExternal(false)
|
||||
}}
|
||||
disabled={!captureOnly && galleryPhotos.length === 0}
|
||||
className={`flex min-w-0 flex-1 items-center justify-center gap-[6px] rounded-[14px] border-[1.5px] p-3 text-center text-[0.75rem] font-semibold disabled:opacity-40 ${
|
||||
className={`flex min-w-0 flex-[1_1_7rem] items-center justify-center gap-[6px] rounded-[14px] border-[1.5px] p-3 text-center text-[0.75rem] font-semibold disabled:opacity-40 ${
|
||||
!captureOnly && showGalleryPick
|
||||
? 'border-[color:var(--m-act)] text-m-ink'
|
||||
: 'border-dashed border-[color:var(--m-rowbr)] text-m-muted'
|
||||
}`}
|
||||
>
|
||||
<Image size={14} strokeWidth={2} className="shrink-0" />
|
||||
<span className="truncate">{captureOnly ? t('journey.share.gallery') : t('journey.editor.fromGallery')}</span>
|
||||
<span className="min-w-0 break-words">{captureOnly ? t('journey.share.gallery') : t('journey.editor.fromGallery')}</span>
|
||||
</button>
|
||||
{/* Immich/Synology, the same source the desktop editor offers (#1808).
|
||||
Only shown once a provider is actually connected: on a phone a
|
||||
button that can only say "nothing connected" is not worth its width.
|
||||
The icons keep their size and the labels truncate, so a third
|
||||
button never squeezes the other two (#2908). */}
|
||||
button that can only say "nothing connected" is not worth its width. */}
|
||||
{!captureOnly && providers.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setShowExternal(v => !v); setShowGalleryPick(false) }}
|
||||
onClick={() => { setShowExternal(true); setShowGalleryPick(false) }}
|
||||
disabled={saving}
|
||||
className={`flex min-w-0 flex-1 items-center justify-center gap-[6px] rounded-[14px] border-[1.5px] p-3 text-center text-[0.75rem] font-semibold disabled:opacity-50 ${
|
||||
showExternal
|
||||
? 'border-[color:var(--m-act)] text-m-ink'
|
||||
: 'border-dashed border-[color:var(--m-rowbr)] text-m-muted'
|
||||
}`}
|
||||
aria-haspopup="dialog"
|
||||
className="flex min-w-0 flex-[1_1_7rem] items-center justify-center gap-[6px] rounded-[14px] border-[1.5px] border-dashed border-[color:var(--m-rowbr)] p-3 text-center text-[0.75rem] font-semibold text-m-muted disabled:opacity-50"
|
||||
>
|
||||
<Images size={14} strokeWidth={2} className="shrink-0" />
|
||||
<span className="truncate">{t('journey.editor.externalPhotos')}</span>
|
||||
<span className="min-w-0 break-words">{t('journey.editor.externalPhotos')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Outside the panel: picking collapses it again, and the queue has
|
||||
to stay visible until the save actually writes it. */}
|
||||
{!captureOnly && queuedProviderPhotos > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPendingProviderGroups([])}
|
||||
className="mt-2 rounded-full border border-[color:var(--m-rowbr)] px-3 py-[5px] font-geist text-[0.65625rem] font-semibold text-m-muted"
|
||||
>
|
||||
{queuedProviderPhotos} {t('journey.editor.externalPhotosQueued')} · {t('common.clear')}
|
||||
{queuedProviderPhotos} {t('journey.editor.externalPhotosQueued')} {t('common.clear')}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{!captureOnly && showExternal && activeProvider && (
|
||||
<div
|
||||
className="mt-2 flex flex-col overflow-hidden rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]"
|
||||
style={{ height: 'min(46vh, 420px)' }}
|
||||
>
|
||||
<div className="flex flex-none items-center gap-2 border-b border-[color:var(--m-rowbr)] px-3 py-2">
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-[0.6875rem] font-semibold text-m-muted">
|
||||
{contextLocation?.name
|
||||
? `${t('journey.editor.externalPhotosNearby')} · ${contextLocation.name}`
|
||||
: t('journey.editor.externalPhotosNoLocation')}
|
||||
</span>
|
||||
</div>
|
||||
{providers.length > 1 && (
|
||||
<div className="flex flex-none gap-1 overflow-x-auto border-b border-[color:var(--m-rowbr)] px-3 py-2">
|
||||
{providers.map(provider => (
|
||||
<button
|
||||
key={provider.id}
|
||||
type="button"
|
||||
data-testid={`journey-external-provider-${provider.id}`}
|
||||
onClick={() => setExternalProvider(provider.id)}
|
||||
className={`whitespace-nowrap rounded-full px-[10px] py-[4px] text-[0.6875rem] font-bold ${
|
||||
activeProvider === provider.id ? 'bg-m-act text-m-actfg' : 'text-m-muted'
|
||||
}`}
|
||||
>
|
||||
{provider.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{/* `embedded` is load-bearing: the standalone picker is
|
||||
position:fixed, which the transformed MSheet panel would
|
||||
anchor to itself and then clip. */}
|
||||
<div className="min-h-0 flex-1">
|
||||
<ProviderPicker
|
||||
key={`${activeProvider}-${entryDate}`}
|
||||
provider={activeProvider}
|
||||
userId={userId}
|
||||
entries={[entry]}
|
||||
trips={trips}
|
||||
existingAssetIds={providerExistingAssetIds}
|
||||
initialDate={entryDate}
|
||||
contextLocation={contextLocation}
|
||||
initialEntryId={entry.id || null}
|
||||
embedded
|
||||
onClose={() => setShowExternal(false)}
|
||||
onAdd={async groups => {
|
||||
setPendingProviderGroups(previous => {
|
||||
const next = [...previous]
|
||||
for (const group of groups) {
|
||||
const existing = next.find(item => item.provider === activeProvider && item.passphrase === group.passphrase)
|
||||
if (existing) {
|
||||
const seen = new Set(existing.assetIds)
|
||||
group.assetIds.forEach((assetId, index) => {
|
||||
if (seen.has(assetId)) return
|
||||
seen.add(assetId)
|
||||
existing.assetIds.push(assetId)
|
||||
existing.mediaTypes?.push(group.mediaTypes?.[index] || 'image')
|
||||
})
|
||||
} else {
|
||||
next.push({ ...group, provider: activeProvider })
|
||||
}
|
||||
}
|
||||
return next
|
||||
})
|
||||
setShowExternal(false)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!captureOnly && showGalleryPick && (
|
||||
<div className="mt-2 max-h-[160px] overflow-y-auto rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-2">
|
||||
<div className="grid grid-cols-5 gap-[6px]">
|
||||
@@ -819,4 +755,29 @@ export default function MJourneyEntrySheet({
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{editor}
|
||||
{providerPickerOpen && activeProvider && (
|
||||
<ProviderPicker
|
||||
key={`${activeProvider}-${entryDate}`}
|
||||
provider={activeProvider}
|
||||
userId={userId}
|
||||
entries={[entry]}
|
||||
trips={trips}
|
||||
existingAssetIds={providerExistingAssetIds}
|
||||
initialDate={entryDate}
|
||||
contextLocation={contextLocation}
|
||||
initialEntryId={entry.id || null}
|
||||
entryPicker={{ providers, onSelectProvider: setExternalProvider, Frame: EntryPhotoPickerSheet }}
|
||||
onClose={closeProviderPicker}
|
||||
onAdd={async groups => {
|
||||
queueProviderPhotos(activeProvider, groups)
|
||||
closeProviderPicker()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { opensSoon, refundedBeforeOpening } from './cloudOrders';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from './cloudOrders';
|
||||
|
||||
describe('opensSoon', () => {
|
||||
const base = { available: true, closed: true, sandbox: false, onPlay: false };
|
||||
@@ -33,3 +33,22 @@ describe('refundedBeforeOpening', () => {
|
||||
expect(refundedBeforeOpening(undefined, true)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Cloud catalog and purchase recovery', () => {
|
||||
it('only offers Start and Plus even when the server still lists retired plans', () => {
|
||||
expect(['start', 'basis', 'plus', 'pro'].filter(isNewCloudPlan)).toEqual(['start', 'plus']);
|
||||
});
|
||||
|
||||
it('can finish setup for a verified purchase from a retired tier', () => {
|
||||
expect(planForUnclaimedPurchase('cloud.pro.yearly', 'consent-deviations')).toEqual({
|
||||
plan: { id: 'pro', name: 'Pro' },
|
||||
interval: 'year',
|
||||
});
|
||||
expect(planForUnclaimedPurchase('cloud.basis.monthly', 'email-invalid')).toEqual({
|
||||
plan: { id: 'basis', name: 'Basis' },
|
||||
interval: 'month',
|
||||
});
|
||||
expect(planForUnclaimedPurchase('cloud.pro.yearly', 'ordering-closed')).toBeNull();
|
||||
expect(planForUnclaimedPurchase('cloud.unknown.monthly', 'email-invalid')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,3 +24,27 @@ export function opensSoon(opts: { available: boolean; closed: boolean; sandbox:
|
||||
export function refundedBeforeOpening(code: string | undefined, onPlay: boolean): boolean {
|
||||
return onPlay && code === 'ordering-closed';
|
||||
}
|
||||
|
||||
export function isNewCloudPlan(id: string): boolean {
|
||||
return id === 'start' || id === 'plus';
|
||||
}
|
||||
|
||||
const PLAN_NAMES: Record<string, string> = { start: 'Start', basis: 'Basis', plus: 'Plus', pro: 'Pro' };
|
||||
|
||||
/** A verified purchase can predate the current offer and still need its instance set up. */
|
||||
export function planForUnclaimedPurchase(productId: string, code: string | undefined) {
|
||||
if (
|
||||
code !== 'email-invalid' &&
|
||||
code !== 'consent-deviations' &&
|
||||
code !== 'consent-outdated' &&
|
||||
!code?.startsWith('slug-')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const match = /^cloud\.(start|basis|plus|pro)\.(monthly|yearly)$/.exec(productId);
|
||||
const id = match?.[1];
|
||||
if (!id) return null;
|
||||
const name = PLAN_NAMES[id] ?? id;
|
||||
const interval = match?.[2] === 'yearly' ? 'year' : 'month';
|
||||
return { plan: { id, name }, interval } as const;
|
||||
}
|
||||
|
||||
@@ -3632,11 +3632,8 @@ describe('JourneyDetailPage', () => {
|
||||
await openEntryEditor(user);
|
||||
await user.click(screen.getByRole('button', { name: /external photos/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('journey-external-provider-immich')).toBeInTheDocument();
|
||||
});
|
||||
await user.click(screen.getByTestId('journey-external-provider-immich'));
|
||||
await waitFor(() => expect(screen.getByTestId('journey-provider-picker-embedded')).toBeInTheDocument());
|
||||
const picker = await screen.findByRole('dialog', { name: 'Immich' });
|
||||
expect(picker).toHaveClass('h-full');
|
||||
await waitFor(() => expect(screen.getByText(/This day|journey\.picker\.day/)).toBeInTheDocument());
|
||||
await waitFor(() => expect(searches.length).toBeGreaterThan(0));
|
||||
|
||||
@@ -3691,10 +3688,7 @@ describe('JourneyDetailPage', () => {
|
||||
await renderAndWait();
|
||||
await openEntryEditor(user);
|
||||
await user.click(screen.getByRole('button', { name: /external photos/i }));
|
||||
await waitFor(() => expect(screen.getByTestId('journey-external-provider-immich')).toBeInTheDocument());
|
||||
await user.click(screen.getByTestId('journey-external-provider-immich'));
|
||||
|
||||
const picker = await waitFor(() => screen.getByTestId('journey-provider-picker-embedded'));
|
||||
const picker = await screen.findByRole('dialog', { name: 'Immich' });
|
||||
await waitFor(() => expect(picker.querySelector('img[src*="/api/integrations/memories/"]')).toBeTruthy());
|
||||
const photo = picker.querySelector('img[src*="/api/integrations/memories/"]')!;
|
||||
await user.click(photo.closest('[class*="aspect-square"]') as HTMLElement);
|
||||
|
||||
@@ -26,7 +26,7 @@ import { computeJourneyLifecycle } from '../utils/journeyLifecycle'
|
||||
import { useJourneyDetail, type JourneyDetailOptions } from './journeyDetail/useJourneyDetail'
|
||||
import { createDraftJourneyEntry, pickGradient, groupByDate, formatDate, photoUrl, matchJourneyEntries } from './journeyDetail/JourneyDetailPage.helpers'
|
||||
import { EntryCard, SkeletonCard, CheckinCard } from '../components/Journey/JourneyDetailPageEntryCard'
|
||||
import { GalleryView } from '../components/Journey/JourneyDetailPageGalleryView'
|
||||
import { CreateEntriesFromPhotosButton, GalleryView } from '../components/Journey/JourneyDetailPageGalleryView'
|
||||
import { EntryEditor } from '../components/Journey/JourneyDetailPageEntryEditor'
|
||||
import { AddTripDialog } from '../components/Journey/JourneyDetailPageAddTripDialog'
|
||||
import { JourneySettingsDialog } from '../components/Journey/JourneyDetailPageSettingsDialog'
|
||||
@@ -34,6 +34,8 @@ import HelpAnchor from '../components/Help/HelpAnchor'
|
||||
import JourneyDayJump from '../components/Journey/JourneyDayJump'
|
||||
import { MemberEntryComments } from '../components/Journey/JourneyEntryComments'
|
||||
|
||||
const GALLERY_ACTION_BUTTON = 'inline-flex h-9 items-center gap-1.5 whitespace-nowrap rounded-full px-4 text-[13px] font-semibold transition-transform hover:-translate-y-0.5'
|
||||
|
||||
export default function JourneyDetailPage() {
|
||||
// ViewportRoute in App.tsx picks the branch now, so the phone screen is a
|
||||
// chunk of its own instead of a dead limb in this one.
|
||||
@@ -147,12 +149,12 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
// the gallery takes the actions over there instead. Exactly one host renders
|
||||
// them, never both.
|
||||
const galleryActions = canEditEntries && view === 'gallery' ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
{galleryProviders.map(p => (
|
||||
<button type="button"
|
||||
key={p.id}
|
||||
onClick={() => galleryBrowseRef.current?.(p.id)}
|
||||
className="inline-flex items-center gap-1.5 h-9 px-4 rounded-full text-[13px] font-semibold transition-transform hover:-translate-y-0.5"
|
||||
className={GALLERY_ACTION_BUTTON}
|
||||
style={{ background: 'var(--vg-ink)', color: 'var(--vg-bg)' }}
|
||||
>
|
||||
<Image size={16} strokeWidth={2.4} />
|
||||
@@ -162,7 +164,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
<button type="button"
|
||||
onClick={() => galleryUploadRef.current?.()}
|
||||
disabled={galleryUploadProgress !== null}
|
||||
className="inline-flex items-center gap-1.5 h-9 px-4 rounded-full text-[13px] font-semibold transition-transform hover:-translate-y-0.5 disabled:opacity-70 disabled:hover:translate-y-0"
|
||||
className={`${GALLERY_ACTION_BUTTON} disabled:opacity-70 disabled:hover:translate-y-0`}
|
||||
style={{ background: 'var(--vg-ink)', color: 'var(--vg-bg)' }}
|
||||
>
|
||||
{galleryUploadProgress ? (
|
||||
@@ -177,6 +179,14 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{!!current.gallery?.length && (
|
||||
<CreateEntriesFromPhotosButton
|
||||
journeyId={current.id}
|
||||
gallery={current.gallery}
|
||||
onCreated={() => { void loadJourney(Number(id)) }}
|
||||
className={GALLERY_ACTION_BUTTON}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : null
|
||||
|
||||
@@ -456,7 +466,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
placeholder={t('journey.detail.searchPlaceholder')}
|
||||
className="min-w-0 flex-1 bg-transparent text-[12.5px] outline-none"
|
||||
className="min-w-0 flex-1 !bg-transparent text-[12.5px] outline-none"
|
||||
style={{ color: 'var(--vg-ink)' }}
|
||||
/>
|
||||
{query && (
|
||||
|
||||
@@ -353,8 +353,7 @@ function CreateJourneyDialog({ title, onTitleChange, subtitle, onSubtitleChange,
|
||||
)
|
||||
|
||||
return (
|
||||
// Pinned at the top: the trips arrive after the dialog opens and grow the body.
|
||||
<DialogShell onClose={onClose} labelledBy={labelId} width="detail" align="top" header={header} footer={footer}>
|
||||
<DialogShell onClose={onClose} labelledBy={labelId} width="detail" header={header} footer={footer}>
|
||||
<EditorField label={t('journey.settings.subtitle')} htmlFor={`${labelId}-subtitle`}>
|
||||
<input
|
||||
id={`${labelId}-subtitle`}
|
||||
|
||||
@@ -363,13 +363,18 @@ describe('assistantStore: threads, window and status', () => {
|
||||
expect(store().status).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-AI-STORE-014: a managed install, which refuses /api/ai, is not asked whatever its addons say', async () => {
|
||||
it('FE-AI-STORE-014: a managed install only asks for status when its assistant addon is on', async () => {
|
||||
const status = vi.spyOn(aiConnectionsRepo, 'status').mockResolvedValue(STATUS);
|
||||
useAssistantStore.setState({ status: STATUS });
|
||||
useAuthStore.setState({ managed: true });
|
||||
addonsOn('ai_assistant', 'llm_parsing');
|
||||
addonsOn('llm_parsing');
|
||||
await store().loadStatus();
|
||||
expect(status).not.toHaveBeenCalled();
|
||||
expect(store().status).toBeNull();
|
||||
|
||||
addonsOn('ai_assistant', 'llm_parsing');
|
||||
await store().loadStatus();
|
||||
expect(status).toHaveBeenCalledOnce();
|
||||
expect(store().status).toEqual(STATUS);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -124,7 +124,7 @@ interface UndoBlockResult {
|
||||
interface AssistantState {
|
||||
/**
|
||||
* What the assistant runs on for this user; null until loaded, while no addon
|
||||
* opens /api/ai (aiRoutesOpen) and on a managed install, and the assistant stays hidden then.
|
||||
* opens /api/ai (aiRoutesOpen). Otherwise the assistant stays hidden.
|
||||
*/
|
||||
status: AiStatusResponse | null;
|
||||
window: { open: boolean; minimized: boolean };
|
||||
@@ -325,13 +325,13 @@ export function chatOf(state: Pick<AssistantState, 'byTrip'>, key: AssistantChat
|
||||
* Whether the addons open /api/ai: the server opens it while the assistant or
|
||||
* AI parsing is on, the two sharing one connection, and answers 404 while
|
||||
* both are off. Closed until the addon list is in. A selector on the addon
|
||||
* store; a managed install refuses /api/ai whatever it says (loadStatus).
|
||||
* store. On managed installs only the assistant addon opens the status route.
|
||||
*/
|
||||
export function aiRoutesOpen({
|
||||
loaded,
|
||||
isEnabled,
|
||||
}: Pick<ReturnType<typeof useAddonStore.getState>, 'loaded' | 'isEnabled'>): boolean {
|
||||
return loaded && (isEnabled('ai_assistant') || isEnabled('llm_parsing'));
|
||||
export function aiRoutesOpen(
|
||||
{ loaded, isEnabled }: Pick<ReturnType<typeof useAddonStore.getState>, 'loaded' | 'isEnabled'>,
|
||||
managed: boolean
|
||||
): boolean {
|
||||
return loaded && (isEnabled('ai_assistant') || (!managed && isEnabled('llm_parsing')));
|
||||
}
|
||||
|
||||
function httpStatus(err: unknown): number | undefined {
|
||||
@@ -586,9 +586,7 @@ function backToAfter(byTrip: Record<number, AssistantTripChat>): Record<number,
|
||||
function shellActions(ctx: Ctx) {
|
||||
return {
|
||||
loadStatus: async () => {
|
||||
// While /api/ai is closed the request could only get a 404, or the 403 of a managed install: nothing is asked,
|
||||
// and the assistant stays hidden. The managed flag comes with the app config, which can land after the addons.
|
||||
if (useAuthStore.getState().managed || !aiRoutesOpen(useAddonStore.getState())) {
|
||||
if (!aiRoutesOpen(useAddonStore.getState(), useAuthStore.getState().managed)) {
|
||||
ctx.set({ status: null });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -321,7 +321,7 @@ describe('MNewTripSheet', () => {
|
||||
|
||||
it('FE-MOB-NTSH-017: create mode previews the picked Unsplash photo without a request', async () => {
|
||||
vi.spyOn(tripsApi, 'searchCoverImages').mockResolvedValue({
|
||||
photos: [{ id: 'p1', url: 'https://img/full.jpg', thumb: 'https://img/thumb.jpg', photographer: 'Ada' }],
|
||||
photos: [{ id: 'p1', url: 'https://img/full.jpg', thumb: 'https://img/thumb.jpg', description: 'Icelandic waterfall', photographer: 'Ada' }],
|
||||
});
|
||||
const update = vi.spyOn(tripsApi, 'update');
|
||||
render(<MNewTripSheet open trip={null} onClose={() => {}} onSave={() => {}} />);
|
||||
@@ -330,6 +330,7 @@ describe('MNewTripSheet', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Search Unsplash' }));
|
||||
|
||||
const pick = await screen.findByRole('button', { name: 'Use Unsplash photo by Ada' });
|
||||
expect(screen.getByAltText('Icelandic waterfall')).toHaveAttribute('title', 'Icelandic waterfall');
|
||||
expect(screen.getByText('Ada')).toBeInTheDocument();
|
||||
fireEvent.click(pick);
|
||||
|
||||
@@ -355,7 +356,10 @@ describe('MNewTripSheet', () => {
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText('e.g. Summer in Japan'), { target: { value: 'Iceland' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Search Unsplash' }));
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Use Unsplash photo by Unsplash' }));
|
||||
const pick = await screen.findByRole('button', { name: 'Use Unsplash photo by Unsplash' });
|
||||
expect(pick.querySelector('img')).toHaveAttribute('alt', '');
|
||||
expect(pick.querySelector('img')).not.toHaveAttribute('title');
|
||||
fireEvent.click(pick);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create New Trip' }));
|
||||
|
||||
await waitFor(() => expect(update).toHaveBeenCalledWith(77, { cover_image: 'https://img/full.jpg' }));
|
||||
|
||||
@@ -1269,17 +1269,26 @@ describe('MJourneyEntrySheet external photos', () => {
|
||||
expect(probes).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-MOB-JENTRY-042: opens the embedded picker for a connected provider', async () => {
|
||||
it('FE-MOB-JENTRY-042: opens a full-screen photo picker for a connected provider', async () => {
|
||||
useConnectedImmich();
|
||||
const user = userEvent.setup();
|
||||
mountSheet(buildEntry({ id: 5, location_lat: 41.9, location_lng: 12.5, location_name: 'Rome' }), { photoProviders: immich });
|
||||
await user.type(screen.getByPlaceholderText('Give this moment a name...'), 'Draft title');
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'External photos' }));
|
||||
|
||||
expect(await screen.findByTestId('journey-provider-picker-embedded')).toBeInTheDocument();
|
||||
expect(screen.getByText('Nearby photos first · Rome')).toBeInTheDocument();
|
||||
const picker = await screen.findByRole('dialog', { name: 'Immich' });
|
||||
expect(picker).toHaveClass('h-full');
|
||||
expect(screen.getAllByRole('button', { name: 'Cancel' })).toHaveLength(1);
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument();
|
||||
expect(picker).toHaveTextContent('Nearby photos first Rome');
|
||||
// A single provider needs no chip row.
|
||||
expect(screen.queryByTestId('journey-external-provider-immich')).not.toBeInTheDocument();
|
||||
|
||||
await user.keyboard('{Escape}');
|
||||
expect(screen.queryByRole('dialog', { name: 'Immich' })).not.toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('Draft title')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeVisible();
|
||||
});
|
||||
|
||||
it('FE-MOB-JENTRY-043: stays out of the quick capture sheet', async () => {
|
||||
@@ -1300,7 +1309,7 @@ describe('MJourneyEntrySheet external photos', () => {
|
||||
await user.click(await screen.findByAltText(''));
|
||||
await user.click(screen.getByRole('button', { name: 'Add (1)' }));
|
||||
|
||||
const queued = await screen.findByRole('button', { name: /1 queued · Clear/ });
|
||||
const queued = await screen.findByRole('button', { name: /1 queued Clear/ });
|
||||
expect(queued).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
@@ -1321,7 +1330,7 @@ describe('MJourneyEntrySheet external photos', () => {
|
||||
await user.click(await screen.findByRole('button', { name: 'External photos' }));
|
||||
await user.click(await screen.findByAltText(''));
|
||||
await user.click(screen.getByRole('button', { name: 'Add (1)' }));
|
||||
await user.click(await screen.findByRole('button', { name: /1 queued · Clear/ }));
|
||||
await user.click(await screen.findByRole('button', { name: /1 queued Clear/ }));
|
||||
|
||||
expect(screen.queryByRole('button', { name: /queued/ })).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
@@ -293,7 +293,7 @@ function carrier(role: CarrierTerminal['role'], over: Partial<CarrierTerminal> =
|
||||
role,
|
||||
title: car ? 'Sixt Hamburg' : 'LH 2020',
|
||||
code: role === 'departure' ? 'HAM' : role === 'arrival' ? 'MUC' : null,
|
||||
at: { departure: '13:20', arrival: '14:30', pickup: '09:00', return: '11:30' }[role],
|
||||
at: { departure: '13:20', arrival: '14:30', pickup: '09:00', return: '11:30', stop: null }[role],
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,14 @@ describe('the document', () => {
|
||||
expect(frame().srcdoc).toContain('@page { size: 224mm 303mm; margin: 0; }')
|
||||
})
|
||||
|
||||
it('lets clipped spreads paginate at their fixed sheet size (#3275)', () => {
|
||||
open()
|
||||
const html = frame().srcdoc
|
||||
const printBlock = html.slice(html.lastIndexOf('@media print'))
|
||||
expect(printBlock).toMatch(/html, body\s*\{[^}]*height: auto;[^}]*overflow: visible;/)
|
||||
expect(printBlock).toMatch(/\.bx-sheet\s*\{[^}]*contain: strict;/)
|
||||
})
|
||||
|
||||
/*
|
||||
* Hyphenation is off in every browser until the language is known, so a
|
||||
* heading the editor had broken as "Lorem ip-sum" printed unbroken, ran past
|
||||
|
||||
Generated
+601
-332
File diff suppressed because it is too large
Load Diff
+9
-9
@@ -66,14 +66,14 @@
|
||||
"dependencies": {
|
||||
"@aws-lite/client": "^0.24.1",
|
||||
"@aws-lite/s3": "^0.2.7",
|
||||
"@mikro-orm/cli": "^7.2.13",
|
||||
"@mikro-orm/core": "^7.2.13",
|
||||
"@mikro-orm/migrations": "^7.2.13",
|
||||
"@mikro-orm/cli": "^7.2.12",
|
||||
"@mikro-orm/core": "^7.2.12",
|
||||
"@mikro-orm/migrations": "^7.2.12",
|
||||
"@mikro-orm/nestjs": "^7.1.0",
|
||||
"@mikro-orm/postgresql": "^7.2.13",
|
||||
"@mikro-orm/seeder": "^7.2.13",
|
||||
"@mikro-orm/postgresql": "^7.2.12",
|
||||
"@mikro-orm/seeder": "^7.2.12",
|
||||
"@mikro-orm/sql": "^7.2.12",
|
||||
"@mikro-orm/sqlite": "^7.2.13",
|
||||
"@mikro-orm/sqlite": "^7.2.12",
|
||||
"@modelcontextprotocol/sdk": "^1.32.2",
|
||||
"@nestjs/common": "^11.2.12",
|
||||
"@nestjs/config": "^4.0.4",
|
||||
@@ -120,13 +120,13 @@
|
||||
"undici": "^7.30.1",
|
||||
"unzipper": "^0.12.5",
|
||||
"uuid": "^14.0.3",
|
||||
"ws": "^8.23.1",
|
||||
"ws": "^8.23.0",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@aws-lite/s3-types": "^0.2.8",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@mikro-orm/entity-generator": "^7.2.13",
|
||||
"@mikro-orm/entity-generator": "^7.2.12",
|
||||
"@nestjs/testing": "^11.2.12",
|
||||
"@swc/core": "^1.16.22",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.3",
|
||||
@@ -149,7 +149,7 @@
|
||||
"@vitest/coverage-istanbul": "^5.1.2",
|
||||
"eslint": "^9.39.5",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
"eslint-config-prettier": "^10.1.9",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"polylabel": "^2.0.1",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
|
||||
@@ -165,7 +165,7 @@ below.)
|
||||
|
||||
**Runtime-toggled** (read live on every access via `readEnv()` /
|
||||
`RuntimeEnvService`; tests mutate these mid-lifetime):
|
||||
TREK_MANAGED, PLACES_API_BASE, PLACES_API_KEY, AMAP_API_BASE, AMAP_API_KEY, AMAP_API_SECRET, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
|
||||
TREK_MANAGED, TREK_MANAGED_ASSISTANT_URL, TREK_MANAGED_ASSISTANT_TOKEN, TREK_MANAGED_ASSISTANT_MODEL, PLACES_API_BASE, PLACES_API_KEY, AMAP_API_BASE, AMAP_API_KEY, AMAP_API_SECRET, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_MODE, NODE_ENV, APP_VERSION, APP_URL, TREK_API_DOCS_ENABLED,
|
||||
TREK_PLUGINS_ENABLED / _DEV_LINK / _IGNORE_TREK_RANGE / _DIR / _DATA_DIR / TREK_PLUGIN_PERMISSIONS,
|
||||
OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE,
|
||||
ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL,
|
||||
|
||||
@@ -122,17 +122,18 @@ function flagText(raw: string | undefined): 'true' | 'false' | undefined {
|
||||
* Whether this instance is centrally administered: somebody other than its
|
||||
* admin user owns the configuration, the credentials and the upgrade schedule.
|
||||
*
|
||||
* Only a boolean, on purpose. It answers "who configures this install", and the
|
||||
* surfaces that care read it themselves rather than being listed here, so adding
|
||||
* one never touches this file.
|
||||
*
|
||||
* `=== true` so an unset, empty or unparseable value means off. A managed
|
||||
* install sets it deliberately; nothing should be able to switch it on by
|
||||
* accident, and a typo must not silently take settings away from an admin.
|
||||
*/
|
||||
export function deriveManaged(raw: RawEnv) {
|
||||
const enabled = parseBool(raw.TREK_MANAGED) === true;
|
||||
const baseUrl = raw.TREK_MANAGED_ASSISTANT_URL?.trim();
|
||||
const token = raw.TREK_MANAGED_ASSISTANT_TOKEN?.trim();
|
||||
const model = raw.TREK_MANAGED_ASSISTANT_MODEL?.trim();
|
||||
return {
|
||||
enabled: parseBool(raw.TREK_MANAGED) === true,
|
||||
enabled,
|
||||
assistant: enabled && baseUrl && token && model ? { baseUrl, token, model } : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -213,6 +213,9 @@ export const envSchema = z.object({
|
||||
ADMIN_EMAIL: anyString,
|
||||
ADMIN_PASSWORD: anyString,
|
||||
TREK_MANAGED: boolStr,
|
||||
TREK_MANAGED_ASSISTANT_URL: url,
|
||||
TREK_MANAGED_ASSISTANT_TOKEN: anyString,
|
||||
TREK_MANAGED_ASSISTANT_MODEL: anyString,
|
||||
PLACES_API_BASE: url,
|
||||
GOOGLE_LIST_DATA_BASE: url,
|
||||
TREK_PLACES_URL: url,
|
||||
|
||||
@@ -28,6 +28,8 @@ export const SECRET_ENV_KEYS: ReadonlySet<string> = new Set([
|
||||
'ADMIN_PASSWORD',
|
||||
'PLACES_API_KEY',
|
||||
'TREK_SERVICES_KEY',
|
||||
'TREK_MANAGED_ASSISTANT_URL',
|
||||
'TREK_MANAGED_ASSISTANT_TOKEN',
|
||||
'AMAP_API_KEY',
|
||||
'AMAP_API_SECRET',
|
||||
'MAPBOX_ACCESS_TOKEN',
|
||||
@@ -153,5 +155,30 @@ function managedPreconditions(raw: RawEnv): string[] {
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
TREK_MANAGED_ASSISTANT_URL: baseUrl,
|
||||
TREK_MANAGED_ASSISTANT_MODEL: model,
|
||||
TREK_MANAGED_ASSISTANT_TOKEN: token,
|
||||
} = raw;
|
||||
if (baseUrl || model || token) {
|
||||
if (!baseUrl || !model?.trim() || !token?.trim()) {
|
||||
problems.push(' - The managed assistant URL, model and token must be configured together.');
|
||||
} else {
|
||||
const endpoint = URL.canParse(baseUrl) ? new URL(baseUrl) : null;
|
||||
if (
|
||||
!endpoint ||
|
||||
endpoint.protocol !== 'https:' ||
|
||||
endpoint.username ||
|
||||
endpoint.password ||
|
||||
endpoint.search ||
|
||||
endpoint.hash
|
||||
) {
|
||||
problems.push(
|
||||
' - TREK_MANAGED_ASSISTANT_URL must be an HTTPS URL without credentials, a query or a fragment.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ export class TripPhotosRepository extends TrekRepository<TripPhotos> {
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** UM8 (`UnifiedMemoriesService.removeAlbumLink`'s pre-tx orphan-candidate list) — `SELECT photo_id FROM trip_photos WHERE trip_id = ? AND album_link_id = ?`. */
|
||||
/** UM8 (`UnifiedMemoriesService.removeAlbumLink`, inside its transaction). */
|
||||
async listPhotoIdsForAlbumLink(trip_id: number | string, album_link_id: number | string): Promise<number[]> {
|
||||
const rows = await this.kysely<TripPhotosKyselyDB>()
|
||||
.selectFrom('trip_photos')
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Injectable } from '@nestjs/common';
|
||||
* is the adapter's.
|
||||
*/
|
||||
const cloudFetch: AiFetch = (url, init) => safeFetch(url, { ...init, signal: init.signal }, { maxBytes: null });
|
||||
const hostedFetch: AiFetch = (url, init) => cloudFetch(url, { ...init, redirect: 'error' });
|
||||
|
||||
/**
|
||||
* An admin's own server, which may sit on loopback or in the LAN: the guard
|
||||
@@ -46,6 +47,15 @@ export class AiChatClientService {
|
||||
create(connection: ResolvedAiConnection): AiChatClient {
|
||||
const { credential, kind, model } = connection;
|
||||
if (credential.type === 'chatgpt') return this.chatgptPlan(connection.id, model, credential.accessToken);
|
||||
if (connection.managed) {
|
||||
return new OpenAiChatClient(
|
||||
'openrouter',
|
||||
model,
|
||||
ownServerChatBase(connection.baseUrl),
|
||||
credential.apiKey,
|
||||
hostedFetch,
|
||||
);
|
||||
}
|
||||
if (kind === 'openai' && openAiWantsResponses(model)) {
|
||||
const apiKey = credential.apiKey ?? '';
|
||||
return new OpenAiResponsesClient(model, () => Promise.resolve(apiKey), cloudFetch, 'openai');
|
||||
|
||||
@@ -46,6 +46,7 @@ export class AiConnectionsController {
|
||||
) {}
|
||||
|
||||
@Get('status')
|
||||
@ManagedForbidden('managed status describes the operator gateway', { allowHostedAssistant: true })
|
||||
@ResponseContract(aiStatusResponseSchema)
|
||||
status(@CurrentUser() user: User) {
|
||||
return this.connections.status(user.id);
|
||||
@@ -78,6 +79,9 @@ export class AiConnectionsController {
|
||||
}
|
||||
|
||||
@Post('privacy-ack')
|
||||
@ManagedForbidden('the hosted assistant requires each user to acknowledge the provider', {
|
||||
allowHostedAssistant: true,
|
||||
})
|
||||
@HttpCode(200)
|
||||
@ResponseContract(successResponseSchema)
|
||||
async ackPrivacy(@CurrentUser() user: User, @Body() body: AiPrivacyAckDto) {
|
||||
|
||||
@@ -48,6 +48,27 @@ import {
|
||||
/** A key test asks the provider for its models: a few a minute per user, so the server is no oracle for keys. */
|
||||
const MODEL_CALLS_PER_MINUTE = 5;
|
||||
|
||||
function hostedConnection(): ResolvedAiConnection | null {
|
||||
const config = readEnv().managed.assistant;
|
||||
if (!config) return null;
|
||||
return {
|
||||
id: 0,
|
||||
managed: true,
|
||||
scope: 'instance',
|
||||
kind: 'openrouter',
|
||||
model: config.model,
|
||||
baseUrl: config.baseUrl,
|
||||
host: aiHostOf('openrouter', null),
|
||||
paidBy: 'instance',
|
||||
status: 'ok',
|
||||
credential: { type: 'api_key', apiKey: config.token },
|
||||
};
|
||||
}
|
||||
|
||||
function privacyTarget(connection: Pick<ResolvedAiConnection, 'kind' | 'host' | 'managed'>): string {
|
||||
return `${connection.kind}@${connection.host}${connection.managed ? ':managed' : ''}`;
|
||||
}
|
||||
|
||||
function kindOf(row: AiConnectionRow): AiConnectionKind {
|
||||
return row.kind as AiConnectionKind;
|
||||
}
|
||||
@@ -94,13 +115,35 @@ export class AiConnectionsService implements SharedAiConnectionPort {
|
||||
/** `kind:model` of the models a provider refused an image for, while this process runs. */
|
||||
private readonly textOnly = new Set<string>();
|
||||
|
||||
/** Whether the assistant exists here at all: the addon is on and the install is not centrally administered. */
|
||||
/** The addon must be on. Managed installs additionally require the operator gateway. */
|
||||
async enabled(): Promise<boolean> {
|
||||
return !readEnv().managed.enabled && (await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT));
|
||||
const managed = readEnv().managed;
|
||||
return (!managed.enabled || !!managed.assistant) && (await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT));
|
||||
}
|
||||
|
||||
async status(userId: number): Promise<AiStatusResponse> {
|
||||
const settings = await this.aiSettings.read();
|
||||
const hosted = hostedConnection();
|
||||
if (hosted) {
|
||||
const available = await this.enabled();
|
||||
const target = privacyTarget(hosted);
|
||||
const instance = { kind: hosted.kind, model: hosted.model, host: hosted.host };
|
||||
return {
|
||||
available,
|
||||
policy: 'instance',
|
||||
canConnectOwn: false,
|
||||
effective: available ? { ...instance, source: 'instance', paidBy: 'instance' } : null,
|
||||
own: null,
|
||||
instance: available ? instance : null,
|
||||
quota: null,
|
||||
privacyAcked:
|
||||
available && (await this.settings.getDecryptedUserSetting(userId, AI_PRIVACY_ACK_SETTING)) === target,
|
||||
studioImages: available && this.readsImages(hosted),
|
||||
studioImagesAcked: available && (await this.studioImagesAckedFor(userId, target)),
|
||||
retention: settings.retention,
|
||||
openrouterOAuth: false,
|
||||
};
|
||||
}
|
||||
const own = await this.connections.findForUser(userId);
|
||||
const instance = await this.connections.findInstance();
|
||||
const picked = (await this.enabled()) ? pickConnection(settings.policy, own, instance) : null;
|
||||
@@ -148,6 +191,14 @@ export class AiConnectionsService implements SharedAiConnectionPort {
|
||||
*/
|
||||
async resolveForUser(userId: number): Promise<ResolvedAiConnection> {
|
||||
if (!(await this.enabled())) throw aiRefusal('not_connected', 'The AI assistant is not available');
|
||||
const hosted = hostedConnection();
|
||||
if (hosted) {
|
||||
const target = privacyTarget(hosted);
|
||||
if ((await this.settings.getDecryptedUserSetting(userId, AI_PRIVACY_ACK_SETTING)) !== target) {
|
||||
throw aiRefusal('forbidden', 'Acknowledge the AI Assistant privacy notice first');
|
||||
}
|
||||
return hosted;
|
||||
}
|
||||
const { policy } = await this.aiSettings.read();
|
||||
const picked = pickConnection(
|
||||
policy,
|
||||
@@ -177,6 +228,7 @@ export class AiConnectionsService implements SharedAiConnectionPort {
|
||||
* clears an earlier mark.
|
||||
*/
|
||||
async noteOutcome(connection: ResolvedAiConnection, code: AssistantErrorCode | null): Promise<void> {
|
||||
if (connection.managed) return;
|
||||
if (code === 'invalid_key' && connection.status !== 'error') {
|
||||
await this.connections.setStatus(connection.id, 'error');
|
||||
} else if (code === 'needs_reauth' && connection.kind === 'chatgpt') {
|
||||
@@ -241,12 +293,19 @@ export class AiConnectionsService implements SharedAiConnectionPort {
|
||||
*/
|
||||
async ackPrivacy(userId: number, req: AiPrivacyAckRequest): Promise<void> {
|
||||
const key = req.scope === 'studio_images' ? AI_STUDIO_IMAGES_ACK_SETTING : AI_PRIVACY_ACK_SETTING;
|
||||
await this.settings.upsertSetting(userId, key, `${req.kind}@${req.host}`);
|
||||
const hosted = hostedConnection();
|
||||
if (hosted && (req.kind !== hosted.kind || req.host !== hosted.host)) {
|
||||
throw aiRefusal('forbidden', 'This is not the configured AI Assistant provider');
|
||||
}
|
||||
await this.settings.upsertSetting(userId, key, privacyTarget(hosted ?? req));
|
||||
}
|
||||
|
||||
/** Whether the user let this connection receive images of their Studio pages; without it a turn stays text. */
|
||||
async studioImagesAcked(userId: number, connection: Pick<ResolvedAiConnection, 'kind' | 'host'>): Promise<boolean> {
|
||||
return this.studioImagesAckedFor(userId, `${connection.kind}@${connection.host}`);
|
||||
async studioImagesAcked(
|
||||
userId: number,
|
||||
connection: Pick<ResolvedAiConnection, 'kind' | 'host' | 'managed'>,
|
||||
): Promise<boolean> {
|
||||
return this.studioImagesAckedFor(userId, privacyTarget(connection));
|
||||
}
|
||||
|
||||
private async studioImagesAckedFor(userId: number, target: string): Promise<boolean> {
|
||||
@@ -259,8 +318,9 @@ export class AiConnectionsService implements SharedAiConnectionPort {
|
||||
* runs. Status asks this too, so the Studio offers images only where a turn
|
||||
* would send them.
|
||||
*/
|
||||
readsImages({ kind, model }: Pick<ResolvedAiConnection, 'kind' | 'model'>): boolean {
|
||||
return modelReadsImages(kind, model) && !this.textOnly.has(`${kind}:${model}`);
|
||||
readsImages({ kind, model, managed }: Pick<ResolvedAiConnection, 'kind' | 'model' | 'managed'>): boolean {
|
||||
const supported = modelReadsImages(kind, model) || (managed === true && model === 'qwen/qwen3.7-flash');
|
||||
return supported && !this.textOnly.has(`${kind}:${model}`);
|
||||
}
|
||||
|
||||
/** A provider refused an image for this model: it reads pages in words until the process restarts. */
|
||||
|
||||
@@ -10,6 +10,8 @@ export type AiCredential = { type: 'api_key'; apiKey: string | null } | { type:
|
||||
*/
|
||||
export interface ResolvedAiConnection {
|
||||
id: number;
|
||||
/** Operator gateway configuration has no database connection row or tenant daily quota. */
|
||||
managed?: true;
|
||||
scope: AiConnectionScope;
|
||||
kind: AiConnectionKind;
|
||||
model: string;
|
||||
|
||||
@@ -5,7 +5,7 @@ import { aiRefusal } from '../ai-connections/ai-connections.constants';
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { isManagedBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
|
||||
import { isManagedAssistantBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { MAX_ATTACHMENT_BYTES } from './assistant-tools.constants';
|
||||
import { channelOf } from './assistant.controller';
|
||||
@@ -90,7 +90,7 @@ export class AssistantAttachmentsController {
|
||||
if (!(await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT))) {
|
||||
throw new HttpException({ error: 'AI assistant addon is not enabled' }, 404);
|
||||
}
|
||||
if (isManagedBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
|
||||
if (isManagedAssistantBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
|
||||
if (!(await this.trips.findAccessible(tripId, user.id))) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { readImageHeader } from '../common/image-header';
|
||||
import { isManagedBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
|
||||
import { isManagedAssistantBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { toRowId } from '../common/row-id';
|
||||
import { JourneyAiPhotosService } from '../journey/journey-ai-photos.service';
|
||||
@@ -90,7 +90,7 @@ export class AssistantRendersController {
|
||||
if (!(await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT))) {
|
||||
throw new HttpException({ error: 'AI assistant addon is not enabled' }, 404);
|
||||
}
|
||||
if (isManagedBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
|
||||
if (isManagedAssistantBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
|
||||
if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) {
|
||||
throw new HttpException({ error: 'Journey addon is not enabled' }, 404);
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ export function channelOf(res: Response): TurnChannel {
|
||||
@Controller('api/trips/:tripId/assistant')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
|
||||
@RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant')
|
||||
@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it')
|
||||
@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true })
|
||||
export class AssistantController {
|
||||
constructor(
|
||||
private readonly assistant: AssistantService,
|
||||
|
||||
@@ -249,7 +249,7 @@ export class AssistantService {
|
||||
if (begun.created) w.thread(begun.threadId, begun.title);
|
||||
await this.usage.record(userId, connection.paidBy, { turns: 1 });
|
||||
const quota =
|
||||
connection.paidBy === 'instance'
|
||||
connection.paidBy === 'instance' && dailyTurns !== null
|
||||
? { used: await this.usage.instanceTurnsToday(userId), limit: dailyTurns }
|
||||
: null;
|
||||
const spec: TurnSpec = {
|
||||
@@ -372,7 +372,7 @@ export class AssistantService {
|
||||
const w = new UiStreamWriter(stream);
|
||||
w.start(messageIdOf(await this.answerStart(threadId, decided[0].call.message_id)));
|
||||
const quota =
|
||||
connection.paidBy === 'instance'
|
||||
connection.paidBy === 'instance' && dailyTurns !== null
|
||||
? { used: await this.usage.instanceTurnsToday(userId), limit: dailyTurns }
|
||||
: null;
|
||||
const spec: TurnSpec = {
|
||||
@@ -530,7 +530,8 @@ export class AssistantService {
|
||||
* day reached the admin's limit; answers that limit. A decision counts no
|
||||
* turn of its own, but runs the model again, so it is held to the limit too.
|
||||
*/
|
||||
private async withinDailyLimit(userId: number, connection: ResolvedAiConnection): Promise<number> {
|
||||
private async withinDailyLimit(userId: number, connection: ResolvedAiConnection): Promise<number | null> {
|
||||
if (connection.managed) return null;
|
||||
const { dailyTurns } = await this.connections.readSettings();
|
||||
if (connection.paidBy === 'instance' && (await this.usage.instanceTurnsToday(userId)) >= dailyTurns) {
|
||||
throw aiRefusal('daily_limit', 'The daily limit of the assistant is reached');
|
||||
|
||||
@@ -36,7 +36,7 @@ import type { Response } from 'express';
|
||||
@Controller('api/assistant')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant')
|
||||
@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it')
|
||||
@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true })
|
||||
export class HomeAssistantController {
|
||||
constructor(private readonly assistant: AssistantService) {}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ function journeyScope(journeyId: string, surface?: AssistantJourneySurface): Ass
|
||||
@Controller('api/journeys/:journeyId/assistant')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard, JourneyAssistantGuard)
|
||||
@RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant')
|
||||
@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it')
|
||||
@ManagedForbidden('managed assistant requests use the operator gateway', { allowHostedAssistant: true })
|
||||
export class JourneyAssistantController {
|
||||
constructor(private readonly assistant: AssistantService) {}
|
||||
|
||||
|
||||
@@ -427,11 +427,11 @@ export class AuthService {
|
||||
if (validInvite.expires_at && new Date(validInvite.expires_at) < new Date()) throw new DomainError(410, 'Invite link has expired');
|
||||
}
|
||||
|
||||
if (userCount > 0 && !validInvite) {
|
||||
const toggles = await this.resolveAuthToggles();
|
||||
if (!toggles.password_registration) {
|
||||
throw new DomainError(403, 'Password registration is disabled. Contact your administrator.');
|
||||
}
|
||||
const toggles = await this.resolveAuthToggles();
|
||||
// Setup and invitations still use the password sign-in policy.
|
||||
const canUseClosedRegistration = toggles.password_login && (userCount === 0 || validInvite !== null);
|
||||
if (!toggles.password_registration && !canUseClosedRegistration) {
|
||||
throw new DomainError(403, 'Password registration is disabled. Contact your administrator.');
|
||||
}
|
||||
|
||||
if (!username || !email || !password) {
|
||||
|
||||
@@ -12,7 +12,12 @@ import { UnitOfWork } from '../database/unit-of-work';
|
||||
import type { SessionClient } from '../sessions/sessions.service';
|
||||
import { stripUserForClient } from './auth.helpers';
|
||||
import { AuthService } from './auth.service';
|
||||
import { WebauthnConfigService, originWithinRpScope, type WebauthnConfig } from './webauthn-config.service';
|
||||
import {
|
||||
WebauthnConfigService,
|
||||
originWithinRpScope,
|
||||
passkeyVerificationOrigins,
|
||||
type WebauthnConfig,
|
||||
} from './webauthn-config.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import {
|
||||
@@ -182,31 +187,6 @@ export class PasskeyService {
|
||||
// Origin handling (#2147)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The origins handed to the verifier for this ceremony. An explicit operator
|
||||
* list is honored verbatim. A derived config (APP_URL fallback) often carries
|
||||
* the wrong scheme or port (TLS-terminating proxy, first ALLOWED_ORIGINS
|
||||
* entry), so the browser-asserted origin is added when it is the RP ID's own
|
||||
* host and only the scheme or port drifted.
|
||||
*
|
||||
* The HOST is never widened, even though the browser's rule would run a
|
||||
* ceremony from any subdomain of the RP ID: on an apex RP ID that exact-origin
|
||||
* list is the only thing between a taken-over sibling subdomain and an
|
||||
* assertion this server would accept, and the browser cannot supply it. A
|
||||
* deployment that really spans several hosts under one RP ID lists them in
|
||||
* webauthn_origins / WEBAUTHN_ORIGINS, which is honored verbatim above.
|
||||
*/
|
||||
private expectedOrigins(cfg: WebauthnConfig, resp: unknown): string[] {
|
||||
if (cfg.explicitOrigins) return cfg.origins;
|
||||
const clientOrigin = originFromResponse(resp);
|
||||
if (!clientOrigin || cfg.origins.includes(clientOrigin) || !originWithinRpScope(clientOrigin, cfg.rpID)) {
|
||||
return cfg.origins;
|
||||
}
|
||||
// Parsing cannot throw here: originWithinRpScope only says yes on a URL it parsed.
|
||||
if (new URL(clientOrigin).hostname !== cfg.rpID) return cfg.origins;
|
||||
return [...cfg.origins, clientOrigin];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-ceremony check of the request's Origin header against the resolved RP
|
||||
* config. A browser on an origin the derived localhost fallback can never
|
||||
@@ -298,7 +278,7 @@ export class PasskeyService {
|
||||
throw new DomainError(400, 'Registration challenge expired. Please try again.');
|
||||
}
|
||||
|
||||
const expectedOrigin = this.expectedOrigins(cfg, resp);
|
||||
const expectedOrigin = passkeyVerificationOrigins(cfg, originFromResponse(resp));
|
||||
let verification;
|
||||
try {
|
||||
verification = await verifyRegistrationResponse({
|
||||
@@ -413,7 +393,7 @@ export class PasskeyService {
|
||||
const cred = await this.webauthnCredentials.findByCredentialId(credId);
|
||||
if (!cred) return { ...AUTH_FAILED };
|
||||
|
||||
const expectedOrigin = this.expectedOrigins(cfg, resp);
|
||||
const expectedOrigin = passkeyVerificationOrigins(cfg, originFromResponse(resp));
|
||||
let verification;
|
||||
try {
|
||||
verification = await verifyAuthenticationResponse({
|
||||
|
||||
@@ -63,13 +63,31 @@ export interface WebauthnConfig {
|
||||
origins: string[];
|
||||
/**
|
||||
* True when `origins` came from operator config (env / admin setting) — such
|
||||
* a list is honored verbatim. False when derived from APP_URL, where the
|
||||
* scheme/port may not match the real browsing origin (TLS-terminating proxy)
|
||||
* and the verifier may widen within the RP ID's scope.
|
||||
* a list is honored verbatim. Derived origins allow the verifier to account
|
||||
* for proxy scheme or port differences on a configured host.
|
||||
*/
|
||||
explicitOrigins: boolean;
|
||||
}
|
||||
|
||||
/** Origins accepted for a registration or sign-in assertion. */
|
||||
export function passkeyVerificationOrigins(config: WebauthnConfig, clientOrigin: string | null): string[] {
|
||||
if (
|
||||
config.explicitOrigins ||
|
||||
!clientOrigin ||
|
||||
config.origins.includes(clientOrigin) ||
|
||||
!originWithinRpScope(clientOrigin, config.rpID)
|
||||
) {
|
||||
return config.origins;
|
||||
}
|
||||
|
||||
// Keep the proxy fallback on the RP host only when a derived origin already uses that host.
|
||||
const clientHost = hostOf(clientOrigin);
|
||||
if (clientHost !== config.rpID || !config.origins.some((origin) => hostOf(origin) === clientHost)) {
|
||||
return config.origins;
|
||||
}
|
||||
return [...config.origins, clientOrigin];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the WebAuthn Relying Party ID + allowed origins for this deployment.
|
||||
*
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { MANAGED_FORBIDDEN, MANAGED_FORBIDDEN_ERROR } from './managed';
|
||||
import { isManagedAssistantBlocked, MANAGED_FORBIDDEN, MANAGED_FORBIDDEN_ERROR } from './managed';
|
||||
import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
|
||||
@@ -31,10 +31,9 @@ export class ManagedGuard implements CanActivate {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
if (!this.env.isManaged()) return true;
|
||||
|
||||
const marked = this.reflector.getAllAndOverride<{ enforcedInHandler?: boolean } | undefined>(MANAGED_FORBIDDEN, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
const marked = this.reflector.getAllAndOverride<
|
||||
{ enforcedInHandler?: boolean; allowHostedAssistant?: boolean } | undefined
|
||||
>(MANAGED_FORBIDDEN, [context.getHandler(), context.getClass()]);
|
||||
if (!marked) return true;
|
||||
|
||||
// A multipart handler checks for itself, after the interceptor has drained
|
||||
@@ -42,6 +41,7 @@ export class ManagedGuard implements CanActivate {
|
||||
// see an ECONNRESET rather than the 403 (PROFILE-015). The marker still sits
|
||||
// on the route so the boot gate can inventory it.
|
||||
if (marked.enforcedInHandler) return true;
|
||||
if (marked.allowHostedAssistant && !isManagedAssistantBlocked(this.env)) return true;
|
||||
|
||||
throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
|
||||
}
|
||||
|
||||
@@ -38,8 +38,12 @@ export const MANAGED_FORBIDDEN_ERROR = {
|
||||
* still carry the marker, because the boot gate inventories markers and a route
|
||||
* missing from that inventory is exactly what nobody notices.
|
||||
*/
|
||||
export const ManagedForbidden = (reason: string, opts?: { enforcedInHandler?: true }) =>
|
||||
SetMetadata(MANAGED_FORBIDDEN, { reason, enforcedInHandler: opts?.enforcedInHandler === true });
|
||||
export const ManagedForbidden = (reason: string, opts?: { enforcedInHandler?: true; allowHostedAssistant?: true }) =>
|
||||
SetMetadata(MANAGED_FORBIDDEN, {
|
||||
reason,
|
||||
enforcedInHandler: opts?.enforcedInHandler === true,
|
||||
...(opts?.allowHostedAssistant ? { allowHostedAssistant: true } : {}),
|
||||
});
|
||||
|
||||
/**
|
||||
* The handler-side flavour of the guard below.
|
||||
@@ -53,6 +57,10 @@ export function isManagedBlocked(env: RuntimeEnvService): boolean {
|
||||
return env.isManaged();
|
||||
}
|
||||
|
||||
export function isManagedAssistantBlocked(env: RuntimeEnvService): boolean {
|
||||
return env.isManaged() && !env.env().managed.assistant;
|
||||
}
|
||||
|
||||
/**
|
||||
* The settings a centrally administered install does not hand to its admin,
|
||||
* because the value belongs to whoever operates it.
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
* flight take minutes on a CPU host. The flat results map into the kitinerary pipeline via the
|
||||
* existing `nuExtractToKiReservations` mapper, so nothing downstream changes.
|
||||
*/
|
||||
import { airportByCode } from '../../airports/airports.contract';
|
||||
import type { KiReservation } from '../../booking-import/kitinerary.types';
|
||||
import { nuExtractToKiReservations } from '../clients/nuextract';
|
||||
import { parseLenientJson } from '../lenient-json';
|
||||
@@ -109,6 +110,22 @@ const TYPE_KEYWORDS: [FlatType, RegExp][] = [
|
||||
*/
|
||||
const EVENT_KEYWORDS = /\b(ticket|concert|konzert|veranstaltung|eintritt|admission)\b/i;
|
||||
|
||||
const FLIGHT_NUMBER_LABEL =
|
||||
/\b(?:flight(?:[ \t]+(?:number|no\.?))?|(?:hin|rück|rueck)?flug(?:nummer|nr\.?)?)[ \t\r\n:#]*$/i;
|
||||
const BOOKING_REFERENCE_LABEL =
|
||||
/\b(?:(?:trip|booking|reservation)[ \t]+(?:id|ref(?:erence)?|code|no\.?|number)|confirmation(?:[ \t]+(?:id|code|number))?|pnr|reference|buchungs(?:code|nummer|referenz)|reservierungsnummer|reiseplan|best(?:ä|ae)tigungs[- \t]?(?:code|nummer))[ \t\r\n:#]*$/i;
|
||||
const AIRPORT_PAIR = /\b([A-Z]{3})[ \t]*(?:->|[–—/→-])[ \t]*([A-Z]{3})\b/g;
|
||||
const FLIGHT_CONTEXT = 64;
|
||||
|
||||
/** Itinerary tables may put their route beside or on the line next to the flight number. */
|
||||
function hasNearbyAirportPair(before: string, number: string, after: string): boolean {
|
||||
const context = before.split('\n').slice(-2).join('\n') + number + after.split('\n').slice(0, 2).join('\n');
|
||||
for (const [, from, to] of context.matchAll(AIRPORT_PAIR)) {
|
||||
if (from && to && from !== to && airportByCode(from) && airportByCode(to)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The transport half of the table, for the flight gate in readType. */
|
||||
const TRANSPORT_FLAT_TYPES = new Set<FlatType>(['train', 'bus', 'ferry', 'car']);
|
||||
|
||||
@@ -126,10 +143,9 @@ interface TypeReading {
|
||||
function readType(text: string): TypeReading {
|
||||
const named = TYPE_KEYWORDS.filter(([, re]) => re.test(text)).map(([type]) => type);
|
||||
// The flight path forces type 'flight' on everything it returns, so it must not
|
||||
// claim a document that names another kind of transport: a German rail ticket
|
||||
// carries numbers like "IC 2023" or "RE 4711", which the two-letters-plus-digits
|
||||
// test cannot tell from an airline code (#2076).
|
||||
if (detectFlightNumbers(text).length > 0 && !named.some((type) => TRANSPORT_FLAT_TYPES.has(type))) {
|
||||
// claim another transport booking (#2076). A code alone cannot override a
|
||||
// named non-transport type either: it may be that booking's reference (#3271).
|
||||
if (!named.some((type) => TRANSPORT_FLAT_TYPES.has(type)) && detectFlightNumbers(text, named.length > 0).length > 0) {
|
||||
return { type: 'flight', candidates: [] };
|
||||
}
|
||||
if (named.length > 1) return { type: null, candidates: named };
|
||||
@@ -137,14 +153,23 @@ function readType(text: string): TypeReading {
|
||||
return { type: EVENT_KEYWORDS.test(text) ? 'event' : null, candidates: [] };
|
||||
}
|
||||
|
||||
/** Detect flight numbers (order-preserving, deduped) — also the "is this a flight doc" test. */
|
||||
export function detectFlightNumbers(text: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const m of text.matchAll(/\b([A-Z]{2})\s?(\d{2,4})\b/g)) {
|
||||
const fn = `${m[1]}${m[2]}`;
|
||||
if (!out.includes(fn)) out.push(fn);
|
||||
/** Flight numbers in document order. When another type is named, require evidence beside each code. */
|
||||
export function detectFlightNumbers(text: string, requireDetails = false): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const match of text.matchAll(/\b([A-Z]{2})\s?(\d{2,4})\b/g)) {
|
||||
const start = match.index;
|
||||
const end = start + match[0].length;
|
||||
const before = text.slice(Math.max(0, start - FLIGHT_CONTEXT), start);
|
||||
if (BOOKING_REFERENCE_LABEL.test(before)) continue;
|
||||
const labelled = FLIGHT_NUMBER_LABEL.test(before);
|
||||
const after = text.slice(end, end + FLIGHT_CONTEXT);
|
||||
// A numeric segment joined by a hyphen usually belongs to a compound reference.
|
||||
// An explicit flight label still allows a number followed by a date.
|
||||
if (!labelled && (/\d-$/.test(before) || /^-\d/.test(after))) continue;
|
||||
if (requireDetails && !labelled && !hasNearbyAirportPair(before, match[0], after)) continue;
|
||||
out.add(`${match[1]}${match[2]}`);
|
||||
}
|
||||
return out;
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -136,7 +136,10 @@ function packTerms(terms: readonly string[]): string[] {
|
||||
export function indexRequests(plan: IndexPoiPlan): IndexRequest[] {
|
||||
const all = plan.terms.join(',');
|
||||
if (plan.cap <= INDEX_MAX_LIMIT && all.length <= INDEX_MAX_CATEGORY_CHARS) {
|
||||
return [{ category: all, limit: plan.cap }];
|
||||
// Give sights room for historic-site rows that turn out to be housing.
|
||||
const limit =
|
||||
plan.wanted.length === 1 && plan.wanted[0] === 'sights' ? Math.min(INDEX_MAX_LIMIT, plan.cap * 2) : plan.cap;
|
||||
return [{ category: all, limit }];
|
||||
}
|
||||
return indexRequestsPerKind(plan);
|
||||
}
|
||||
@@ -199,7 +202,8 @@ export function indexPoiAnswer(
|
||||
): PoiSearchResult {
|
||||
const { wanted, labelFor, cap, radius, reach } = plan;
|
||||
// Pages asked per category can together run past the cap.
|
||||
const kept = belonging(found, plan).slice(0, cap);
|
||||
const matching = belonging(found, plan);
|
||||
const kept = matching.slice(0, cap);
|
||||
return {
|
||||
pois: kept.map((p) => ({
|
||||
osm_id: `gers:${p.gers}`,
|
||||
@@ -233,13 +237,17 @@ export function indexPoiAnswer(
|
||||
// The page the index sent, not what was left of it: a full page means more
|
||||
// places, however many of them this one had to leave out. Pages asked per
|
||||
// category say so for themselves, and their sum may run past the cap.
|
||||
truncated: pageFull || found.length > cap,
|
||||
truncated: pageFull || matching.length > cap,
|
||||
// A wide viewport is narrowed here too, and the caller is told so
|
||||
// for the same reason the Overpass path tells it.
|
||||
clamped: radius < reach,
|
||||
};
|
||||
}
|
||||
|
||||
const RESIDENTIAL_SITE_SUFFIX = /\b(?:apartments?|apts\.?|apartment homes|condos?|condominiums?|condo association)$/i;
|
||||
const PUBLIC_SITE_NAME = /\b(?:historic|heritage|museum|landmark)\b/i;
|
||||
const HISTORIC_SITE_TERM = 'cultural_and_historic>historic_site';
|
||||
|
||||
/**
|
||||
* The rows that belong to a pill the request asked for. The index matches its
|
||||
* terms inside the category text, so a near miss can still come back, and it
|
||||
@@ -247,9 +255,16 @@ export function indexPoiAnswer(
|
||||
* be told either way and stays, as it always has.
|
||||
*/
|
||||
export function belonging<T extends TrekPlace & { categoryPath?: string | null }>(found: T[], plan: IndexPoiPlan): T[] {
|
||||
return found.filter(
|
||||
(p) => (!p.category && !p.categoryPath) || plan.labelFor(p.category ?? null, p.categoryPath ?? null) !== undefined,
|
||||
);
|
||||
return found.filter((place) => {
|
||||
const leaf = place.category ?? null;
|
||||
const path = place.categoryPath ?? null;
|
||||
const category = plan.labelFor(leaf, path);
|
||||
if (category === 'sights' && place.source === 'overture' && indexRowTerm([HISTORIC_SITE_TERM], leaf, path)) {
|
||||
// Overture labels some residential buildings as historic sites (#3270).
|
||||
if (RESIDENTIAL_SITE_SUFFIX.test(place.name.trim()) && !PUBLIC_SITE_NAME.test(place.name)) return false;
|
||||
}
|
||||
return category !== undefined || (!leaf && !path);
|
||||
});
|
||||
}
|
||||
|
||||
const regionNamesByLang = new Map<string, Intl.DisplayNames | null>();
|
||||
|
||||
@@ -304,25 +304,19 @@ export class UnifiedMemoriesService {
|
||||
}
|
||||
|
||||
async removeAlbumLink(tripId: string, linkId: string, userId: number): Promise<ServiceResult<true>> {
|
||||
const access = await this.trips.findAccessible(tripId, userId);
|
||||
if (!access) {
|
||||
return fail('Trip not found or access denied', 404);
|
||||
}
|
||||
// A link id toRowId refuses names no link, so there is nothing to remove,
|
||||
// as for an id no link has; bound raw, Postgres refused it with an error.
|
||||
const link = toRowId(linkId);
|
||||
if (link === null) return success(true);
|
||||
|
||||
try {
|
||||
const linkedPhotoIds = await this.tripPhotos.listPhotoIdsForAlbumLink(tripId, link);
|
||||
return await this.uow.transactional<ServiceResult<true>>(async () => {
|
||||
const trip = await this.trips.findAccessible(tripId, userId);
|
||||
if (!trip) return fail('Trip not found or access denied', 404);
|
||||
if (link === null || !(await this.tripAlbumLinks.findScoped(link, trip.id, userId))) return success(true);
|
||||
|
||||
await this.uow.transactional(async () => {
|
||||
await this.tripPhotos.deleteForAlbumLink(tripId, link);
|
||||
await this.tripAlbumLinks.deleteScoped(link, tripId, userId);
|
||||
const linkedPhotoIds = await this.tripPhotos.listPhotoIdsForAlbumLink(trip.id, link);
|
||||
await this.tripPhotos.deleteForAlbumLink(trip.id, link);
|
||||
await this.tripAlbumLinks.deleteScoped(link, trip.id, userId);
|
||||
for (const photo_id of linkedPhotoIds) await this.photos.deleteIfOrphan(photo_id);
|
||||
return success(true);
|
||||
});
|
||||
|
||||
return success(true);
|
||||
} catch (error) {
|
||||
return mapDbError(error, 'Failed to remove album link');
|
||||
}
|
||||
|
||||
@@ -182,6 +182,8 @@ export function pluginPermissionArgs(pluginId: string): string[] {
|
||||
const codeRoot = serverCodeRoot();
|
||||
return [
|
||||
'--permission',
|
||||
// Built-in SQLite is outside Node's filesystem allowlist. Plugins use ctx.db.
|
||||
'--no-experimental-sqlite',
|
||||
`--allow-fs-read=${codeRoot}`,
|
||||
// The server package.json sits one level above dist and Node reads it to
|
||||
// resolve the child's module type. Grant just that file — never its dir,
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
carrierSeam,
|
||||
foldRouteRun,
|
||||
hotelBookendsOn,
|
||||
incomingDayJoin,
|
||||
isStationaryJoin,
|
||||
oneNightPerStay,
|
||||
splitIntoRuns,
|
||||
@@ -224,9 +225,11 @@ export class RoadtripPlanService {
|
||||
stops.forEach((stop, index) => {
|
||||
stopAt.push(points.length);
|
||||
points.push({ lat: stop.lat, lng: stop.lng });
|
||||
// None bend the drive from or to a booked night's hotel (`viasOnLeg`).
|
||||
if (index < stops.length - 1)
|
||||
// A via dropped on the leg shapes the drive between its stops. None bend the drive
|
||||
// from or to a booked night's hotel (`viasOnLeg`).
|
||||
if (index < stops.length - 1) {
|
||||
points.push(...viasOnLeg(stop, stops[index + 1], context.vias).map((v) => ({ lat: v.lat, lng: v.lng })));
|
||||
}
|
||||
});
|
||||
try {
|
||||
if (points.length > 100) throw new Error('Too many waypoints');
|
||||
@@ -286,17 +289,17 @@ export class RoadtripPlanService {
|
||||
for (const run of splitIntoRuns(day.stops, (from) => from.legMode ?? fallback))
|
||||
await fetchRun(run.stops, day.dayId, run.mode);
|
||||
}
|
||||
const driveDays = plan.filter((d) => standsAsDay(d.stops));
|
||||
const quietDays = plan.filter((d) => !standsAsDay(d.stops));
|
||||
const chains = window
|
||||
? plan.filter((d) => d.stops.length)
|
||||
: spillChains(
|
||||
plan.filter((d) => d.stops.length > 1),
|
||||
plan.filter((d) => d.stops.length < 2),
|
||||
(a, b) => allLegs[stopKey(a) + '>' + stopKey(b)],
|
||||
);
|
||||
let previous: RoadtripStop | undefined;
|
||||
: spillChains(driveDays, quietDays, (a, b) => allLegs[stopKey(a) + '>' + stopKey(b)]);
|
||||
let previous: readonly RoadtripStop[] = [];
|
||||
for (const chain of chains) {
|
||||
const pairs = chain.stops.slice(0, -1).map((from, index) => ({ from, to: chain.stops[index + 1] }));
|
||||
if (connectDays && previous && chain.stops.length) pairs.push({ from: previous, to: chain.stops[0] });
|
||||
const to = chain.stops[0];
|
||||
const from = incomingDayJoin(previous, chain.stops, connectDays);
|
||||
if (from && to) pairs.push({ from, to });
|
||||
for (const { from, to } of pairs) {
|
||||
// A night spent at one hotel is no drive, and no router is asked about it.
|
||||
if (isStationaryJoin(from, to) || asked.has(stopKey(from) + '>' + stopKey(to))) continue;
|
||||
@@ -306,7 +309,7 @@ export class RoadtripPlanService {
|
||||
from.legMode ?? context.days.find((d) => d.id === chain.dayId)?.default_transport_mode ?? 'driving',
|
||||
);
|
||||
}
|
||||
previous = chain.stops[chain.stops.length - 1] ?? previous;
|
||||
if (chain.stops.length) previous = chain.stops;
|
||||
}
|
||||
const vehicleKind = preferences.roadtrip_vehicle || null;
|
||||
const rangeKm =
|
||||
@@ -322,8 +325,8 @@ export class RoadtripPlanService {
|
||||
preferences.roadtrip_range_km,
|
||||
) || null;
|
||||
const calculated = assembleRoadtrip({
|
||||
plan: plan.filter((d) => standsAsDay(d.stops)),
|
||||
quietDays: plan.filter((d) => !standsAsDay(d.stops)),
|
||||
plan: driveDays,
|
||||
quietDays,
|
||||
window,
|
||||
allLegs,
|
||||
snapByDay,
|
||||
|
||||
@@ -49,7 +49,7 @@ export class RoadtripPlanningMcp {
|
||||
@Tool({
|
||||
name: 'calculate_roadtrip',
|
||||
description:
|
||||
'Calculate a saved trip without an open browser, using the same daily scheduling and vehicle-range rules as the planner. Returns derived days, arrivals, departures, driving limits, fuel warnings, automatic pauses and routing failures. A flight, train, ferry, cruise or bus booking with located terminals is a seam: its terminals appear as stops carrying `carrier` (role departure or arrival), the road ends at the departure terminal and resumes at the arrival one, and the leg between them is the ride, in the mode of the booking type, with its timetable minutes and no distance. The departure terminal is pinned a check-in ahead of the timetable departure (an hour for a flight); reaching it after that is a late warning with the full minutes, however many, and the ride keeps its own day, so the drive after the arrival terminal goes on from the timetable arrival. On a day a ride leaves and lands on, the stop of a stay checked into that day comes after the arrival terminal when the stay lies nearer to it than to the departure terminal: a check-in is the earliest arrival, not a time that seats the stay ahead of the ride, and it pins the stay only when the ride lands before it. A time set on the stop itself keeps its seat. A hire car booking with a located pick-up desk puts that desk on the road as a stop carrying `carrier` with role pickup, and its return desk with role return when the booking names a return day and place; the road runs through both. A flight, train, ferry, cruise or bus booking that is on none of the days of the trip (saved without a date, or on a day the trip no longer has) is not on the drive at all, although its terminals are located: undatedRides lists each one (id, type, title) so it can be given a date within the trip with the reservation tools, after which the road ends at its terminal. With roadtrip_hotel_bookends switched on (missing means off), a day after a booked night starts at that stay and a day before one ends there. Such stops carry `bookend` {phase, accommodationId, reservationId, checkingOut, checkingIn, checkOut, and checkIn on the evening a stay begins when it has a check-in time}, stopType hotel, the real placeId of the stay and a synthetic negative assignmentId that belongs to no assignment: they cannot be reordered, edited or given via points, and `failures` may name them. The check-out and check-in are labels, never a departure or arrival time. A day between two nights in the same stay with no visit has no drive. Nor does a day with nothing on it but the check-in of the next stay when a flight, train, ferry, cruise or bus is booked on that day, with or without located terminals: the booking is the move between the two stays. A stay is never joined by road to a terminal more than 2000 km away in a straight line. Pass settings {roadtrip_hotel_bookends:true} to preview the drive from and to the stays without saving it. A hotel visited more than once on the check-in day of its stay is the night (night true, checkInTime set) at one visit only: the visit that ends the day, else the stop the booking put on the day, else the last visit; the other visits are ordinary stops. Fixed visit times retain priority. The end time of a visit is when the drive leaves it, in place of its stay; reaching the visit after it is reported as a missedLeave warning. No accommodation or place is created. Optional settings are a read-only preview, not saved. Distances are metres, durations seconds, dwell times minutes. A failed leg or conflicting window means the output is incomplete: never present its totals as a complete route. Up to 150 legs; requests are paced for public routing servers and can take time. Existing place/assignment tools edit stops, stays and ordering, update_roadtrip_settings saves preferences, set_assignment_end_day and set_day_boundary set exceptions. Recalculate after changes. Plugin profiles follow installed route-provider permissions.',
|
||||
'Calculate a saved trip without an open browser, using the same daily scheduling and vehicle-range rules as the planner. Returns derived days, arrivals, departures, driving limits, fuel warnings, automatic pauses and routing failures. A flight, train, ferry, cruise or bus booking with located terminals is a seam: its terminals appear as stops carrying `carrier` (role departure or arrival), the road ends at the departure terminal and resumes at the arrival one, and the leg between them is the ride, in the mode of the booking type, with its timetable minutes and no distance. The departure terminal is pinned a check-in ahead of the timetable departure (an hour for a flight); reaching it after that is a late warning with the full minutes, however many, and the ride keeps its own day, so the drive after the arrival terminal goes on from the timetable arrival. On a day a ride leaves and lands on, the stop of a stay checked into that day comes after the arrival terminal when the stay lies nearer to it than to the departure terminal: a check-in is the earliest arrival, not a time that seats the stay ahead of the ride, and it pins the stay only when the ride lands before it. A time set on the stop itself keeps its seat. A hire car booking with a located pick-up desk puts it on the road with role pickup, and its located return desk with role return. Located intermediate stops stay on the road even when the booking has no return desk. Those stops have synthetic negative assignment IDs and no carrier role. A flight, train, ferry, cruise or bus booking that is on none of the days of the trip (saved without a date, or on a day the trip no longer has) is not on the drive at all, although its terminals are located: undatedRides lists each one (id, type, title) so it can be given a date within the trip with the reservation tools, after which the road ends at its terminal. With roadtrip_hotel_bookends switched on (missing means off), a day after a booked night starts at that stay and a day before one ends there. Such stops carry `bookend` {phase, accommodationId, reservationId, checkingOut, checkingIn, checkOut, and checkIn on the evening a stay begins when it has a check-in time}, stopType hotel, the real placeId of the stay and a synthetic negative assignmentId that belongs to no assignment: they cannot be reordered, edited or given via points, and `failures` may name them. The check-out and check-in are labels, never a departure or arrival time. A day between two nights in the same stay with no visit has no drive. Nor does a day with nothing on it but the check-in of the next stay when a flight, train, ferry, cruise or bus is booked on that day, with or without located terminals: the booking is the move between the two stays. A stay is never joined by road to a terminal more than 2000 km away in a straight line. Pass settings {roadtrip_hotel_bookends:true} to preview the drive from and to the stays without saving it. A hotel visited more than once on the check-in day of its stay is the night (night true, checkInTime set) at one visit only: the visit that ends the day, else the stop the booking put on the day, else the last visit; the other visits are ordinary stops. Fixed visit times retain priority. The end time of a visit is when the drive leaves it, in place of its stay; reaching the visit after it is reported as a missedLeave warning. No accommodation or place is created. Optional settings are a read-only preview, not saved. Distances are metres, durations seconds, dwell times minutes. A failed leg or conflicting window means the output is incomplete: never present its totals as a complete route. Up to 150 legs; requests are paced for public routing servers and can take time. Existing place/assignment tools edit stops, stays and ordering, update_roadtrip_settings saves preferences, set_assignment_end_day and set_day_boundary set exceptions. Recalculate after changes. Plugin profiles follow installed route-provider permissions.',
|
||||
inputSchema: roadtripPlanRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
@@ -74,7 +74,8 @@ export class RoadtripPlanningMcp {
|
||||
dayNumber: day.dayNumber,
|
||||
date: day.date,
|
||||
title: day.title,
|
||||
stops: day.stops,
|
||||
// Waypoints are synthesised stops. Keep the public carrier roles for terminals only.
|
||||
stops: day.stops.map((stop) => (stop.carrier?.role === 'stop' ? { ...stop, carrier: undefined } : stop)),
|
||||
schedule: day.schedule,
|
||||
legs: day.legs,
|
||||
distanceMetres: day.distance,
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
import { AiConnections } from '../../src/db/entities/AiConnections.entity';
|
||||
import { AiConnectionsModule } from '../../src/nest/ai-connections/ai-connections.module';
|
||||
import { AiConnectionsService } from '../../src/nest/ai-connections/ai-connections.service';
|
||||
import { AppConfigModule } from '../../src/nest/app-config/app-config.module';
|
||||
import { DemoModule } from '../../src/nest/common/demo.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
@@ -24,6 +25,7 @@ import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { RequestContext } from '@mikro-orm/core';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
@@ -111,6 +113,42 @@ afterAll(async () => {
|
||||
});
|
||||
|
||||
describe('AI connections e2e', () => {
|
||||
it('uses the operator gateway and requires a separate acknowledgement on a managed instance', async () => {
|
||||
vi.stubEnv('TREK_MANAGED', '1');
|
||||
vi.stubEnv('TREK_MANAGED_ASSISTANT_URL', 'https://gate.example.test/ai/v1');
|
||||
vi.stubEnv('TREK_MANAGED_ASSISTANT_MODEL', 'qwen/qwen3.7-flash');
|
||||
vi.stubEnv('TREK_MANAGED_ASSISTANT_TOKEN', 'synthetic-instance-bearer');
|
||||
try {
|
||||
const connections = app.get(AiConnectionsService);
|
||||
const resolve = () => RequestContext.create(orm.em, () => connections.resolveForUser(OTHER));
|
||||
const first = await request(server).get('/api/ai/status').set(as(OTHER));
|
||||
expect(first.status).toBe(200);
|
||||
expect(first.body).toMatchObject({
|
||||
available: true,
|
||||
canConnectOwn: false,
|
||||
effective: { kind: 'openrouter', host: 'openrouter.ai', source: 'instance' },
|
||||
privacyAcked: false,
|
||||
quota: null,
|
||||
studioImages: true,
|
||||
});
|
||||
expect(first.text).not.toContain('synthetic-instance-bearer');
|
||||
await expect(resolve()).rejects.toThrow('Acknowledge the AI Assistant privacy notice');
|
||||
const ack = await request(server)
|
||||
.post('/api/ai/privacy-ack')
|
||||
.set(as(OTHER))
|
||||
.send({ kind: 'openrouter', host: 'openrouter.ai' });
|
||||
expect(ack.status).toBe(200);
|
||||
await expect(resolve()).resolves.toMatchObject({
|
||||
managed: true,
|
||||
baseUrl: 'https://gate.example.test/ai/v1',
|
||||
});
|
||||
expect((await request(server).get('/api/ai/status').set(as(OTHER))).body.privacyAcked).toBe(true);
|
||||
expect(safeFetch).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
it('AIE2E-001: the addon gate answers 404 before auth, then auth answers 401', async () => {
|
||||
await setAddonEnabled(orm, 'ai_assistant', false);
|
||||
expect((await request(server).get('/api/ai/status')).status).toBe(404);
|
||||
|
||||
@@ -24,6 +24,9 @@ const NOT_OPERATOR_SETTINGS: Record<string, string> = {
|
||||
APP_VERSION: 'set by the image build; the VERSION file wins over it',
|
||||
TREK_DB_FILE: 'points the Playwright harness at a throwaway database',
|
||||
TREK_MANAGED: 'managed hosting only, deliberately undocumented for self-hosters',
|
||||
TREK_MANAGED_ASSISTANT_URL: 'managed hosting only, the operator gateway URL',
|
||||
TREK_MANAGED_ASSISTANT_TOKEN: 'managed hosting only, the instance credential for the operator gateway',
|
||||
TREK_MANAGED_ASSISTANT_MODEL: 'managed hosting only, the operator-selected assistant model',
|
||||
MAPBOX_ACCESS_TOKEN: 'managed hosting only (read with TREK_MANAGED), deliberately undocumented for self-hosters',
|
||||
CARTO_API_KEY: 'managed hosting only (read with TREK_MANAGED), deliberately undocumented for self-hosters',
|
||||
PLACES_API_BASE: "managed hosting's egress gateway for the Places calls, deliberately undocumented for self-hosters",
|
||||
|
||||
@@ -59,6 +59,41 @@ describe('validateEnvAtBoot', () => {
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
const managedAssistant = {
|
||||
TREK_MANAGED: '1',
|
||||
ENCRYPTION_KEY: 'a'.repeat(64),
|
||||
TREK_MANAGED_ASSISTANT_URL: 'https://gate.example.com/ai/v1',
|
||||
TREK_MANAGED_ASSISTANT_MODEL: 'provider/model',
|
||||
TREK_MANAGED_ASSISTANT_TOKEN: 'synthetic-assistant-credential',
|
||||
};
|
||||
|
||||
it('accepts a managed assistant with a complete gateway configuration', () => {
|
||||
expect(() => validateEnvAtBoot(managedAssistant)).not.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['TREK_MANAGED_ASSISTANT_URL', ''],
|
||||
['TREK_MANAGED_ASSISTANT_MODEL', ' '],
|
||||
['TREK_MANAGED_ASSISTANT_TOKEN', ' '],
|
||||
])('refuses partial managed assistant configuration with %s missing', (key, value) => {
|
||||
const report = bootReport({ ...managedAssistant, [key]: value });
|
||||
expect(report.printed).toContain('URL, model and token must be configured together');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'https://name:synthetic-url-password@invalid host/',
|
||||
'http://gate.example.com/ai/v1',
|
||||
'https://user@gate.example.com/ai/v1',
|
||||
'https://:synthetic-url-password@gate.example.com/ai/v1',
|
||||
'https://gate.example.com/ai/v1?query=1',
|
||||
'https://gate.example.com/ai/v1#section',
|
||||
])('refuses an unsafe managed assistant URL', (url) => {
|
||||
const report = bootReport({ ...managedAssistant, TREK_MANAGED_ASSISTANT_URL: url });
|
||||
expect(report.printed).toContain('must be an HTTPS URL without credentials, a query or a fragment');
|
||||
expect(report.printed).not.toContain('synthetic-url-password');
|
||||
expect(report.printed).not.toContain(managedAssistant.TREK_MANAGED_ASSISTANT_TOKEN);
|
||||
});
|
||||
|
||||
it('refuses an LLM ceiling that would silently become a zero timeout', () => {
|
||||
// Both shapes pass a plain "positive number" check and then degrade into an
|
||||
// immediate abort: a fractional value floors to 0, and anything past the
|
||||
|
||||
@@ -48,13 +48,16 @@ class FakeResponse extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
function make(opts: { addon?: boolean; managed?: boolean; trip?: boolean } = {}) {
|
||||
function make(opts: { addon?: boolean; managed?: boolean; managedAssistant?: boolean; trip?: boolean } = {}) {
|
||||
const service = {
|
||||
attach: vi.fn(async (_u: number, _t: number, _b: unknown, _f: unknown, _c: TurnChannel) => undefined),
|
||||
};
|
||||
const trips = { findAccessible: vi.fn(async () => (opts.trip === false ? undefined : { id: 5, user_id: 7 })) };
|
||||
const addons = { isAddonEnabled: vi.fn(async () => opts.addon !== false) };
|
||||
const env = { isManaged: () => opts.managed === true };
|
||||
const env = {
|
||||
isManaged: () => opts.managed === true,
|
||||
env: () => ({ managed: { assistant: opts.managedAssistant ? { model: 'test-model' } : undefined } }),
|
||||
};
|
||||
const controller = new AssistantAttachmentsController(
|
||||
service as unknown as AssistantService,
|
||||
trips as unknown as TripAccessService,
|
||||
@@ -105,6 +108,10 @@ describe('AssistantAttachmentsController', () => {
|
||||
});
|
||||
expect(stranger.trips.findAccessible).toHaveBeenCalledWith('5', 7);
|
||||
for (const t of [off, managed, stranger]) expect(t.service.attach).not.toHaveBeenCalled();
|
||||
|
||||
const managedWithAssistant = make({ managed: true, managedAssistant: true });
|
||||
await managedWithAssistant.controller.attach(user, '5', file('a.pdf'), BODY, res);
|
||||
expect(managedWithAssistant.service.attach).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('ASTATT-003: a missing, too large or unknown file is refused before the turn', async () => {
|
||||
|
||||
@@ -519,6 +519,30 @@ describe('registerUser — OIDC-only / registration-disabled', () => {
|
||||
expect(result.error).toMatch(/password registration is disabled/i);
|
||||
});
|
||||
|
||||
it.each(['environment', 'legacy setting'])(
|
||||
'AUTH-DB-033b: honors the SSO-only registration policy from the %s',
|
||||
async (source) => {
|
||||
vi.stubEnv('OIDC_ONLY', source === 'environment' ? 'true' : '');
|
||||
try {
|
||||
if (source === 'legacy setting') await appSetting('oidc_only', 'true');
|
||||
await appSetting('oidc_issuer', 'https://sso.example.test');
|
||||
await appSetting('oidc_client_id', 'test-client');
|
||||
|
||||
const credentials = { username: 'signup', email: 'signup@example.test', password: 'Secure123!' };
|
||||
expect(await asLegacyResult(svc.registerUser(credentials))).toMatchObject({ status: 403 });
|
||||
expect(await countRows(orm, Users, {})).toBe(0);
|
||||
|
||||
const invite = createInviteToken(testDb);
|
||||
const invited = await asLegacyResult(svc.registerUser({ ...credentials, invite_token: invite.token }));
|
||||
expect(invited).toMatchObject({ status: 403 });
|
||||
expect(await countRows(orm, Users, {})).toBe(1);
|
||||
expect(await findRow(orm, InviteTokens, { id: invite.id })).toMatchObject({ used_count: 0 });
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('AUTH-DB-034: returns 403 when registration is disabled and no invite', async () => {
|
||||
createUser(testDb); // ensure userCount > 0
|
||||
await appSetting('allow_registration', 'false');
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
routeImageExtraction,
|
||||
} from '../../../../src/nest/llm-parse/router/extraction-router';
|
||||
import { FLAT_SCHEMA_BY_TYPE, FLIGHTS_ARRAY_SCHEMA } from '../../../../src/nest/llm-parse/router/flat-schemas';
|
||||
import { fitTextWindow } from '../../../../src/nest/llm-parse/text-window';
|
||||
import { fitTextWindow, LOCAL_TEXT_WINDOW } from '../../../../src/nest/llm-parse/text-window';
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
@@ -88,6 +88,14 @@ describe('detectFlightNumbers', () => {
|
||||
it('returns [] when there is no flight-number pattern', () => {
|
||||
expect(detectFlightNumbers('A hotel booking with no flight codes')).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores flight-like fragments of compound numeric references (#3271)', () => {
|
||||
expect(detectFlightNumbers('ZO-AX1234-00001, 00002-AX2345-ZO, then LH400-FRA.')).toEqual(['LH400']);
|
||||
});
|
||||
|
||||
it('keeps a labelled flight number before a date and skips labelled booking references (#3271)', () => {
|
||||
expect(detectFlightNumbers('Trip ID: AX1234\nFlight number: LH400-12 DEC\nBooking No.: AX4567')).toEqual(['LH400']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fixArrivalDate', () => {
|
||||
@@ -155,6 +163,40 @@ describe('routeExtraction', () => {
|
||||
expect(flats[0].type).toBe('hotel');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'Trip ID: ZO-AX1234-00001',
|
||||
'Trip ID: AX1234',
|
||||
'Trip ID: AX1234\nPlease send your flight number for airport pickup.',
|
||||
'Rate AX1234\nVAT-REG: 123456',
|
||||
])('reads a hotel confirmation with a reference line %j (#3271)', async (reference) => {
|
||||
const header = `Hotel Sol\n${reference}\nCheck-in: 3 Dec 2026\nCheck-out: 6 Dec 2026\n`;
|
||||
const boilerplate = 'Booking conditions apply.\n'.repeat(250);
|
||||
const { text } = fitTextWindow(`${header}${boilerplate}Cruise offers\n${boilerplate}`, LOCAL_TEXT_WINDOW);
|
||||
expect(text).not.toContain('Cruise offers');
|
||||
const hotel = { name: 'Hotel Sol', checkin_time: '2026-12-03T15:00:00', checkout_time: '2026-12-06T11:00:00' };
|
||||
extractEnforced.mockImplementation(async ({ schema }) =>
|
||||
schema === FLAT_SCHEMA_BY_TYPE.hotel ? hotel : { flights: [] },
|
||||
);
|
||||
mapToKi.mockImplementationOnce((flats) => (flats.length ? [{ '@type': 'LodgingReservation' }] : []));
|
||||
|
||||
const result = await routeExtraction(text, CTX);
|
||||
|
||||
expect(extractEnforced).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ schema: FLAT_SCHEMA_BY_TYPE.hotel }),
|
||||
);
|
||||
expect(mapToKi.mock.calls[0][0]).toEqual([{ ...hotel, type: 'hotel' }]);
|
||||
expect(result).toEqual({ kiItems: [{ '@type': 'LodgingReservation' }], warnings: [], outcome: 'ok' });
|
||||
});
|
||||
|
||||
it('keeps a restaurant booking with a flight-like reference on its own schema (#3271)', async () => {
|
||||
extractEnforced.mockResolvedValue({ name: 'Sol', start_time: '2026-12-03T19:00:00' });
|
||||
await routeExtraction('Restaurant Sol\nBooking No.: AX1234\nPlease add your flight number if arriving today.', CTX);
|
||||
expect(extractEnforced).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ schema: FLAT_SCHEMA_BY_TYPE.restaurant }),
|
||||
);
|
||||
expect(mapToKi.mock.calls[0][0][0].type).toBe('restaurant');
|
||||
});
|
||||
|
||||
it('falls back to the union schema and the model-picked type for an unclear document', async () => {
|
||||
extractEnforced.mockResolvedValue({ type: 'event', name: 'Concert' });
|
||||
const res = await routeExtraction('A document with no obvious type keywords', CTX);
|
||||
@@ -389,6 +431,20 @@ describe('documents that name more than one type', () => {
|
||||
expect(mapToKi.mock.calls[0][0][0].type).toBe('flight');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['Lufthansa LH 400 FRA-JFK. Hotels in New York.', 'LH400', 'FRA', 'JFK'],
|
||||
['Confirmación de vuelo\nIB 3178\nMAD / LIS\nHotel recomendado', 'IB3178', 'MAD', 'LIS'],
|
||||
['Flight number: LH400-12 DEC\nHotels in New York.', 'LH400', 'FRA', 'JFK'],
|
||||
])(
|
||||
'keeps the itinerary %j with hotel offers on the flight path (#3271)',
|
||||
async (itinerary, vehicle_number, from_code, to_code) => {
|
||||
extractEnforced.mockResolvedValue({ flights: [{ vehicle_number, from_code, to_code }] });
|
||||
await routeExtraction(itinerary, CTX);
|
||||
expect(sentSchema()).toBe(FLIGHTS_ARRAY_SCHEMA);
|
||||
expect(mapToKi.mock.calls[0][0][0].type).toBe('flight');
|
||||
},
|
||||
);
|
||||
|
||||
it('reads the event words only when the document names no other type', async () => {
|
||||
extractEnforced.mockResolvedValue({ name: 'Concert' });
|
||||
await routeExtraction('Concert ticket. Doors open 19:00.', CTX);
|
||||
|
||||
@@ -17,12 +17,23 @@ import { Reflector } from '@nestjs/core';
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
function makeGuard(managed: boolean, marked: boolean, enforcedInHandler = false) {
|
||||
function makeGuard(
|
||||
managed: boolean,
|
||||
marked: boolean,
|
||||
enforcedInHandler = false,
|
||||
hosted = false,
|
||||
allowHostedAssistant = false,
|
||||
) {
|
||||
const getAllAndOverride = vi.fn((key: string) =>
|
||||
key === MANAGED_FORBIDDEN && marked ? { reason: 'the operator holds this', enforcedInHandler } : undefined,
|
||||
key === MANAGED_FORBIDDEN && marked
|
||||
? { reason: 'the operator holds this', enforcedInHandler, allowHostedAssistant }
|
||||
: undefined,
|
||||
);
|
||||
const guard = new ManagedGuard(
|
||||
{ isManaged: () => managed } as unknown as RuntimeEnvService,
|
||||
{
|
||||
isManaged: () => managed,
|
||||
env: () => ({ managed: { assistant: hosted ? {} : null } }),
|
||||
} as unknown as RuntimeEnvService,
|
||||
{ getAllAndOverride } as unknown as Reflector,
|
||||
);
|
||||
return { guard, getAllAndOverride };
|
||||
@@ -80,6 +91,12 @@ describe('ManagedGuard', () => {
|
||||
expect(guard.canActivate(ctx)).toBe(true);
|
||||
});
|
||||
|
||||
it('only lets the hosted assistant through when the operator configured it and the handler permits it', () => {
|
||||
expect(makeGuard(true, true, false, true, true).guard.canActivate(ctx)).toBe(true);
|
||||
expect(thrown(() => makeGuard(true, true, false, true).guard.canActivate(ctx))?.getStatus()).toBe(403);
|
||||
expect(thrown(() => makeGuard(true, true, false, false, true).guard.canActivate(ctx))?.getStatus()).toBe(403);
|
||||
});
|
||||
|
||||
it('MANAGED-GUARD-005: asks for the decorator on handler and controller, not for a path', () => {
|
||||
const { guard, getAllAndOverride } = makeGuard(true, false);
|
||||
guard.canActivate(ctx);
|
||||
|
||||
@@ -161,6 +161,30 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe('MapsService.pois answered from the index', () => {
|
||||
it('MAPS-POIS-019: residential rows mislabeled as historic sites do not consume the sights list', async () => {
|
||||
const historicSite = {
|
||||
...FULL,
|
||||
category: 'historic_site',
|
||||
categoryPath: 'cultural_and_historic>historic_site',
|
||||
confidence: 0.99,
|
||||
};
|
||||
const results = [
|
||||
{ ...historicSite, gers: 'housing', name: 'Pisgah View Apartments' },
|
||||
{ ...historicSite, gers: 'condos', name: 'The Landings Condos', category: null },
|
||||
{ ...historicSite, gers: 'museum', name: 'Museum of Historic Apartments' },
|
||||
{ ...historicSite, gers: 'estate', name: 'Biltmore Estate', confidence: 0.8 },
|
||||
];
|
||||
mockNearby.mockImplementation(async (_lat, _lng, options) => results.slice(0, options?.limit));
|
||||
const svc = make();
|
||||
const overpass = stubOverpass(svc);
|
||||
|
||||
const answer = await svc.pois('sights', BOX, undefined, 3);
|
||||
|
||||
expect(overpass).not.toHaveBeenCalled();
|
||||
expect(answer.pois.map((poi) => poi.name)).toEqual(['Museum of Historic Apartments', 'Biltmore Estate']);
|
||||
expect(answer.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it('MAPS-POIS-001: maps a full index row onto the record the map already reads', async () => {
|
||||
mockNearby.mockResolvedValue([FULL]);
|
||||
const svc = make();
|
||||
|
||||
@@ -454,6 +454,49 @@ describe('a booking the traveller rides (#2428)', () => {
|
||||
expect(card.distance).toBe(240_000);
|
||||
expect(calculated.totalStops).toBe(3);
|
||||
});
|
||||
|
||||
it('routes a hire car through its waypoint and across days to its own return desk', async () => {
|
||||
const { user, trip, plans, visits } = await setup();
|
||||
const start = await dayOf(visits[0].id);
|
||||
const end = createDay(db, trip.id);
|
||||
const destination = createPlace(db, trip.id, { name: 'Destination', lat: 52.51, lng: 13.41 });
|
||||
const destinationVisit = createDayAssignment(db, end.id, destination.id);
|
||||
await setVisit(destinationVisit.id, { assignment_time: '01:00' });
|
||||
const car = await addReservation({
|
||||
trip: trip.id,
|
||||
type: 'car',
|
||||
title: 'Hire car',
|
||||
day: start.day_id,
|
||||
endDay: end.id,
|
||||
reservation_time: '08:00',
|
||||
reservation_end_time: '02:00',
|
||||
});
|
||||
await addEndpoint(car, 'from', 0, 'Pick-up', null, 53.55, 10.0);
|
||||
await addEndpoint(car, 'stop', 1, 'On the way', null, 53.43, 10.4);
|
||||
await addEndpoint(car, 'to', 2, 'Return', null, 52.52, 13.41);
|
||||
|
||||
const { calculated } = await plans.calculate(trip.id, user.id);
|
||||
|
||||
expect(calculated.days[0].stops.map((stop) => stop.name)).toEqual([
|
||||
'Pick-up',
|
||||
'On the way',
|
||||
'Hamburg',
|
||||
'Lueneburg',
|
||||
'Celle',
|
||||
]);
|
||||
expect(calculated.days[1].stops.map((stop) => stop.name)).toEqual(['Destination', 'Return']);
|
||||
expect(calculated.days[1].arrivingFrom).toMatchObject({ name: 'Celle' });
|
||||
expect(calculated.days[1].arrivingLeg?.distance).toBe(60_000);
|
||||
|
||||
const tool = new RoadtripPlanningMcp(plans, {} as never, {} as never);
|
||||
const answer = await tool.calculate({ tripId: trip.id, includeGeometry: true }, { userId: user.id } as McpContext);
|
||||
const body = JSON.parse(answer.content[0].text);
|
||||
expect(body.days[0].stops[0].carrier.role).toBe('pickup');
|
||||
expect(body.days[0].stops[1]).toMatchObject({ name: 'On the way', lat: 53.43, lng: 10.4 });
|
||||
expect(body.days[0].stops[1]).not.toHaveProperty('carrier');
|
||||
expect(body.days[1].stops[1].carrier.role).toBe('return');
|
||||
expect(body.days[1].distanceMetres).toBe(120_000);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -354,6 +354,30 @@ describe('removeAlbumLink', () => {
|
||||
expect((result as any).error.status).toBe(404);
|
||||
});
|
||||
|
||||
it('MEM-UNIFIED-020a: treats an absent scoped link as a no-op inside the transaction', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const findScoped = vi.spyOn(tripAlbumLinksRepo, 'findScoped').mockImplementationOnce(async () => {
|
||||
expect(tripAlbumLinksRepo.getEntityManager().isInTransaction()).toBe(true);
|
||||
return null;
|
||||
});
|
||||
const listPhotos = vi.spyOn(tripPhotosRepo, 'listPhotoIdsForAlbumLink');
|
||||
const deletePhotos = vi.spyOn(tripPhotosRepo, 'deleteForAlbumLink');
|
||||
const deleteLink = vi.spyOn(tripAlbumLinksRepo, 'deleteScoped');
|
||||
try {
|
||||
expect(expectSuccess(await removeAlbumLink(String(trip.id), '17', user.id))).toBe(true);
|
||||
expect(findScoped).toHaveBeenCalledWith(17, trip.id, user.id);
|
||||
expect(listPhotos).not.toHaveBeenCalled();
|
||||
expect(deletePhotos).not.toHaveBeenCalled();
|
||||
expect(deleteLink).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
findScoped.mockRestore();
|
||||
listPhotos.mockRestore();
|
||||
deletePhotos.mockRestore();
|
||||
deleteLink.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('MEM-UNIFIED-020: UM8/UM9/UM10 — the transaction removes the link and every trip_photos row it owned', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
@@ -384,6 +408,7 @@ describe('removeAlbumLink', () => {
|
||||
// The orphaned trek_photos row is reclaimed too (TrekPhotoRegistrationService.deleteIfOrphan, PH10/PH11).
|
||||
const orphan = await findRow(orm, TrekPhotos, { id: photoRow?.photo_id });
|
||||
expect(orphan).toBeNull();
|
||||
expect(expectSuccess(await removeAlbumLink(String(trip.id), String(linkRow.id), user.id))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
|
||||
import { WebauthnConfigService, originWithinRpScope } from '../../../src/nest/auth/webauthn-config.service';
|
||||
import {
|
||||
WebauthnConfigService,
|
||||
originWithinRpScope,
|
||||
passkeyVerificationOrigins,
|
||||
} from '../../../src/nest/auth/webauthn-config.service';
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { assert, describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* webauthn-config.service.test.ts
|
||||
@@ -182,6 +186,44 @@ describe('WebauthnConfigService.resolve', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('passkeyVerificationOrigins', () => {
|
||||
it('WAC-019: keeps the application origin when the relying party ID is shared', async () => {
|
||||
appUrlRef.value = 'https://trek.example.org';
|
||||
settingsStore.set('webauthn_rp_id', 'example.org');
|
||||
const config = await svc.resolve();
|
||||
assert(config);
|
||||
|
||||
expect(passkeyVerificationOrigins(config, 'https://example.org')).toEqual(['https://trek.example.org']);
|
||||
expect(passkeyVerificationOrigins(config, 'https://trek.example.org')).toEqual(['https://trek.example.org']);
|
||||
});
|
||||
|
||||
it('WAC-020: tolerates a proxy scheme and port on the configured RP host', async () => {
|
||||
appUrlRef.value = 'http://trek.example.org:3001';
|
||||
const config = await svc.resolve();
|
||||
assert(config);
|
||||
|
||||
expect(passkeyVerificationOrigins(config, 'https://trek.example.org:8443')).toEqual([
|
||||
'http://trek.example.org:3001',
|
||||
'https://trek.example.org:8443',
|
||||
]);
|
||||
expect(passkeyVerificationOrigins(config, 'https://other.trek.example.org')).toEqual(config.origins);
|
||||
expect(passkeyVerificationOrigins(config, 'https://unrelated.example.net')).toEqual(config.origins);
|
||||
expect(passkeyVerificationOrigins(config, null)).toEqual(config.origins);
|
||||
});
|
||||
|
||||
it('WAC-021: applies an explicit list exactly, including its ports', async () => {
|
||||
settingsStore.set('webauthn_rp_id', 'example.org');
|
||||
settingsStore.set('webauthn_origins', 'https://example.org, https://trek.example.org');
|
||||
const config = await svc.resolve();
|
||||
assert(config);
|
||||
|
||||
expect(passkeyVerificationOrigins(config, 'https://example.org:8443')).toEqual([
|
||||
'https://example.org',
|
||||
'https://trek.example.org',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
// The scope rule mirrors what the browser enforces for a ceremony: https-only
|
||||
// (http for loopback dev), hostname equal to the RP ID or a subdomain of it.
|
||||
// Anything laxer would weaken origin binding, so each edge is pinned.
|
||||
|
||||
@@ -82,6 +82,7 @@ describe('paths', () => {
|
||||
delete process.env.TREK_PLUGIN_PERMISSIONS;
|
||||
const args = pluginPermissionArgs('flight-tracker');
|
||||
expect(args).toContain('--permission');
|
||||
expect(args).toContain('--no-experimental-sqlite');
|
||||
// read is scoped to the compiled server dir + this plugin's own code dir…
|
||||
expect(args.some((a) => a === `--allow-fs-read=${serverCodeRoot()}`)).toBe(true);
|
||||
expect(args.some((a) => a === `--allow-fs-read=${pluginCodeDir('flight-tracker')}`)).toBe(true);
|
||||
|
||||
+1
-1
@@ -110,7 +110,7 @@
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-config-flat-gitignore": "^2.4.0",
|
||||
"eslint-config-prettier": "^10.1.9",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"prettier": "3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"tsdown": "^0.23.7",
|
||||
|
||||
@@ -114,10 +114,6 @@ export const NOT_PLURAL = [
|
||||
{ key: 'dawarich.duration.hours', because: 'a duration in a unit symbol (h), the same for any number' },
|
||||
{ key: 'dawarich.duration.hoursMinutes', because: 'a duration in unit symbols (h, min), the same for any number' },
|
||||
{ key: 'files.uploadErrorSize', because: 'a size limit in a unit symbol (MB), the same for any number' },
|
||||
{
|
||||
key: 'native.plans.photos',
|
||||
because: 'an estimate of photos a plan holds, always in the thousands, so no singular ever shows',
|
||||
},
|
||||
{
|
||||
key: 'native.plans.aiPerMonth',
|
||||
because: 'a monthly document allowance before a unit ("25 / month"), always in the tens',
|
||||
|
||||
@@ -49,6 +49,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordLabel': 'كلمة المرور',
|
||||
'native.claim.passwordHint': '8 أحرف على الأقل. يجب أن تحتوي كلمة المرور على حرف كبير وحرف صغير ورقم ورمز خاص.',
|
||||
'native.claim.subscribe': 'اشترك مقابل {price}',
|
||||
'native.claim.completeSetup': 'إكمال الإعداد',
|
||||
'native.claim.cancelled': 'تم إلغاء الشراء.',
|
||||
'native.claim.failed': 'لم تتم عملية الشراء. حاول مرة أخرى.',
|
||||
'native.claim.redeemFailed': 'تعذّر علينا إعداد TREK الخاص بك. حاول مرة أخرى.',
|
||||
@@ -200,9 +201,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'في كل خطة',
|
||||
'native.plans.yearlyIs': '{price} سنويًا، ألغِ في أي وقت',
|
||||
'native.plans.monthlyIs': 'أي {price} شهريًا',
|
||||
'native.plans.photos': '≈ {n} صورة',
|
||||
'native.plans.storageFairUse': 'تخزين وفق الاستخدام العادل',
|
||||
'native.plans.aiPerMonth': '{n} / شهر',
|
||||
'native.plans.aiNone': 'لا شيء',
|
||||
'native.plans.aiNone': 'غير مشمول',
|
||||
'native.plans.included': 'مشمول',
|
||||
'native.plans.planned': 'مخطط له',
|
||||
'native.plans.assistant': 'مساعد الذكاء الاصطناعي',
|
||||
'native.plans.mailImport': 'استيراد البريد تلقائيًا',
|
||||
'native.plans.aiLabel': 'مستندات الذكاء الاصطناعي',
|
||||
'native.plans.choose': 'اختر {trip}',
|
||||
'native.plans.termsShort': 'شروط الاستخدام (EULA)',
|
||||
|
||||
@@ -49,6 +49,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordLabel': 'Parol',
|
||||
'native.claim.passwordHint': 'Ən azı 8 simvol. Parolda böyük hərf, kiçik hərf, rəqəm və xüsusi simvol olmalıdır.',
|
||||
'native.claim.subscribe': '{price} qarşılığında abunə ol',
|
||||
'native.claim.completeSetup': 'Quraşdırmanı tamamla',
|
||||
'native.claim.cancelled': 'Alış ləğv edildi.',
|
||||
'native.claim.failed': 'Alış baş tutmadı. Zəhmət olmasa yenidən cəhd edin.',
|
||||
'native.claim.redeemFailed': 'TREK-inizi hazırlaya bilmədik. Zəhmət olmasa yenidən cəhd edin.',
|
||||
@@ -205,9 +206,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'hər planda',
|
||||
'native.plans.yearlyIs': 'İllik {price}, istənilən vaxt ləğv edin',
|
||||
'native.plans.monthlyIs': 'Bu, ayda {price} edir',
|
||||
'native.plans.photos': '≈ {n} foto',
|
||||
'native.plans.storageFairUse': 'Ədalətli istifadə yaddaşı',
|
||||
'native.plans.aiPerMonth': '{n} / ay',
|
||||
'native.plans.aiNone': 'Yoxdur',
|
||||
'native.plans.aiNone': 'Daxil deyil',
|
||||
'native.plans.included': 'Daxildir',
|
||||
'native.plans.planned': 'Planlaşdırılır',
|
||||
'native.plans.assistant': 'Sİ köməkçisi',
|
||||
'native.plans.mailImport': 'Avtomatik e-poçt idxalı',
|
||||
'native.plans.aiLabel': 'Sİ sənədləri',
|
||||
'native.plans.choose': '{trip} seçin',
|
||||
'native.plans.termsShort': 'İstifadə şərtləri (EULA)',
|
||||
|
||||
@@ -50,6 +50,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Pelo menos 8 caracteres. A senha deve ter maiúscula, minúscula, número e um caractere especial.',
|
||||
'native.claim.subscribe': 'Assinar por {price}',
|
||||
'native.claim.completeSetup': 'Concluir configuração',
|
||||
'native.claim.cancelled': 'Compra cancelada.',
|
||||
'native.claim.failed': 'A compra não foi concluída. Tente novamente.',
|
||||
'native.claim.redeemFailed': 'Não conseguimos preparar seu TREK. Tente novamente.',
|
||||
@@ -207,9 +208,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'em todos os planos',
|
||||
'native.plans.yearlyIs': '{price} por ano, cancele quando quiser',
|
||||
'native.plans.monthlyIs': 'São {price} por mês',
|
||||
'native.plans.photos': '≈ {n} fotos',
|
||||
'native.plans.storageFairUse': 'Armazenamento de uso justo',
|
||||
'native.plans.aiPerMonth': '{n} / mês',
|
||||
'native.plans.aiNone': 'Nenhum',
|
||||
'native.plans.aiNone': 'Não incluído',
|
||||
'native.plans.included': 'Incluído',
|
||||
'native.plans.planned': 'Planejado',
|
||||
'native.plans.assistant': 'Assistente de IA',
|
||||
'native.plans.mailImport': 'Importação automática de e-mails',
|
||||
'native.plans.aiLabel': 'Documentos de IA',
|
||||
'native.plans.choose': 'Escolher {trip}',
|
||||
'native.plans.termsShort': 'Termos de uso (EULA)',
|
||||
|
||||
@@ -50,6 +50,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Almenys 8 caràcters. La contrasenya ha de contenir majúscules, minúscules, números i un caràcter especial.',
|
||||
'native.claim.subscribe': 'Subscriu-te per {price}',
|
||||
'native.claim.completeSetup': 'Completa la configuració',
|
||||
'native.claim.cancelled': 'Compra cancel·lada.',
|
||||
'native.claim.failed': 'La compra no s’ha completat. Torna-ho a provar.',
|
||||
'native.claim.redeemFailed': 'No hem pogut preparar el teu TREK. Torna-ho a provar.',
|
||||
@@ -208,9 +209,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'en tots els plans',
|
||||
'native.plans.yearlyIs': '{price} l’any, cancel·la quan vulguis',
|
||||
'native.plans.monthlyIs': 'Són {price} al mes',
|
||||
'native.plans.photos': '≈ {n} fotos',
|
||||
'native.plans.storageFairUse': 'Emmagatzematge d’ús raonable',
|
||||
'native.plans.aiPerMonth': '{n} / mes',
|
||||
'native.plans.aiNone': 'Cap',
|
||||
'native.plans.aiNone': 'No inclòs',
|
||||
'native.plans.included': 'Inclòs',
|
||||
'native.plans.planned': 'Previst',
|
||||
'native.plans.assistant': 'Assistent d’IA',
|
||||
'native.plans.mailImport': 'Importació automàtica de correus',
|
||||
'native.plans.aiLabel': 'Documents IA',
|
||||
'native.plans.choose': 'Tria {trip}',
|
||||
'native.plans.termsShort': 'Condicions d’ús (EULA)',
|
||||
|
||||
@@ -49,6 +49,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordLabel': 'Heslo',
|
||||
'native.claim.passwordHint': 'Alespoň 8 znaků. Heslo musí obsahovat velké a malé písmeno, číslici a speciální znak.',
|
||||
'native.claim.subscribe': 'Předplatit za {price}',
|
||||
'native.claim.completeSetup': 'Dokončit nastavení',
|
||||
'native.claim.cancelled': 'Nákup zrušen.',
|
||||
'native.claim.failed': 'Nákup se nezdařil. Zkuste to znovu.',
|
||||
'native.claim.redeemFailed': 'Nepodařilo se připravit váš TREK. Zkuste to znovu.',
|
||||
@@ -201,9 +202,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'v každém tarifu',
|
||||
'native.plans.yearlyIs': '{price} ročně, zrušení kdykoli',
|
||||
'native.plans.monthlyIs': 'To je {price} měsíčně',
|
||||
'native.plans.photos': '≈ {n} fotek',
|
||||
'native.plans.storageFairUse': 'Úložiště v režimu férového využití',
|
||||
'native.plans.aiPerMonth': '{n} / měsíc',
|
||||
'native.plans.aiNone': 'Žádné',
|
||||
'native.plans.aiNone': 'Není součástí',
|
||||
'native.plans.included': 'Součástí',
|
||||
'native.plans.planned': 'Plánováno',
|
||||
'native.plans.assistant': 'Asistent AI',
|
||||
'native.plans.mailImport': 'Automatický import e-mailů',
|
||||
'native.plans.aiLabel': 'Dokumenty AI',
|
||||
'native.plans.choose': 'Vybrat: {trip}',
|
||||
'native.plans.termsShort': 'Podmínky použití (EULA)',
|
||||
|
||||
@@ -51,6 +51,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Mindestens 8 Zeichen. Passwort muss Groß-, Kleinbuchstaben, eine Zahl und ein Sonderzeichen enthalten.',
|
||||
'native.claim.subscribe': 'Abonnieren für {price}',
|
||||
'native.claim.completeSetup': 'Einrichtung abschließen',
|
||||
'native.claim.cancelled': 'Kauf abgebrochen.',
|
||||
'native.claim.failed': 'Der Kauf hat nicht geklappt. Bitte versuch es erneut.',
|
||||
'native.claim.redeemFailed': 'Wir konnten dein TREK nicht einrichten. Bitte versuch es erneut.',
|
||||
@@ -211,9 +212,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'in jedem Tarif',
|
||||
'native.plans.yearlyIs': 'Jährlich {price}, jederzeit kündbar',
|
||||
'native.plans.monthlyIs': 'Das sind {price} im Monat',
|
||||
'native.plans.photos': '≈ {n} Fotos',
|
||||
'native.plans.storageFairUse': 'Speicher unter Fair Use',
|
||||
'native.plans.aiPerMonth': '{n} / Monat',
|
||||
'native.plans.aiNone': 'Keine',
|
||||
'native.plans.aiNone': 'Nicht enthalten',
|
||||
'native.plans.included': 'Enthalten',
|
||||
'native.plans.planned': 'Geplant',
|
||||
'native.plans.assistant': 'KI-Assistent',
|
||||
'native.plans.mailImport': 'Automatischer E-Mail-Import',
|
||||
'native.plans.aiLabel': 'KI-Dokumente',
|
||||
'native.plans.choose': '{trip} wählen',
|
||||
'native.plans.termsShort': 'Nutzungsbedingungen (EULA)',
|
||||
|
||||
@@ -50,6 +50,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'At least 8 characters. Password must contain uppercase, lowercase, a number, and a special character.',
|
||||
'native.claim.subscribe': 'Subscribe for {price}',
|
||||
'native.claim.completeSetup': 'Complete setup',
|
||||
'native.claim.cancelled': 'Purchase cancelled.',
|
||||
'native.claim.failed': 'The purchase did not go through. Please try again.',
|
||||
'native.claim.redeemFailed': 'We could not set up your TREK. Please try again.',
|
||||
@@ -206,9 +207,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'in every plan',
|
||||
'native.plans.yearlyIs': 'Yearly {price}, cancel anytime',
|
||||
'native.plans.monthlyIs': 'That is {price} a month',
|
||||
'native.plans.photos': '≈ {n} photos',
|
||||
'native.plans.storageFairUse': 'Storage fair use',
|
||||
'native.plans.aiPerMonth': '{n} / month',
|
||||
'native.plans.aiNone': 'None',
|
||||
'native.plans.aiNone': 'Not included',
|
||||
'native.plans.included': 'Included',
|
||||
'native.plans.planned': 'Planned',
|
||||
'native.plans.assistant': 'AI Assistant',
|
||||
'native.plans.mailImport': 'Automated Mail Import',
|
||||
'native.plans.aiLabel': 'AI documents',
|
||||
'native.plans.choose': 'Choose {trip}',
|
||||
'native.plans.termsShort': 'Terms of Use (EULA)',
|
||||
|
||||
@@ -50,6 +50,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Al menos 8 caracteres. La contraseña debe contener mayúsculas, minúsculas, números y un carácter especial.',
|
||||
'native.claim.subscribe': 'Suscribirse por {price}',
|
||||
'native.claim.completeSetup': 'Completar configuración',
|
||||
'native.claim.cancelled': 'Compra cancelada.',
|
||||
'native.claim.failed': 'La compra no se completó. Inténtalo de nuevo.',
|
||||
'native.claim.redeemFailed': 'No pudimos preparar tu TREK. Inténtalo de nuevo.',
|
||||
@@ -206,9 +207,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'en todos los planes',
|
||||
'native.plans.yearlyIs': '{price} al año, cancela cuando quieras',
|
||||
'native.plans.monthlyIs': 'Son {price} al mes',
|
||||
'native.plans.photos': '≈ {n} fotos',
|
||||
'native.plans.storageFairUse': 'Almacenamiento de uso razonable',
|
||||
'native.plans.aiPerMonth': '{n} / mes',
|
||||
'native.plans.aiNone': 'Ninguno',
|
||||
'native.plans.aiNone': 'No incluido',
|
||||
'native.plans.included': 'Incluido',
|
||||
'native.plans.planned': 'Previsto',
|
||||
'native.plans.assistant': 'Asistente de IA',
|
||||
'native.plans.mailImport': 'Importación automática de correo',
|
||||
'native.plans.aiLabel': 'Documentos IA',
|
||||
'native.plans.choose': 'Elegir {trip}',
|
||||
'native.plans.termsShort': 'Condiciones de uso (EULA)',
|
||||
|
||||
@@ -49,6 +49,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordLabel': 'Parool',
|
||||
'native.claim.passwordHint': 'Vähemalt 8 märki. Parool peab sisaldama suur- ja väiketähte, numbrit ning erimärki.',
|
||||
'native.claim.subscribe': 'Telli hinnaga {price}',
|
||||
'native.claim.completeSetup': 'Lõpeta seadistamine',
|
||||
'native.claim.cancelled': 'Ost tühistatud.',
|
||||
'native.claim.failed': 'Ost ei õnnestunud. Proovi uuesti.',
|
||||
'native.claim.redeemFailed': 'Me ei saanud sinu TREK-i seadistada. Proovi uuesti.',
|
||||
@@ -203,9 +204,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'igas paketis',
|
||||
'native.plans.yearlyIs': '{price} aastas, tühista igal ajal',
|
||||
'native.plans.monthlyIs': 'See on {price} kuus',
|
||||
'native.plans.photos': '≈ {n} fotot',
|
||||
'native.plans.storageFairUse': 'Õiglase kasutuse salvestusruum',
|
||||
'native.plans.aiPerMonth': '{n} / kuus',
|
||||
'native.plans.aiNone': 'Puudub',
|
||||
'native.plans.aiNone': 'Ei sisaldu',
|
||||
'native.plans.included': 'Sisaldub',
|
||||
'native.plans.planned': 'Plaanis',
|
||||
'native.plans.assistant': 'AI-assistent',
|
||||
'native.plans.mailImport': 'Automaatne e-kirjade import',
|
||||
'native.plans.aiLabel': 'TI-dokumendid',
|
||||
'native.plans.choose': 'Vali {trip}',
|
||||
'native.plans.termsShort': 'Kasutustingimused (EULA)',
|
||||
|
||||
@@ -51,6 +51,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Au moins 8 caractères. Le mot de passe doit contenir des majuscules, des minuscules, un chiffre et un caractère spécial.',
|
||||
'native.claim.subscribe': 'S’abonner pour {price}',
|
||||
'native.claim.completeSetup': 'Terminer la configuration',
|
||||
'native.claim.cancelled': 'Achat annulé.',
|
||||
'native.claim.failed': 'L’achat n’a pas abouti. Réessayez.',
|
||||
'native.claim.redeemFailed': 'Nous n’avons pas pu préparer votre TREK. Réessayez.',
|
||||
@@ -210,9 +211,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'dans chaque offre',
|
||||
'native.plans.yearlyIs': '{price} par an, résiliable à tout moment',
|
||||
'native.plans.monthlyIs': 'Soit {price} par mois',
|
||||
'native.plans.photos': '≈ {n} photos', // same-as-en
|
||||
'native.plans.storageFairUse': 'Stockage en usage raisonnable',
|
||||
'native.plans.aiPerMonth': '{n} / mois',
|
||||
'native.plans.aiNone': 'Aucun',
|
||||
'native.plans.aiNone': 'Non inclus',
|
||||
'native.plans.included': 'Inclus',
|
||||
'native.plans.planned': 'Prévu',
|
||||
'native.plans.assistant': 'Assistant IA',
|
||||
'native.plans.mailImport': 'Import automatique des e-mails',
|
||||
'native.plans.aiLabel': 'Documents IA',
|
||||
'native.plans.choose': 'Choisir {trip}',
|
||||
'native.plans.termsShort': 'Conditions d’utilisation (EULA)',
|
||||
|
||||
@@ -51,6 +51,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Τουλάχιστον 8 χαρακτήρες. Ο κωδικός πρέπει να περιέχει κεφαλαία, πεζά, έναν αριθμό και έναν ειδικό χαρακτήρα.',
|
||||
'native.claim.subscribe': 'Εγγραφή για {price}',
|
||||
'native.claim.completeSetup': 'Ολοκλήρωση ρύθμισης',
|
||||
'native.claim.cancelled': 'Η αγορά ακυρώθηκε.',
|
||||
'native.claim.failed': 'Η αγορά δεν ολοκληρώθηκε. Δοκιμάστε ξανά.',
|
||||
'native.claim.redeemFailed': 'Δεν μπορέσαμε να ετοιμάσουμε το TREK σας. Δοκιμάστε ξανά.',
|
||||
@@ -213,9 +214,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'σε κάθε πακέτο',
|
||||
'native.plans.yearlyIs': '{price} τον χρόνο, ακύρωση οποτεδήποτε',
|
||||
'native.plans.monthlyIs': 'Δηλαδή {price} τον μήνα',
|
||||
'native.plans.photos': '≈ {n} φωτογραφίες',
|
||||
'native.plans.storageFairUse': 'Αποθήκευση με εύλογη χρήση',
|
||||
'native.plans.aiPerMonth': '{n} / μήνα',
|
||||
'native.plans.aiNone': 'Κανένα',
|
||||
'native.plans.aiNone': 'Δεν περιλαμβάνεται',
|
||||
'native.plans.included': 'Περιλαμβάνεται',
|
||||
'native.plans.planned': 'Προγραμματίζεται',
|
||||
'native.plans.assistant': 'Βοηθός AI',
|
||||
'native.plans.mailImport': 'Αυτόματη εισαγωγή email',
|
||||
'native.plans.aiLabel': 'Έγγραφα AI',
|
||||
'native.plans.choose': 'Επιλογή: {trip}',
|
||||
'native.plans.termsShort': 'Όροι χρήσης (EULA)',
|
||||
|
||||
@@ -49,6 +49,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordLabel': 'סיסמה',
|
||||
'native.claim.passwordHint': 'לפחות 8 תווים. הסיסמה חייבת להכיל אות גדולה, אות קטנה, ספרה ותו מיוחד.',
|
||||
'native.claim.subscribe': 'הרשמה תמורת {price}',
|
||||
'native.claim.completeSetup': 'השלמת ההגדרה',
|
||||
'native.claim.cancelled': 'הרכישה בוטלה.',
|
||||
'native.claim.failed': 'הרכישה לא הושלמה. אנא נסו שוב.',
|
||||
'native.claim.redeemFailed': 'לא הצלחנו להכין את ה-TREK שלכם. אנא נסו שוב.',
|
||||
@@ -199,9 +200,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'בכל חבילה',
|
||||
'native.plans.yearlyIs': '{price} לשנה, ביטול בכל עת',
|
||||
'native.plans.monthlyIs': 'כלומר {price} לחודש',
|
||||
'native.plans.photos': '≈ {n} תמונות',
|
||||
'native.plans.storageFairUse': 'אחסון בשימוש הוגן',
|
||||
'native.plans.aiPerMonth': '{n} / חודש',
|
||||
'native.plans.aiNone': 'אין',
|
||||
'native.plans.aiNone': 'לא כלול',
|
||||
'native.plans.included': 'כלול',
|
||||
'native.plans.planned': 'מתוכנן',
|
||||
'native.plans.assistant': 'עוזר AI',
|
||||
'native.plans.mailImport': 'ייבוא דוא״ל אוטומטי',
|
||||
'native.plans.aiLabel': 'מסמכי AI',
|
||||
'native.plans.choose': 'בחירת {trip}',
|
||||
'native.plans.termsShort': 'תנאי שימוש (EULA)',
|
||||
|
||||
@@ -51,6 +51,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Legalább 8 karakter. A jelszónak tartalmaznia kell nagybetűt, kisbetűt, számot és speciális karaktert.',
|
||||
'native.claim.subscribe': 'Előfizetés ennyiért: {price}',
|
||||
'native.claim.completeSetup': 'Beállítás befejezése',
|
||||
'native.claim.cancelled': 'Vásárlás megszakítva.',
|
||||
'native.claim.failed': 'A vásárlás nem sikerült. Próbáld újra.',
|
||||
'native.claim.redeemFailed': 'Nem sikerült beállítani a TREK-edet. Próbáld újra.',
|
||||
@@ -209,9 +210,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'minden csomagban',
|
||||
'native.plans.yearlyIs': 'Évente {price}, bármikor lemondható',
|
||||
'native.plans.monthlyIs': 'Ez havonta {price}',
|
||||
'native.plans.photos': '≈ {n} fotó',
|
||||
'native.plans.storageFairUse': 'Tárhely méltányos használatra',
|
||||
'native.plans.aiPerMonth': '{n} / hó',
|
||||
'native.plans.aiNone': 'Nincs',
|
||||
'native.plans.aiNone': 'Nem tartalmazza',
|
||||
'native.plans.included': 'Tartalmazza',
|
||||
'native.plans.planned': 'Tervezett',
|
||||
'native.plans.assistant': 'MI-asszisztens',
|
||||
'native.plans.mailImport': 'Automatikus e-mail-importálás',
|
||||
'native.plans.aiLabel': 'MI-dokumentumok',
|
||||
'native.plans.choose': '{trip} választása',
|
||||
'native.plans.termsShort': 'Felhasználási feltételek (EULA)',
|
||||
|
||||
@@ -50,6 +50,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Minimal 8 karakter. Kata sandi harus mengandung huruf besar, huruf kecil, angka, dan karakter khusus.',
|
||||
'native.claim.subscribe': 'Berlangganan seharga {price}',
|
||||
'native.claim.completeSetup': 'Selesaikan penyiapan',
|
||||
'native.claim.cancelled': 'Pembelian dibatalkan.',
|
||||
'native.claim.failed': 'Pembelian tidak berhasil. Silakan coba lagi.',
|
||||
'native.claim.redeemFailed': 'Kami tidak dapat menyiapkan TREK Anda. Silakan coba lagi.',
|
||||
@@ -208,9 +209,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'di setiap paket',
|
||||
'native.plans.yearlyIs': '{price} per tahun, batalkan kapan saja',
|
||||
'native.plans.monthlyIs': 'Itu {price} per bulan',
|
||||
'native.plans.photos': '≈ {n} foto',
|
||||
'native.plans.storageFairUse': 'Penyimpanan penggunaan wajar',
|
||||
'native.plans.aiPerMonth': '{n} / bulan',
|
||||
'native.plans.aiNone': 'Tidak ada',
|
||||
'native.plans.aiNone': 'Tidak disertakan',
|
||||
'native.plans.included': 'Disertakan',
|
||||
'native.plans.planned': 'Direncanakan',
|
||||
'native.plans.assistant': 'Asisten AI',
|
||||
'native.plans.mailImport': 'Impor email otomatis',
|
||||
'native.plans.aiLabel': 'Dokumen AI',
|
||||
'native.plans.choose': 'Pilih {trip}',
|
||||
'native.plans.termsShort': 'Ketentuan Penggunaan (EULA)',
|
||||
|
||||
@@ -51,6 +51,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Almeno 8 caratteri. La password deve contenere lettere maiuscole, minuscole, un numero e un carattere speciale.',
|
||||
'native.claim.subscribe': 'Abbonati per {price}',
|
||||
'native.claim.completeSetup': 'Completa la configurazione',
|
||||
'native.claim.cancelled': 'Acquisto annullato.',
|
||||
'native.claim.failed': 'L’acquisto non è andato a buon fine. Riprova.',
|
||||
'native.claim.redeemFailed': 'Non siamo riusciti a preparare il tuo TREK. Riprova.',
|
||||
@@ -210,9 +211,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'in ogni piano',
|
||||
'native.plans.yearlyIs': '{price} all’anno, disdici quando vuoi',
|
||||
'native.plans.monthlyIs': 'Sono {price} al mese',
|
||||
'native.plans.photos': '≈ {n} foto',
|
||||
'native.plans.storageFairUse': 'Spazio con uso ragionevole',
|
||||
'native.plans.aiPerMonth': '{n} / mese',
|
||||
'native.plans.aiNone': 'Nessuno',
|
||||
'native.plans.aiNone': 'Non incluso',
|
||||
'native.plans.included': 'Incluso',
|
||||
'native.plans.planned': 'Previsto',
|
||||
'native.plans.assistant': 'Assistente IA',
|
||||
'native.plans.mailImport': 'Importazione automatica delle e-mail',
|
||||
'native.plans.aiLabel': 'Documenti IA',
|
||||
'native.plans.choose': 'Scegli {trip}',
|
||||
'native.plans.termsShort': 'Condizioni d’uso (EULA)',
|
||||
|
||||
@@ -49,6 +49,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordLabel': 'パスワード',
|
||||
'native.claim.passwordHint': '8文字以上。大文字・小文字・数字・記号を含めてください。',
|
||||
'native.claim.subscribe': '{price} で登録',
|
||||
'native.claim.completeSetup': '設定を完了',
|
||||
'native.claim.cancelled': '購入をキャンセルしました。',
|
||||
'native.claim.failed': '購入できませんでした。もう一度お試しください。',
|
||||
'native.claim.redeemFailed': 'TREKを用意できませんでした。もう一度お試しください。',
|
||||
@@ -205,9 +206,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'すべてのプランで',
|
||||
'native.plans.yearlyIs': '年額 {price}、いつでも解約可能',
|
||||
'native.plans.monthlyIs': '月あたり {price}',
|
||||
'native.plans.photos': '約 {n} 枚の写真',
|
||||
'native.plans.storageFairUse': 'ストレージの公平利用枠',
|
||||
'native.plans.aiPerMonth': '{n} / 月',
|
||||
'native.plans.aiNone': 'なし',
|
||||
'native.plans.aiNone': '対象外',
|
||||
'native.plans.included': '利用可能',
|
||||
'native.plans.planned': '提供予定',
|
||||
'native.plans.assistant': 'AI アシスタント',
|
||||
'native.plans.mailImport': 'メールの自動取り込み',
|
||||
'native.plans.aiLabel': 'AI ドキュメント',
|
||||
'native.plans.choose': '{trip}を選ぶ',
|
||||
'native.plans.termsShort': '利用規約 (EULA)',
|
||||
|
||||
@@ -48,6 +48,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordLabel': '비밀번호',
|
||||
'native.claim.passwordHint': '8자 이상. 비밀번호는 대문자, 소문자, 숫자, 특수문자를 포함해야 합니다.',
|
||||
'native.claim.subscribe': '{price}에 구독',
|
||||
'native.claim.completeSetup': '설정 완료',
|
||||
'native.claim.cancelled': '구매가 취소되었습니다.',
|
||||
'native.claim.failed': '구매가 완료되지 않았습니다. 다시 시도하세요.',
|
||||
'native.claim.redeemFailed': 'TREK을 준비하지 못했습니다. 다시 시도하세요.',
|
||||
@@ -202,9 +203,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': '모든 요금제에 포함',
|
||||
'native.plans.yearlyIs': '연 {price}, 언제든 해지',
|
||||
'native.plans.monthlyIs': '월 {price}에 해당',
|
||||
'native.plans.photos': '약 {n}장의 사진',
|
||||
'native.plans.storageFairUse': '공정 사용 저장 공간',
|
||||
'native.plans.aiPerMonth': '{n} / 월',
|
||||
'native.plans.aiNone': '없음',
|
||||
'native.plans.aiNone': '미포함',
|
||||
'native.plans.included': '포함',
|
||||
'native.plans.planned': '예정',
|
||||
'native.plans.assistant': 'AI 어시스턴트',
|
||||
'native.plans.mailImport': '자동 이메일 가져오기',
|
||||
'native.plans.aiLabel': 'AI 문서',
|
||||
'native.plans.choose': '{trip} 선택',
|
||||
'native.plans.termsShort': '이용 약관 (EULA)',
|
||||
|
||||
@@ -50,6 +50,7 @@ const native: TranslationStrings = {
|
||||
'native.claim.passwordHint':
|
||||
'Minstens 8 tekens. Wachtwoord moet hoofdletters, kleine letters, een cijfer en een speciaal teken bevatten.',
|
||||
'native.claim.subscribe': 'Abonneren voor {price}',
|
||||
'native.claim.completeSetup': 'Installatie voltooien',
|
||||
'native.claim.cancelled': 'Aankoop geannuleerd.',
|
||||
'native.claim.failed': 'De aankoop is niet gelukt. Probeer het opnieuw.',
|
||||
'native.claim.redeemFailed': 'We konden je TREK niet klaarzetten. Probeer het opnieuw.',
|
||||
@@ -208,9 +209,13 @@ const native: TranslationStrings = {
|
||||
'native.plans.inEveryPlan': 'in elk abonnement',
|
||||
'native.plans.yearlyIs': '{price} per jaar, altijd opzegbaar',
|
||||
'native.plans.monthlyIs': 'Dat is {price} per maand',
|
||||
'native.plans.photos': '≈ {n} foto’s',
|
||||
'native.plans.storageFairUse': 'Opslag bij redelijk gebruik',
|
||||
'native.plans.aiPerMonth': '{n} / maand',
|
||||
'native.plans.aiNone': 'Geen',
|
||||
'native.plans.aiNone': 'Niet inbegrepen',
|
||||
'native.plans.included': 'Inbegrepen',
|
||||
'native.plans.planned': 'Gepland',
|
||||
'native.plans.assistant': 'AI-assistent',
|
||||
'native.plans.mailImport': 'Automatische e-mailimport',
|
||||
'native.plans.aiLabel': 'AI-documenten',
|
||||
'native.plans.choose': '{trip} kiezen',
|
||||
'native.plans.termsShort': 'Gebruiksvoorwaarden (EULA)',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user