feat: support electronic photo purchases and download completion

This commit is contained in:
2026-09-15 10:51:38 +08:00
parent 712f6154bc
commit b1cdc1fe06
33 changed files with 1488 additions and 218 deletions
@@ -112,6 +112,10 @@ class LocalAudioPlayService @Inject constructor(
// 同一结果页根据入口选择播报,避免最近照片误播识别成功。
val audioKey = localAudioKeyForRoute(route)
if (audioKey == ELECTRONIC_COMPLETION_AUDIO_KEY) {
stop()
return
}
val audioResId = ROUTE_TO_AUDIO_MAP[audioKey]
if (audioResId == null) {
@@ -3,11 +3,16 @@ package com.yzx.kiosk.audio
import com.yzx.kiosk.navigation.routes.AppRoutes
import java.net.URLDecoder
internal const val ELECTRONIC_COMPLETION_AUDIO_KEY = "electronic_completion_silent"
internal const val RECENT_PHOTOS_AUDIO_KEY = "recent_photos_result"
/** Keep result-page audio tied to the entry source, not just the destination name. */
internal fun localAudioKeyForRoute(route: String): String {
val baseRoute = route.substringBefore("?")
if (baseRoute == AppRoutes.ELECTRONIC_COMPLETION) {
return ELECTRONIC_COMPLETION_AUDIO_KEY
}
if (baseRoute != AppRoutes.FACE_RECOGNITION_RESULT) return baseRoute
val source = route.substringAfter("?", "").substringBefore("#")
@@ -209,6 +209,18 @@ fun AppNavHost(
)
}
// 电子版订单完成页,不创建打印页面或打印 ViewModel。
composable(
route = AppRoutes.ELECTRONIC_COMPLETION_PATTERN,
arguments = listOf(
navArgument("orderNumber") { type = NavType.StringType },
),
) { entry ->
com.yzx.kiosk.ui.face.view.ElectronicCompletionScreen(
orderNumber = entry.arguments?.getString("orderNumber").orEmpty(),
)
}
// 协议页面
agreementScreen()
}
@@ -8,6 +8,12 @@ object AppRoutes {
const val UPLOAD_PHOTO = "upload_photo"
const val PHOTO_SELECT = "photo_select"
const val PRINTING = "printing"
const val ELECTRONIC_COMPLETION = "electronic_completion"
const val ELECTRONIC_COMPLETION_PATTERN = "$ELECTRONIC_COMPLETION?orderNumber={orderNumber}"
fun buildElectronicCompletionRoute(orderNumber: String): String =
"$ELECTRONIC_COMPLETION?orderNumber=${java.net.URLEncoder.encode(orderNumber, "UTF-8")}"
const val PRINT_SUCCESS = "print_success"
const val FACE_RECOGNITION = "face_recognition"
const val FACE_RECOGNITION_RESULT = "face_recognition_result"
@@ -6,6 +6,10 @@ data class GetPayUrlRequest(
@SerializedName("type")
val type: Int,
@SerializedName("image_id")
val imageId: List<Int>
val imageId: List<Int>,
@SerializedName("purchase_mode")
val purchaseMode: String? = null,
@SerializedName("video_id")
val videoId: List<Int>? = null
)
@@ -6,6 +6,8 @@ data class VerifyResultRequest(
@SerializedName("type")
val type: Int,
@SerializedName("image_id")
val imageId: List<Int>
val imageId: List<Int>,
@SerializedName("video_id")
val videoId: List<Int>? = null
)
@@ -7,6 +7,12 @@ data class GetPayUrlResponse(
val url: String?,
@SerializedName("order_number")
val orderNumber: String?
val orderNumber: String?,
@SerializedName("purchase_mode")
val purchaseMode: String? = null,
@SerializedName("amount")
val amount: String? = null,
@SerializedName("order_status")
val orderStatus: Int? = null
)
@@ -27,5 +27,8 @@ data class PaySuccessMessageData(
val captureType: Int?,
@SerializedName("image_id")
val imageIds: List<Int>?
val imageIds: List<Int>?,
@SerializedName("purchase_mode")
val purchaseMode: String? = null
)
@@ -6,6 +6,10 @@ data class VerifyResultResponse(
@SerializedName("price_image")
val priceImage: String?,
@SerializedName("amount")
val amount: String?
val amount: String?,
@SerializedName("price_electronic")
val priceElectronic: String? = null,
@SerializedName("amount_electronic")
val amountElectronic: String? = null
)
@@ -0,0 +1,187 @@
package com.yzx.kiosk.ui.face.view
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowLeft
import androidx.compose.material.icons.rounded.Call
import androidx.compose.material.icons.rounded.Info
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.yzx.kiosk.R
import com.yzx.kiosk.navigation.routes.AppRoutes
import com.yzx.kiosk.theme.AppTheme
import com.yzx.kiosk.ui.common.view.FullScreenMode
import com.yzx.kiosk.ui.face.viewmodel.ElectronicCompletionViewModel
import com.yzx.kiosk.utils.QrCodeUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable
fun ElectronicCompletionScreen(
orderNumber: String,
viewModel: ElectronicCompletionViewModel = hiltViewModel(),
) {
val countdown by viewModel.countdown.collectAsState()
val qrUrl by viewModel.qrCodeUrl.collectAsState()
val failed by viewModel.qrCodeFailed.collectAsState()
val hotline by viewModel.hotline.collectAsState()
LaunchedEffect(orderNumber) { viewModel.initialize(orderNumber) }
var renderAttempt by remember { mutableIntStateOf(0) }
val renderedQr by produceState<Pair<ImageBitmap?, Boolean>>(null to false, qrUrl, renderAttempt) {
value = null to false
if (qrUrl.isNotBlank()) {
value = withContext(Dispatchers.Default) {
val result = runCatching {
QrCodeUtils.generateStyledQrBitmap(
content = qrUrl, size = 800, qrColor = android.graphics.Color.BLACK,
bgColor = android.graphics.Color.WHITE, cornerRadius = 0f,
).asImageBitmap()
}
result.getOrNull() to result.isFailure
}
}
}
val returnHome = { viewModel.closeAllExcept(AppRoutes.HOME) }
BackHandler(onBack = returnHome)
FullScreenMode()
ElectronicCompletionContent(
bitmap = renderedQr.first,
failed = failed || renderedQr.second,
countdown = countdown,
hotline = hotline,
onRetry = {
renderAttempt += 1
viewModel.retryQrCode()
},
onReturnHome = returnHome,
)
}
/** Reference is 941 × 1672. Uniform density keeps typography and spacing in proportion
* on the portrait kiosk, without stretching the QR code on other display sizes. */
@Composable
internal fun ElectronicCompletionContent(
bitmap: ImageBitmap?,
failed: Boolean,
countdown: Int,
hotline: String,
onRetry: () -> Unit,
onReturnHome: () -> Unit,
) {
val primary = MaterialTheme.colorScheme.primary
val resources = LocalContext.current.resources
// Only the decorative phone and footer are used from the artwork. The QR, copy,
// hotline, buttons and all panels below are native, live Compose content.
val artwork = remember(resources) {
val source = BitmapFactory.decodeResource(resources, R.drawable.electronic_completion_artwork)
val phone = Bitmap.createBitmap(source, 34, 354, 424, 635).asImageBitmap()
val footer = Bitmap.createBitmap(source, 0, 1440, 941, 232).asImageBitmap()
source.recycle()
phone to footer
}
BoxWithConstraints(Modifier.fillMaxSize().background(Color.White), contentAlignment = Alignment.Center) {
val density = LocalDensity.current
val scale = minOf(maxWidth.value / 941f, maxHeight.value / 1672f)
val canvasHeight = maxOf(1672f, maxHeight.value / scale)
CompositionLocalProvider(LocalDensity provides Density(density.density * scale, fontScale = 1f)) {
Box(Modifier.requiredSize(941.dp, canvasHeight.dp).background(Color.White)) {
Box(Modifier.fillMaxWidth().height(186.dp).background(primary)) {
IconButton(onClick = onReturnHome, modifier = Modifier.offset(20.dp, 91.dp).size(80.dp)) {
Icon(Icons.AutoMirrored.Rounded.KeyboardArrowLeft, "返回首页", tint = Color.White, modifier = Modifier.size(58.dp))
}
Text("获取电子照片", Modifier.align(Alignment.BottomCenter).padding(bottom = 30.dp),
color = Color.White, fontSize = 42.sp, fontWeight = FontWeight.Bold)
Text("${countdown}秒后返回首页", Modifier.align(Alignment.TopEnd).padding(top = 28.dp, end = 36.dp),
color = Color.White.copy(alpha = .9f), fontSize = 23.sp)
}
Box(Modifier.offset(y = 186.dp).fillMaxWidth().height(138.dp).background(primary.copy(alpha = .055f)),
contentAlignment = Alignment.Center) {
Text("请使用微信扫描下方二维码,获取电子版照片/视频\n可多人多次扫描",
color = Color(0xFF55585C), fontSize = 29.sp, lineHeight = 46.sp, textAlign = TextAlign.Center)
}
Image(artwork.first, "电子照片保存到手机示意图", Modifier.offset(34.dp, 354.dp).size(424.dp, 635.dp),
contentScale = ContentScale.FillBounds)
Box(Modifier.offset(483.dp, 354.dp).size(424.dp, 635.dp)
.background(Color(0xFFF5F5F6), RoundedCornerShape(28.dp))) {
Box(Modifier.offset(27.dp, 34.dp).size(369.dp, 354.dp)
.background(Color.White, RoundedCornerShape(26.dp)), contentAlignment = Alignment.Center) {
when {
bitmap != null -> Image(bitmap, "电子版照片下载二维码", Modifier.size(340.dp),
filterQuality = FilterQuality.None)
failed -> Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("二维码加载失败", fontSize = 26.sp, color = Color(0xFF55585C))
TextButton(onClick = onRetry) { Text("重新加载", fontSize = 26.sp) }
}
else -> CircularProgressIndicator(Modifier.size(52.dp), color = primary)
}
}
Text("请使用微信扫描", Modifier.offset(y = 410.dp).fillMaxWidth(),
color = Color(0xFF444444), fontSize = 29.sp, textAlign = TextAlign.Center)
Text("获取电子版照片/视频", Modifier.offset(y = 462.dp).fillMaxWidth(),
color = Color.Black, fontSize = 32.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center)
Text("可多人多次扫描", Modifier.offset(y = 530.dp).fillMaxWidth(),
color = Color(0xFF555555), fontSize = 29.sp, textAlign = TextAlign.Center)
}
Box(Modifier.offset(34.dp, 1020.dp).size(873.dp, 387.dp)
.background(primary.copy(alpha = .055f), RoundedCornerShape(28.dp))) {
Icon(Icons.Rounded.Info, null, Modifier.offset(39.dp, 37.dp).size(50.dp), tint = primary)
Text("温馨提示", Modifier.offset(109.dp, 35.dp), color = primary, fontSize = 40.sp, fontWeight = FontWeight.Bold)
TipRow(1, "请使用微信扫描二维码获取电子版照片 / 视频。", Modifier.offset(40.dp, 122.dp))
TipRow(2, "照片和视频将以高清原图的形式提供,可多次下载。", Modifier.offset(40.dp, 186.dp))
TipRow(3, "如遇问题,请联系客服。", Modifier.offset(40.dp, 250.dp))
Row(Modifier.offset(109.dp, 312.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Rounded.Call, null, Modifier.size(37.dp), tint = primary)
Spacer(Modifier.width(24.dp))
Text("客服电话:${hotline.takeIf { it.isNotBlank() } ?: "暂无"}",
fontSize = 31.sp, color = primary, fontWeight = FontWeight.SemiBold)
}
}
Image(artwork.second, null, Modifier.align(Alignment.BottomCenter).size(941.dp, 232.dp),
contentScale = ContentScale.FillBounds)
}
}
}
}
@Composable
private fun TipRow(number: Int, text: String, modifier: Modifier = Modifier) {
val primary = MaterialTheme.colorScheme.primary
Row(modifier, verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(46.dp).background(primary.copy(alpha = .1f), CircleShape), contentAlignment = Alignment.Center) {
Text(number.toString(), color = primary, fontSize = 30.sp)
}
Spacer(Modifier.width(23.dp))
Text(text, color = Color(0xFF55585C), fontSize = 29.sp, lineHeight = 40.sp)
}
}
@Preview(name = "电子版完成页", widthDp = 941, heightDp = 1672, showBackground = true)
@Composable
private fun ElectronicCompletionPreview() {
AppTheme {
ElectronicCompletionContent(null, false, 90, "12345678910", {}, {})
}
}
@@ -1,7 +1,10 @@
package com.yzx.kiosk.ui.face.view
import com.yzx.kiosk.utils.formatPriceDisplay
import android.graphics.Bitmap
import androidx.compose.foundation.ExperimentalFoundationApi
import com.yzx.kiosk.ui.face.viewmodel.PurchaseMode
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -77,6 +80,12 @@ fun FaceRecognitionResultScreen(
val selectedPhotos by viewModel.selectedPhotos.collectAsState()
val pricePerPhoto by viewModel.pricePerPhoto.collectAsState()
val totalPrice by viewModel.totalPrice.collectAsState()
val electronicPrice by viewModel.electronicPrice.collectAsState()
val electronicTotal by viewModel.electronicTotal.collectAsState()
val creatingOrder by viewModel.creatingOrder.collectAsState()
val quoteLoading by viewModel.quoteLoading.collectAsState()
val quoteError by viewModel.quoteError.collectAsState()
val paymentAmount by viewModel.paymentAmount.collectAsState()
val imageLoadStates by viewModel.imageLoadStates.collectAsState()
var isOpeningRecentPhotos by remember { mutableStateOf(false) }
@@ -139,62 +148,46 @@ fun FaceRecognitionResultScreen(
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(containerColor = Color(0xFFF4F4F4))
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = "已选择",
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
color = Color.Black
)
Text(
modifier = Modifier.padding(top = 4.dp),
text = selectedCount.toString(),
fontSize = 28.sp,
fontWeight = FontWeight.Bold,
color = Color(0xFF0073FF)
)
Text(
text = "张",
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
color = Color.Black
)
}
Spacer(modifier = Modifier.height(18.dp))
Text(
text = "打印${pricePerPhoto}元/张",
fontSize = 21.sp,
color = Color(0xFF000000)
)
}
Button(
onClick = {
viewModel.getPayUrl { url ->
showPayDialog = true
Column(Modifier.fillMaxWidth().padding(24.dp)) {
Text("已选择 ${selectedCount} 张", fontSize = 24.sp, fontWeight = FontWeight.Bold)
Spacer(Modifier.height(16.dp))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
PurchaseMode.entries.forEach { mode ->
val isPrint = mode == PurchaseMode.PRINT
val unit = if (isPrint) pricePerPhoto else electronicPrice
val total = if (isPrint) totalPrice else electronicTotal
Column(Modifier.weight(1f)) {
Text("${mode.label} ${formatPriceDisplay(unit)}元/张", fontSize = 21.sp)
Spacer(Modifier.height(12.dp))
Button(
onClick = { viewModel.getPayUrl(mode) { showPayDialog = true } },
enabled = selectedCount > 0 && total != "--" && !creatingOrder && !quoteLoading,
modifier = Modifier.fillMaxWidth().heightIn(min = 88.dp),
shape = RoundedCornerShape(18.dp),
colors = ButtonDefaults.buttonColors(
containerColor = if (isPrint) Color(0xFF0073FF) else Color(0xFFE3EFFF),
contentColor = if (isPrint) Color.White else Color(0xFF1756A9),
),
) {
Text(
text = if (!isPrint && total == "--" && !quoteLoading)
"电子版暂不可购买" else "支付${mode.label}\n${formatPriceDisplay(total)}元",
textAlign = TextAlign.Center,
fontSize = 24.sp,
lineHeight = 32.sp,
fontWeight = FontWeight.Bold,
)
}
}
},
modifier = Modifier
.height(72.dp)
.widthIn(min = 180.dp),
shape = RoundedCornerShape(18.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF0073FF)),
enabled = selectedCount > 0
) {
Text(
text = if (selectedCount > 0) "支付${totalPrice}元" else "支付0元",
fontSize = 24.sp,
color = Color.White,
fontWeight = FontWeight.Bold
)
}
}
if (quoteLoading) {
Text("正在获取价格…", modifier = Modifier.padding(top = 12.dp))
} else if (quoteError != null || totalPrice == "--") {
Text(quoteError ?: "打印价格暂不可用", modifier = Modifier.padding(top = 12.dp))
TextButton(onClick = { viewModel.retryQuote() }, enabled = !creatingOrder && !quoteLoading) {
Text("重新获取价格")
}
}
}
}
@@ -343,7 +336,7 @@ fun FaceRecognitionResultScreen(
}
// 支付弹框
if (showPayDialog && selectedCount > 0 && payQrCodeUrl != null) {
if (showPayDialog && payQrCodeUrl != null) {
DisposableEffect(payQrCodeUrl) {
viewModel.startPayStatusPolling()
onDispose {
@@ -353,7 +346,7 @@ fun FaceRecognitionResultScreen(
WechatPayDialog(
qrCodeUrl = payQrCodeUrl!!,
totalPrice = totalPrice,
totalPrice = paymentAmount,
onDismiss = {
showPayDialog = false
viewModel.onPayDialogDismissed()
@@ -0,0 +1,80 @@
package com.yzx.kiosk.ui.face.viewmodel
import androidx.lifecycle.viewModelScope
import com.yzx.kiosk.base.BaseViewModel
import com.yzx.kiosk.datastore.AppState
import com.yzx.kiosk.datastore.AppStoreDataSource
import com.yzx.kiosk.navigation.AppNavigator
import com.yzx.kiosk.navigation.routes.AppRoutes
import com.yzx.kiosk.network.model.request.SaveAlbumUrlRequest
import com.yzx.kiosk.network.repository.NetWorkRepository
import com.yzx.kiosk.utils.ToastUtils
import com.yzx.kiosk.utils.LogUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
/** Download-only completion: deliberately has no printer or print-download dependencies. */
@HiltViewModel
class ElectronicCompletionViewModel @Inject constructor(
navigator: AppNavigator,
appState: AppState,
appStoreDataSource: AppStoreDataSource,
private val netWorkRepository: NetWorkRepository,
) : BaseViewModel(navigator = navigator, appState = appState) {
private val _countdown = MutableStateFlow(90)
val countdown = _countdown.asStateFlow()
private val _qrCodeUrl = MutableStateFlow("")
val qrCodeUrl = _qrCodeUrl.asStateFlow()
private val _qrCodeFailed = MutableStateFlow(false)
val qrCodeFailed = _qrCodeFailed.asStateFlow()
val hotline = MutableStateFlow(appStoreDataSource.getHomepageServicePhone()).asStateFlow()
private var orderNumber: String? = null
private var qrJob: Job? = null
fun initialize(orderNumber: String) {
if (this.orderNumber != null) return
if (orderNumber.isBlank()) {
_qrCodeFailed.value = true
return
}
this.orderNumber = orderNumber
retryQrCode()
viewModelScope.launch {
while (_countdown.value > 0) {
delay(1_000)
_countdown.value -= 1
}
navigator.closeAllExcept(AppRoutes.HOME)
}
}
fun retryQrCode() {
val number = orderNumber ?: return
if (qrJob?.isActive == true) return
_qrCodeFailed.value = false
qrJob = viewModelScope.launch {
try {
val response = netWorkRepository.saveAlbumUrl(SaveAlbumUrlRequest(number)).first()
val url = response.data?.url?.trim()
if (response.isSucceeded && !url.isNullOrEmpty()) {
_qrCodeUrl.value = url
} else {
_qrCodeFailed.value = true
ToastUtils.show(response.message?.takeIf { it.isNotBlank() } ?: "二维码加载失败,请重试")
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_qrCodeFailed.value = true
LogUtils.e("ElectronicCompletion", "获取二维码失败: ${e.message}")
}
}
}
}
@@ -10,8 +10,8 @@ internal enum class FacePayStatusDecision {
internal fun decideFacePayStatus(orderStatus: Int?): FacePayStatusDecision = when (orderStatus) {
30 -> FacePayStatusDecision.COMPLETE_PAYMENT
40, 50, 60 -> FacePayStatusDecision.STOP_WITH_TERMINAL_STATUS
else -> FacePayStatusDecision.CONTINUE_POLLING
10 -> FacePayStatusDecision.CONTINUE_POLLING
else -> FacePayStatusDecision.STOP_WITH_TERMINAL_STATUS
}
internal fun isValidFacePaySuccessMessage(
@@ -19,7 +19,7 @@ internal fun isValidFacePaySuccessMessage(
message: PaySuccessMessageResponse?
): Boolean {
val paymentData = message?.data ?: return false
return message.type == 5 &&
return message.orderStatus == 30 && message.type == 5 &&
paymentData.orderNumber == expectedOrderNumber &&
paymentData.captureType == 2 &&
!paymentData.imageIds.isNullOrEmpty()
@@ -0,0 +1,60 @@
package com.yzx.kiosk.ui.face.viewmodel
import com.yzx.kiosk.network.model.response.GetPayUrlResponse
import java.math.BigDecimal
import java.math.RoundingMode
enum class PurchaseMode(val wireValue: String, val label: String) {
PRINT("print", "打印版"), ELECTRONIC("electronic", "电子版")
}
internal fun money(value: String?): String? {
if (value == null || !Regex("[0-9]+(?:\\.[0-9]{1,2})?").matches(value)) return null
return value.toBigDecimalOrNull()?.setScale(2, RoundingMode.UNNECESSARY)?.toPlainString()
}
internal fun isPositiveMoney(value: String?): Boolean =
money(value)?.toBigDecimal()?.let { it > BigDecimal.ZERO } == true
internal fun electronicQuoteAvailable(unit: String?, total: String?, hasPhotos: Boolean): Boolean =
isPositiveMoney(unit) && money(total) != null && (!hasPhotos || isPositiveMoney(total))
internal data class FacePaymentOrder(
val number: String,
val mode: PurchaseMode,
val imageIds: Set<Int>,
val amount: String,
val legacyPrint: Boolean,
) {
fun matches(number: String?, captureType: Int?, ids: List<Int>, purchaseMode: String?): Boolean =
this.number == number && captureType == 2 && ids.isNotEmpty() &&
ids.size == ids.toSet().size && imageIds == ids.toSet() &&
(purchaseMode == mode.wireValue || (legacyPrint && purchaseMode == null))
}
internal fun createFacePaymentOrder(
response: GetPayUrlResponse,
mode: PurchaseMode,
ids: List<Int>,
quotedAmount: String,
): FacePaymentOrder? {
val number = response.orderNumber?.trim()?.takeIf { it.isNotEmpty() } ?: return null
// Only an entirely old-style print response may omit the new order fields.
val legacy = mode == PurchaseMode.PRINT && response.purchaseMode == null && response.amount == null
if (!legacy && response.purchaseMode != mode.wireValue) return null
val amount = money(if (legacy) quotedAmount else response.amount) ?: return null
if (ids.isEmpty()) return null
val order = FacePaymentOrder(number, mode, ids.toSet(), amount, legacy)
if (mode == PurchaseMode.ELECTRONIC && !isPositiveMoney(amount)) return null
// The link represents a pending preselection, never proof of purchase.
if (!legacy && response.orderStatus != 10) return null
if (response.url.isNullOrBlank()) return null
return order
}
/** Versioning also rejects responses from an old A selection after A -> B -> A. */
internal class QuoteRevision {
private var revision = 0L
fun next(): Long = ++revision
fun isCurrent(candidate: Long): Boolean = revision == candidate
}
@@ -12,7 +12,6 @@ import com.yzx.kiosk.network.model.response.FaceSearchResult
import com.yzx.kiosk.network.service.FaceSearchService
import com.yzx.kiosk.network.service.buildRecentPhotosUrl
import com.yzx.kiosk.network.repository.NetWorkRepository
import com.yzx.kiosk.network.result.asResult
import com.yzx.kiosk.ui.upload.viewmodel.FileMapData
import com.yzx.kiosk.ui.upload.viewmodel.PhotoData
import com.yzx.kiosk.utils.ToastUtils
@@ -100,6 +99,24 @@ class FaceRecognitionResultViewModel @Inject constructor(
private val _totalPrice = MutableStateFlow<String>("--")
val totalPrice: StateFlow<String> = _totalPrice.asStateFlow()
private val _electronicPrice = MutableStateFlow("--")
val electronicPrice = _electronicPrice.asStateFlow()
private val _electronicTotal = MutableStateFlow("--")
val electronicTotal = _electronicTotal.asStateFlow()
private val _creatingOrder = MutableStateFlow(false)
val creatingOrder = _creatingOrder.asStateFlow()
private val _quoteLoading = MutableStateFlow(false)
val quoteLoading = _quoteLoading.asStateFlow()
private val _quoteError = MutableStateFlow<String?>(null)
val quoteError = _quoteError.asStateFlow()
private val _paymentAmount = MutableStateFlow("--")
val paymentAmount = _paymentAmount.asStateFlow()
private val _paymentMode = MutableStateFlow(PurchaseMode.PRINT)
val paymentMode = _paymentMode.asStateFlow()
private var activeOrder: FacePaymentOrder? = null
private val quoteRevision = QuoteRevision()
private var quoteJob: Job? = null
// 支付二维码URL
private val _payQrCodeUrl = MutableStateFlow<String?>(null)
val payQrCodeUrl: StateFlow<String?> = _payQrCodeUrl.asStateFlow()
@@ -139,6 +156,7 @@ class FaceRecognitionResultViewModel @Inject constructor(
orderNumber = event.orderNumber,
captureType = event.captureType,
imageIds = event.imageIds,
purchaseMode = event.purchaseMode,
source = "WebSocket"
)
}
@@ -234,6 +252,7 @@ class FaceRecognitionResultViewModel @Inject constructor(
* 切换单张图片选中状态
*/
fun togglePhotoSelection(url: String) {
if (_creatingOrder.value) return
val current = _selectedPhotos.value.toMutableSet()
if (current.contains(url)) {
current.remove(url)
@@ -251,6 +270,7 @@ class FaceRecognitionResultViewModel @Inject constructor(
* 切换全选状态
*/
fun toggleSelectAll() {
if (_creatingOrder.value) return
if (_photoList.value.isEmpty()) return
val allUrls = _photoList.value.map { it.url }.toSet()
val newSelected = if (_selectedPhotos.value.size == allUrls.size) {
@@ -280,100 +300,109 @@ class FaceRecognitionResultViewModel @Inject constructor(
* 验证结果接口
*/
private fun verifyResult(imageIds: List<Int>) {
viewModelScope.launch {
clearActivePayment()
_quoteLoading.value = true
_quoteError.value = null
val revision = quoteRevision.next()
quoteJob?.cancel()
_pricePerPhoto.value = "--"
_totalPrice.value = "--"
_electronicPrice.value = "--"
_electronicTotal.value = "--"
quoteJob = viewModelScope.launch {
try {
val request = VerifyResultRequest(
type = 2,
imageId = imageIds
)
handleResultWithData(
flow = netWorkRepository.verifyResult(request).asResult(),
showToast = false,
onData = { response ->
// 更新单价(使用接口返回的 price_image)
val priceImage = response.priceImage
if (!priceImage.isNullOrEmpty()) {
_pricePerPhoto.value = priceImage
} else {
_pricePerPhoto.value = "--"
}
// 更新总价(使用接口返回的 amount)
val amount = response.amount
if (!amount.isNullOrEmpty()) {
_totalPrice.value = amount
} else {
_totalPrice.value = "--"
}
LogUtils.d("FaceRecognitionResultViewModel", "验证结果成功 - 单价: $priceImage, 总价: $amount")
},
onError = { msg, _ ->
LogUtils.e("FaceRecognitionResultViewModel", "验证结果失败: $msg")
// 接口失败时,保持当前值或设置为默认值
if (imageIds.isEmpty()) {
_pricePerPhoto.value = "--"
_totalPrice.value = "--"
}
}
)
} catch (e: Exception) {
LogUtils.e("FaceRecognitionResultViewModel", "验证结果异常: ${e.message}")
if (imageIds.isEmpty()) {
_pricePerPhoto.value = "--"
_totalPrice.value = "--"
val response = netWorkRepository.verifyResult(VerifyResultRequest(2, imageIds.distinct(), videoId = emptyList())).first()
if (!quoteRevision.isCurrent(revision)) return@launch
if (!response.isSucceeded) {
_quoteError.value = response.message?.takeIf { it.isNotBlank() } ?: "获取报价失败,请重试"
return@launch
}
val data = response.data
if (data == null) {
_quoteError.value = "报价数据不完整,请重试"
return@launch
}
val printUnit = money(data.priceImage)
val printTotal = money(data.amount)
if (printUnit != null && printTotal != null) {
_pricePerPhoto.value = printUnit
_totalPrice.value = printTotal
}
val electronicUnit = money(data.priceElectronic)
val electronicTotal = money(data.amountElectronic)
if (electronicQuoteAvailable(electronicUnit, electronicTotal, imageIds.isNotEmpty())) {
_electronicPrice.value = checkNotNull(electronicUnit)
_electronicTotal.value = checkNotNull(electronicTotal)
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
LogUtils.e(TAG, "获取报价失败: ${e.message}")
if (quoteRevision.isCurrent(revision)) _quoteError.value = "网络异常,请重新获取价格"
} finally {
if (quoteRevision.isCurrent(revision)) _quoteLoading.value = false
}
}
}
/**
* 获取支付URL
*/
fun getPayUrl(onSuccess: (String) -> Unit) {
private fun clearActivePayment() {
stopPayStatusPolling()
activeOrder = null
activePaymentOrderNumber = null
_payQrCodeUrl.value = null
_dismissPayDialogEvents.tryEmit(Unit)
}
private fun recoverPayment(message: String) {
clearActivePayment()
ToastUtils.show(message)
retryQuote()
}
fun retryQuote() = verifyResult(getSelectedImageIds())
fun getPayUrl(mode: PurchaseMode, onSuccess: (String) -> Unit) {
if (_creatingOrder.value) return
val selectedIds = getSelectedImageIds().distinct()
val quotedAmount = if (mode == PurchaseMode.PRINT) _totalPrice.value else _electronicTotal.value
if (selectedIds.isEmpty() || money(quotedAmount) == null || _quoteLoading.value) return
if (mode == PurchaseMode.ELECTRONIC && !isPositiveMoney(quotedAmount)) return
clearActivePayment()
_creatingOrder.value = true
viewModelScope.launch {
val selectedIds = getSelectedImageIds()
if (selectedIds.isEmpty()) {
ToastUtils.show("请选择要打印的照片")
return@launch
}
showLoading()
try {
val request = GetPayUrlRequest(
type = 2,
imageId = selectedIds
)
handleResultWithData(
flow = netWorkRepository.getPayUrl(request).asResult(),
showToast = false,
onData = { response ->
val url = response.url?.trim()
val orderNumber = response.orderNumber?.trim()
if (url.isNullOrEmpty() || orderNumber.isNullOrEmpty()) {
_payQrCodeUrl.value = null
LogUtils.e(TAG, "获取支付二维码成功,但 url 或 order_number 为空")
ToastUtils.show("获取支付二维码失败")
} else {
stopPayStatusPolling()
activePaymentOrderNumber = orderNumber
paymentHandled.set(false)
_payQrCodeUrl.value = url
onSuccess(url)
}
},
onError = { msg, _ ->
LogUtils.e("FaceRecognitionResultViewModel", "获取支付URL失败: $msg")
ToastUtils.show("获取支付二维码失败")
},
onEnd = {
hideLoading()
}
)
val response = netWorkRepository.getPayUrl(
GetPayUrlRequest(2, selectedIds, mode.wireValue, videoId = emptyList())
).first()
if (!response.isSucceeded) {
recoverPayment(response.message?.takeIf { it.isNotBlank() } ?: "获取支付链接失败,请重新选择")
return@launch
}
val data = response.data
val order = if (data != null)
createFacePaymentOrder(data, mode, selectedIds, quotedAmount) else null
if (order == null) {
recoverPayment("支付链接信息无效,请重新选择")
return@launch
}
stopPayStatusPolling()
activeOrder = order
activePaymentOrderNumber = order.number
paymentHandled.set(false)
_paymentAmount.value = order.amount
_paymentMode.value = order.mode
val url = checkNotNull(data?.url).trim()
_payQrCodeUrl.value = url
onSuccess(url)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
LogUtils.e("FaceRecognitionResultViewModel", "获取支付URL异常: ${e.message}")
ToastUtils.show("获取支付二维码失败")
LogUtils.e(TAG, "创建订单失败: ${e.message}")
ToastUtils.show("创建订单失败,请重试")
} finally {
_creatingOrder.value = false
hideLoading()
}
}
}
@@ -420,14 +449,17 @@ class FaceRecognitionResultViewModel @Inject constructor(
.getPaySuccessMessage(PaySuccessMessageRequest(orderNumber))
.first()
if (activePaymentOrderNumber != orderNumber || paymentHandled.get()) return
if (!response.isSucceeded) {
LogUtils.e(
TAG,
"查询支付状态业务失败 - order_number: $orderNumber, code: ${response.code}, msg: ${response.message}"
)
recoverPayment(response.message?.takeIf { it.isNotBlank() } ?: "订单已失效,请重新选择照片")
return
}
if (activePaymentOrderNumber != orderNumber) return
val message = response.data
when (decideFacePayStatus(message?.orderStatus)) {
FacePayStatusDecision.CONTINUE_POLLING -> {
@@ -448,6 +480,7 @@ class FaceRecognitionResultViewModel @Inject constructor(
orderNumber = paymentData.orderNumber,
captureType = paymentData.captureType,
imageIds = paymentData.imageIds.orEmpty(),
purchaseMode = paymentData.purchaseMode,
source = "HTTP"
)
}
@@ -470,16 +503,17 @@ class FaceRecognitionResultViewModel @Inject constructor(
stopPayStatusPolling()
activePaymentOrderNumber = null
activeOrder = null
_payQrCodeUrl.value = null
_dismissPayDialogEvents.tryEmit(Unit)
val statusText = orderStatusName?.takeIf { it.isNotBlank() } ?: when (orderStatus) {
40 -> "已取消"
50 -> "已退款"
60 -> "部分退款"
else -> "状态异常"
}
ToastUtils.show("订单$statusText")
retryQuote()
LogUtils.i(TAG, "订单进入终态,停止支付轮询 - status: $orderStatus, name: $statusText")
}
@@ -487,19 +521,13 @@ class FaceRecognitionResultViewModel @Inject constructor(
orderNumber: String?,
captureType: Int?,
imageIds: List<Int>,
purchaseMode: String?,
source: String
) {
val expectedOrderNumber = activePaymentOrderNumber
if (
expectedOrderNumber.isNullOrEmpty() ||
orderNumber != expectedOrderNumber ||
captureType != 2 ||
imageIds.isEmpty()
) {
LogUtils.i(
TAG,
"忽略不匹配的支付成功消息 - source: $source, expected: $expectedOrderNumber, actual: $orderNumber, capture_type: $captureType, image_ids: $imageIds"
)
val order = activeOrder ?: return
if (!order.matches(orderNumber, captureType, imageIds, purchaseMode)) {
LogUtils.i(TAG, "忽略不匹配的支付成功消息 - source: $source, expected: $expectedOrderNumber")
return
}
@@ -518,16 +546,16 @@ class FaceRecognitionResultViewModel @Inject constructor(
stopPayStatusPolling()
_payQrCodeUrl.value = null
_dismissPayDialogEvents.tryEmit(Unit)
navigateToPrinting(orderNumber, captureType, imageIds)
navigateAfterPurchase(orderNumber, captureType, imageIds, order)
}
/**
* 支付成功后直接跳转到打印页面
* 按已确认订单的模式进入打印流程或独立电子版完成页
* @param orderNumber 订单号
* @param captureType 抓拍类型
* @param imageIds 图片ID数组(从支付成功消息中获取)
*/
private fun navigateToPrinting(orderNumber: String?, captureType: Int?, imageIds: List<Int>) {
private fun navigateAfterPurchase(orderNumber: String?, captureType: Int?, imageIds: List<Int>, order: FacePaymentOrder) {
viewModelScope.launch {
if (orderNumber.isNullOrBlank() || captureType == null) {
LogUtils.e(
@@ -567,7 +595,11 @@ class FaceRecognitionResultViewModel @Inject constructor(
.setPopUpTo(AppRoutes.FACE_RECOGNITION_RESULT, inclusive = true)
.build()
val route = AppRoutes.buildPrintingRoute(jsonArray, orderNumber, captureType)
val route = if (order.mode == PurchaseMode.ELECTRONIC) {
AppRoutes.buildElectronicCompletionRoute(orderNumber)
} else {
AppRoutes.buildPrintingRoute(jsonArray, orderNumber, captureType)
}
toPage(route, navOptions)
}
}
@@ -1,5 +1,6 @@
package com.yzx.kiosk.ui.upload.view
import com.yzx.kiosk.utils.formatPriceDisplay
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
@@ -150,7 +151,7 @@ fun PhotoSelectScreen(
}
Spacer(modifier = Modifier.height(18.dp))
Text(
text = "打印${pricePerPhoto}元/张",
text = "打印${formatPriceDisplay(pricePerPhoto)}元/张",
fontSize = 21.sp,
color = Color(0xFF000000)
)
@@ -170,7 +171,7 @@ fun PhotoSelectScreen(
enabled = selectedCount > 0
) {
Text(
text = if (selectedCount > 0) "支付${totalPrice}元" else "支付0元",
text = if (selectedCount > 0) "支付${formatPriceDisplay(totalPrice)}元" else "支付0元",
fontSize = 24.sp,
color = Color.White,
fontWeight = FontWeight.Bold
@@ -1,5 +1,6 @@
package com.yzx.kiosk.ui.upload.view
import com.yzx.kiosk.utils.formatPriceDisplay
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
@@ -259,7 +260,7 @@ fun UploadPhotoScreen(
// 打印价格
ServiceInfoRow(
label = "打印价格",
value = printPrice,
value = formatPriceDisplay(printPrice),
valueColor = Color(0xFFEF4444)
)
@@ -0,0 +1,8 @@
package com.yzx.kiosk.utils
private val decimalPrice = Regex("[0-9]+\\.[0-9]+")
/** Display only; also preserves units such as 元/张 and placeholders such as --. */
fun formatPriceDisplay(value: String): String = decimalPrice.replace(value) {
it.value.toBigDecimal().stripTrailingZeros().toPlainString()
}
@@ -0,0 +1,30 @@
package com.yzx.kiosk.websocket
import com.google.gson.JsonObject
/** New gateway: code -> data(type=5) -> data(order). Older gateways used a flat data object. */
internal fun parsePurchaseCompletedEvent(message: JsonObject): UploadPhotoEvent.PaySuccess? = runCatching {
if (message.get("code")?.asString != "5") return null
val envelope = message.getAsJsonObject("data") ?: return null
val order = if (envelope.has("data")) {
if (envelope.get("type")?.asInt != 5) return null
envelope.getAsJsonObject("data") ?: return null
} else {
if (envelope.has("type") && envelope.get("type")?.asInt != 5) return null
envelope
}
val number = order.get("order_number")?.takeUnless { it.isJsonNull }?.asString
?.takeIf { it.isNotBlank() } ?: return null
val captureType = order.get("capture_type")?.asInt ?: return null
if (captureType !in listOf(1, 2)) return null
val imageIds = order.get("image_id")?.takeUnless { it.isJsonNull }
?.asJsonArray?.map { it.asInt }.orEmpty()
if (captureType == 2 && imageIds.isEmpty()) return null
UploadPhotoEvent.PaySuccess(
orderNumber = number,
captureType = captureType,
imageIds = imageIds,
fileMap = order.get("file_map")?.takeUnless { it.isJsonNull }?.toString().orEmpty(),
purchaseMode = order.get("purchase_mode")?.takeUnless { it.isJsonNull }?.asString,
)
}.getOrNull()
@@ -390,46 +390,13 @@ class WebSocketService @Inject constructor(
}
}
"5" -> {
// 支付成功消息
LogUtils.d(TAG, ">>> 收到支付成功消息 (code=5) <<<")
try {
val dataElement = jsonObject.get("data")
if (dataElement != null && dataElement.isJsonObject) {
val dataObj = dataElement.asJsonObject
val orderNumber = dataObj.get("order_number")?.asString
val captureType = dataObj.get("capture_type")?.asInt
val imageIdList = mutableListOf<Int>()
if (dataObj.has("image_id")) {
val imageIdArray = dataObj.get("image_id")
if (imageIdArray != null && imageIdArray.isJsonArray) {
imageIdArray.asJsonArray.forEach { element ->
element.asInt.let { imageIdList.add(it) }
}
}
}
var fileMap = ""
if (dataObj.has("file_map")){
fileMap = dataObj.get("file_map").toString()
}
LogUtils.d(TAG, "支付成功 - order_number: $orderNumber, capture_type: $captureType, image_id: $imageIdList,fileMap:$fileMap")
// 发送支付成功事件
CoroutineScope(Dispatchers.Main).launch {
_uploadPhotoEvents.emit(
UploadPhotoEvent.PaySuccess(
orderNumber = orderNumber,
captureType = captureType,
imageIds = imageIdList,
fileMap = fileMap
)
)
}
val event = parsePurchaseCompletedEvent(jsonObject)
if (event != null) {
CoroutineScope(Dispatchers.Main).launch {
_uploadPhotoEvents.emit(event)
}
} catch (e: Exception) {
LogUtils.e(TAG, "解析支付成功消息失败: ${e.message}")
} else {
LogUtils.e(TAG, "忽略无效的购买完成消息")
}
}
"4" -> {
@@ -974,6 +941,7 @@ sealed class UploadPhotoEvent {
val orderNumber: String?,
val captureType: Int?,
val fileMap:String,
val imageIds: List<Int>
val imageIds: List<Int>,
val purchaseMode: String? = null
) : UploadPhotoEvent()
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB