diff --git a/backend/src/repositories/mobileAppReleaseRepository.ts b/backend/src/repositories/mobileAppReleaseRepository.ts index 20a80daf..6359d109 100644 --- a/backend/src/repositories/mobileAppReleaseRepository.ts +++ b/backend/src/repositories/mobileAppReleaseRepository.ts @@ -216,10 +216,25 @@ export async function listReleases(filters: { return { items: rows.map(mapRelease), total }; } +export async function findByPlatformChannelVersionCode( + platform: MobilePlatform, + channel: MobileChannel, + versionCode: number +): Promise { + const rows = await query( + `SELECT ${RELEASE_COLS} FROM mobile_app_releases + WHERE platform = $1 AND channel = $2 AND version_code = $3 + LIMIT 1`, + [platform, channel, versionCode] + ); + return rows[0] ? mapRelease(rows[0]) : null; +} + export async function updateRelease( id: string, patch: Partial<{ versionName: string; + versionCode: number; previousVersionName: string | null; whatsNew: string; bugFixes: string; @@ -237,24 +252,26 @@ export async function updateRelease( const rows = await query( `UPDATE mobile_app_releases SET version_name = COALESCE($2, version_name), - previous_version_name = CASE WHEN $3::boolean THEN $4 ELSE previous_version_name END, - whats_new = COALESCE($5, whats_new), - bug_fixes = COALESCE($6, bug_fixes), - update_policy = COALESCE($7, update_policy), - rollout_percent = COALESCE($8, rollout_percent), - status = COALESCE($9, status), - package_name = CASE WHEN $10::boolean THEN $11 ELSE package_name END, - storage_key = CASE WHEN $12::boolean THEN $13 ELSE storage_key END, - file_size_bytes = CASE WHEN $14::boolean THEN $15 ELSE file_size_bytes END, - sha256 = CASE WHEN $16::boolean THEN $17 ELSE sha256 END, - signing_cert_sha256 = CASE WHEN $18::boolean THEN $19 ELSE signing_cert_sha256 END, - published_at = CASE WHEN $20::boolean THEN $21 ELSE published_at END, + version_code = COALESCE($3, version_code), + previous_version_name = CASE WHEN $4::boolean THEN $5 ELSE previous_version_name END, + whats_new = COALESCE($6, whats_new), + bug_fixes = COALESCE($7, bug_fixes), + update_policy = COALESCE($8, update_policy), + rollout_percent = COALESCE($9, rollout_percent), + status = COALESCE($10, status), + package_name = CASE WHEN $11::boolean THEN $12 ELSE package_name END, + storage_key = CASE WHEN $13::boolean THEN $14 ELSE storage_key END, + file_size_bytes = CASE WHEN $15::boolean THEN $16 ELSE file_size_bytes END, + sha256 = CASE WHEN $17::boolean THEN $18 ELSE sha256 END, + signing_cert_sha256 = CASE WHEN $19::boolean THEN $20 ELSE signing_cert_sha256 END, + published_at = CASE WHEN $21::boolean THEN $22 ELSE published_at END, updated_at = NOW() WHERE id = $1 RETURNING ${RELEASE_COLS}`, [ id, patch.versionName ?? null, + patch.versionCode ?? null, patch.previousVersionName !== undefined, patch.previousVersionName ?? null, patch.whatsNew ?? null, diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index cd7a4807..0555f83f 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -659,7 +659,20 @@ router.post( requireRoles('admin'), requirePermissions('admin.mobile_releases.manage'), validateParams(mobileReleaseIdParamSchema), - apkUpload.single('file'), + (req, res, next) => { + apkUpload.single('file')(req, res, (err: unknown) => { + if (!err) { + next(); + return; + } + const multerErr = err as { code?: string; message?: string }; + if (multerErr.code === 'LIMIT_FILE_SIZE') { + res.status(413).json({ error: 'APK exceeds maximum upload size' }); + return; + } + res.status(400).json({ error: multerErr.message || 'APK upload failed' }); + }); + }, mobileAppReleaseController.adminUploadApk ); router.post( diff --git a/backend/src/services/mobileAppReleaseService.ts b/backend/src/services/mobileAppReleaseService.ts index 6ad5d6b2..19cf55de 100644 --- a/backend/src/services/mobileAppReleaseService.ts +++ b/backend/src/services/mobileAppReleaseService.ts @@ -199,12 +199,22 @@ export async function attachApk(id: string, uploadedAbsolutePath: string): Promi ); } + // Draft/pending: adopt APK versionCode/name when they differ (admin often mistypes the form). + let nextVersionCode = release.versionCode; if (parsed.versionCode !== release.versionCode) { - removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); - throw new MobileReleaseError( - 400, - `APK versionCode ${parsed.versionCode} does not match release versionCode ${release.versionCode}` + const conflict = await repo.findByPlatformChannelVersionCode( + release.platform, + release.channel, + parsed.versionCode ); + if (conflict && conflict.id !== release.id) { + removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`); + throw new MobileReleaseError( + 409, + `APK versionCode ${parsed.versionCode} is already used by another release (${conflict.versionName})` + ); + } + nextVersionCode = parsed.versionCode; } const expectedCert = config.mobileReleases.expectedCertSha256; @@ -227,6 +237,7 @@ export async function attachApk(id: string, uploadedAbsolutePath: string): Promi const updated = await repo.updateRelease(id, { packageName: parsed.packageName, versionName: parsed.versionName || release.versionName, + versionCode: nextVersionCode, storageKey: stagingKey, fileSizeBytes: stat.size, sha256: fileSha, diff --git a/prediqo_web/src/features/mobile-versions/MobileVersionsAdminPage.tsx b/prediqo_web/src/features/mobile-versions/MobileVersionsAdminPage.tsx index 686d9504..a583b2a6 100644 --- a/prediqo_web/src/features/mobile-versions/MobileVersionsAdminPage.tsx +++ b/prediqo_web/src/features/mobile-versions/MobileVersionsAdminPage.tsx @@ -12,6 +12,7 @@ import { DialogTitle, FormControl, InputLabel, + LinearProgress, MenuItem, Select, Stack, @@ -46,6 +47,7 @@ import { uploadMobileApk, type MobileAppRelease, type MobileUpdatePolicy, + type UploadProgress, } from './api/mobileVersionsApi'; function formatBytes(n: number | null): string { @@ -55,6 +57,15 @@ function formatBytes(n: number | null): string { return `${(n / (1024 * 1024)).toFixed(1)} MB`; } +function formatEta(seconds: number | null, t: (k: string, o?: Record) => string): string { + if (seconds == null) return t('admin.mobileVersions.etaCalculating'); + if (seconds < 5) return t('admin.mobileVersions.etaAlmostDone'); + if (seconds < 60) return t('admin.mobileVersions.etaSeconds', { count: seconds }); + const m = Math.floor(seconds / 60); + const s = seconds % 60; + return t('admin.mobileVersions.etaMinutes', { minutes: m, seconds: s }); +} + function statusColor(status: string): 'default' | 'success' | 'warning' | 'error' | 'info' { switch (status) { case 'published': @@ -91,7 +102,15 @@ const emptyCreate: CreateForm = { }; function errMsg(e: unknown, fallback: string): string { - return (e as { response?: { data?: { error?: string } } })?.response?.data?.error || fallback; + const ax = e as { + response?: { status?: number; data?: { error?: string; message?: string } }; + message?: string; + code?: string; + }; + if (ax.response?.status === 413) { + return 'APK too large for the server (nginx/body limit).'; + } + return ax.response?.data?.error || ax.response?.data?.message || ax.message || fallback; } export function MobileVersionsAdminPage() { @@ -108,6 +127,8 @@ export function MobileVersionsAdminPage() { const [form, setForm] = useState(emptyCreate); const [selected, setSelected] = useState(null); const [error, setError] = useState(null); + const [uploadProgress, setUploadProgress] = useState(null); + const [uploadPhase, setUploadPhase] = useState<'idle' | 'uploading' | 'processing'>('idle'); const [settingsForm, setSettingsForm] = useState({ minSupportedVersionCode: '1', checkIntervalSeconds: '21600', @@ -169,7 +190,19 @@ export function MobileVersionsAdminPage() { patch?: Parameters[1]; }) => { const { action, id, file, patch } = args; - if (action === 'upload' && file) return uploadMobileApk(id, file); + if (action === 'upload' && file) { + setUploadPhase('uploading'); + setUploadProgress({ percent: 0, loaded: 0, total: file.size, etaSeconds: null }); + try { + const result = await uploadMobileApk(id, file, (p) => { + setUploadProgress(p); + if (p.percent >= 100) setUploadPhase('processing'); + }); + return result; + } finally { + /* phase cleared in onSettled */ + } + } if (action === 'submit') return submitMobileRelease(id); if (action === 'publish') return publishMobileRelease(id); if (action === 'suspend') return suspendMobileRelease(id); @@ -183,6 +216,10 @@ export function MobileVersionsAdminPage() { invalidate(); }, onError: (e: unknown) => setError(errMsg(e, t('admin.mobileVersions.actionFailed'))), + onSettled: () => { + setUploadPhase('idle'); + setUploadProgress(null); + }, }); const settingsMut = useMutation({ @@ -340,6 +377,31 @@ export function MobileVersionsAdminPage() { + {uploadPhase !== 'idle' && uploadProgress && ( + + + + {uploadPhase === 'processing' + ? t('admin.mobileVersions.uploadProcessing') + : t('admin.mobileVersions.uploading')} + + + {uploadProgress.percent}% · {formatBytes(uploadProgress.loaded)} /{' '} + {formatBytes(uploadProgress.total)} + + + + + {uploadPhase === 'processing' + ? t('admin.mobileVersions.uploadProcessingHint') + : formatEta(uploadProgress.etaSeconds, t)} + + + )} { const file = e.target.files?.[0]; - if (file) actionMut.mutate({ action: 'upload', id: detail.id, file }); + if (file) { + setError(null); + actionMut.mutate({ action: 'upload', id: detail.id, file }); + } e.target.value = ''; }} /> @@ -357,7 +422,9 @@ export function MobileVersionsAdminPage() { disabled={!canManage || actionMut.isPending} onClick={() => fileInputRef.current?.click()} > - {t('admin.mobileVersions.uploadApk')} + {actionMut.isPending && uploadPhase !== 'idle' + ? t('admin.mobileVersions.uploading') + : t('admin.mobileVersions.uploadApk')}