Author SHA1 Message Date
lujiuyin f16ac79d68 feat: allow photo selection in preview
Keep each preview session's photo list stable when selection changes, and
show an inline circular selection control across upload, face and recent
photo pages. Allow deselection and reselection without changing the photo
or page number, and synchronize counts and quoted amounts.

Reject stale upload quotes and disable purchase while a valid quote is
unavailable. Show zero totals when all photos are deselected.

Add preview interaction and pricing regressions for all three entry points,
plus optional screenshot capture for design review.

Validation: Debug and Release builds, JVM tests, and simulator regressions.
2026-10-13 14:25:18 +08:00
lujiuyin 3c93572fbc docs: record KIOSK cleanup results and verification evidence 2026-09-20 10:48:56 +08:00
lujiuyin e6b671ef76 chore: remove unused bitmaps and Crashlytics buildtools runtime dependency 2026-09-20 10:46:57 +08:00
lujiuyin 5fe95f9255 fix: restore wrapper and Android quality checks 2026-09-20 10:44:22 +08:00
168 changed files with 4279 additions and 304 deletions
+2
View File
@@ -0,0 +1,2 @@
/gradlew text eol=lf
/gradlew.bat text eol=crlf
-1
View File
@@ -230,7 +230,6 @@ dependencies {
implementation(libs.androidx.compose.foundation) implementation(libs.androidx.compose.foundation)
implementation(libs.firebase.crashlytics.buildtools)
compileOnly(libs.ksp.gradlePlugin) compileOnly(libs.ksp.gradlePlugin)
implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.ktx)
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<lint>
<!-- Glide is used only for image views (GlideEngine). No NotificationTarget,
notification posting, or foreground-service calls exist in app sources.
Match this library-only diagnostic; keep other permission errors enabled. -->
<issue id="NotificationPermission">
<ignore regexp=".*usage from com\.bumptech\.glide\.request\.target\.NotificationTarget.*" />
</issue>
</lint>
@@ -19,6 +19,6 @@ class ExampleInstrumentedTest {
fun useAppContext() { fun useAppContext() {
// Context of the app under test. // Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.zhifly.follow", appContext.packageName) assertEquals("com.yzx.kiosk", appContext.packageName)
} }
} }
@@ -29,6 +29,8 @@ import com.yzx.kiosk.ui.face.resource.FaceCaptureFileStore
import com.yzx.kiosk.ui.face.resource.FaceThumbnailDecoder import com.yzx.kiosk.ui.face.resource.FaceThumbnailDecoder
import com.yzx.kiosk.ui.face.view.* import com.yzx.kiosk.ui.face.view.*
import com.yzx.kiosk.ui.face.viewmodel.* import com.yzx.kiosk.ui.face.viewmodel.*
import com.yzx.kiosk.ui.upload.view.PhotoSelectScreen
import com.yzx.kiosk.ui.upload.viewmodel.PhotoSelectViewModel
import com.yzx.kiosk.websocket.WebSocketService import com.yzx.kiosk.websocket.WebSocketService
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -57,6 +59,7 @@ class RecentPhotosFlowTest {
private val requests = CopyOnWriteArrayList<Request>() private val requests = CopyOnWriteArrayList<Request>()
private lateinit var testRepository: NetWorkRepository private lateinit var testRepository: NetWorkRepository
private var completionVm: ElectronicCompletionViewModel? = null private var completionVm: ElectronicCompletionViewModel? = null
private var uploadVm: PhotoSelectViewModel? = null
@Volatile private var electronicAmount: String? = null @Volatile private var electronicAmount: String? = null
@Volatile private var completionStatus = 30 @Volatile private var completionStatus = 30
@Volatile private var payFails = false @Volatile private var payFails = false
@@ -140,6 +143,7 @@ class RecentPhotosFlowTest {
if (::resultVm.isInitialized) resultVm.viewModelScope.cancel() if (::resultVm.isInitialized) resultVm.viewModelScope.cancel()
if (::faceVm.isInitialized) faceVm.viewModelScope.cancel() if (::faceVm.isInitialized) faceVm.viewModelScope.cancel()
completionVm?.viewModelScope?.cancel() completionVm?.viewModelScope?.cancel()
uploadVm?.viewModelScope?.cancel()
scopedResultVms.forEach { it.viewModelScope.cancel() } scopedResultVms.forEach { it.viewModelScope.cancel() }
restoreConfig?.invoke() restoreConfig?.invoke()
} }
@@ -320,6 +324,221 @@ class RecentPhotosFlowTest {
job.cancel() job.cancel()
} }
@Test fun facePreviewUpdatesSelectionAndBothPurchaseAmounts() {
verifyPreviewSelectionPricing(AppRoutes.FACE_RESULT_SOURCE)
}
@Test fun recentPreviewUpdatesSelectionAndBothPurchaseAmounts() {
verifyPreviewSelectionPricing(AppRoutes.RECENT_RESULT_SOURCE)
}
@Test fun capturePhotoPreviewSelectedAndUnselectedScreenshots() {
val externalDir = checkNotNull(context.getExternalFilesDir(null))
val demo = File(externalDir, "demo-photo.jpg")
Assume.assumeTrue("Screenshot capture requires demo-photo.jpg in the app's external files directory.", demo.isFile)
electronicAmount = "1.00"
val files = (1..3).map { id ->
File.createTempFile("preview-demo-$id-", ".jpg", context.cacheDir).also { demo.copyTo(it, overwrite = true) }
}
val photos = files.mapIndexed { index, file ->
val url = file.toURI().toString()
FaceSearchResult(index + 1, url, url, url, url)
}
compose.setContent { FaceRecognitionResultScreen(results = photos, viewModel = resultVm) }
compose.waitUntil(10_000) { resultVm.photoList.value.size == 3 }
compose.onNodeWithText("全选").performClick()
waitForPreviewQuote(selectedCount = 3, printAmount = "6.00", electronicAmount = "3.00")
compose.onAllNodesWithText("点击预览")[1].performClick()
compose.onNodeWithText("2/3").assertIsDisplayed()
compose.onNodeWithText("上一张").assertIsEnabled()
compose.onNodeWithText("下一张").assertIsEnabled()
compose.onNode(isToggleable()).assertIsOn()
compose.waitUntil(10_000) {
compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo))
.fetchSemanticsNodes().isEmpty()
}
saveFullScreenScreenshot(File(externalDir, "photo-preview-selected.png"))
compose.onNode(isToggleable()).performClick()
waitForPreviewQuote(selectedCount = 2, printAmount = "4.00", electronicAmount = "2.00")
compose.onNodeWithText("2/3").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff()
saveFullScreenScreenshot(File(externalDir, "photo-preview-unselected.png"))
files.forEach { it.delete() }
}
private fun saveFullScreenScreenshot(file: File) {
compose.waitForIdle()
val automation = InstrumentationRegistry.getInstrumentation().uiAutomation
automation.waitForIdle(500, 5_000)
val bitmap = checkNotNull(automation.takeScreenshot())
try {
file.outputStream().use { output ->
check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, output))
}
} finally {
bitmap.recycle()
}
}
@Test fun uploadPreviewUpdatesSelectionAmountAndTypeOneQuoteIds() {
val app = context.applicationContext as com.yzx.kiosk.App
lateinit var vm: PhotoSelectViewModel
compose.runOnUiThread {
vm = PhotoSelectViewModel(nav, app.appState, testRepository, app.appStoreDataSource, testSocket)
uploadVm = vm
}
val fixtures = previewPriceFixtures()
val ids = listOf(41, 42)
val urls = fixtures.mapIndexed { index, file -> "${ids[index]}:${file.toURI()}" }
compose.setContent { PhotoSelectScreen(photoUrls = urls, viewModel = vm) }
if (compose.onAllNodesWithText("我知道了").fetchSemanticsNodes().isNotEmpty()) {
compose.onNodeWithText("我知道了").performClick()
}
compose.waitUntil(10_000) {
vm.photoList.value.size == 2 && !vm.quoteLoading.value && vm.pricePerPhoto.value == "2.00"
}
assertLatestUploadQuoteIds(emptySet())
compose.onNodeWithText("全选").performClick()
waitForUploadQuote(vm, ids.toSet(), "4.00")
assertLatestUploadQuoteIds(ids.toSet())
compose.onNodeWithText("支付4元").assertIsEnabled()
compose.onAllNodesWithText("点击预览")[0].performClick()
compose.onNodeWithText("1/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOn().performClick()
waitForUploadQuote(vm, setOf(ids[1]), "2.00")
assertLatestUploadQuoteIds(setOf(ids[1]))
compose.onNodeWithText("1/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff().performClick()
waitForUploadQuote(vm, ids.toSet(), "4.00")
assertLatestUploadQuoteIds(ids.toSet())
compose.onNode(isToggleable()).performClick()
waitForUploadQuote(vm, setOf(ids[1]), "2.00")
compose.onNodeWithText("下一张").performClick()
compose.onNodeWithText("2/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOn().performClick()
waitForUploadQuote(vm, emptySet(), "0.00")
assertLatestUploadQuoteIds(emptySet())
compose.onNodeWithText("2/2").assertIsDisplayed()
compose.onNodeWithText("上一张").performClick()
compose.onNodeWithText("1/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff().performClick()
waitForUploadQuote(vm, setOf(ids[0]), "2.00")
compose.onNodeWithContentDescription("关闭").performClick()
compose.onNodeWithText("已选择").assertIsDisplayed()
compose.onNodeWithText("1").assertIsDisplayed()
compose.onNodeWithText("支付2元").assertIsEnabled()
compose.onAllNodesWithText("点击预览")[0].performClick()
compose.onNodeWithText("1/1").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOn().performClick()
waitForUploadQuote(vm, emptySet(), "0.00")
assertLatestUploadQuoteIds(emptySet())
compose.onNodeWithText("1/1").assertIsDisplayed()
compose.onNodeWithContentDescription("关闭").performClick()
compose.onNodeWithText("0").assertIsDisplayed()
compose.onNodeWithText("支付0元").assertIsNotEnabled()
assertTrue(requests.none { it.url.encodedPath.endsWith("get-pay-url") })
fixtures.forEach { it.delete() }
}
private fun waitForUploadQuote(vm: PhotoSelectViewModel, selectedIds: Set<Int>, amount: String) {
compose.waitUntil(10_000) {
vm.selectedPhotoIds.value == selectedIds && !vm.quoteLoading.value && vm.totalPrice.value == amount
}
}
private fun assertLatestUploadQuoteIds(expectedIds: Set<Int>) {
val quote = requests.filter { it.url.encodedPath.endsWith("verify-result") }.map { request ->
val body = okio.Buffer().also { request.body!!.writeTo(it) }.readUtf8()
Gson().fromJson(body, com.google.gson.JsonObject::class.java)
}.last { it.get("type").asInt == 1 }
assertEquals(expectedIds, quote.getAsJsonArray("image_id").map { it.asInt }.toSet())
assertFalse(quote.has("video_id"))
}
private fun previewPriceFixtures(): List<File> =
(1..2).map { id ->
val file = File.createTempFile("preview-price-$id-", ".png", context.cacheDir)
val image = Bitmap.createBitmap(160, 100, Bitmap.Config.ARGB_8888).apply {
eraseColor(if (id == 1) Color.GREEN else Color.BLUE)
}
file.outputStream().use { image.compress(Bitmap.CompressFormat.PNG, 100, it) }
image.recycle()
file
}
private fun verifyPreviewSelectionPricing(source: String) {
electronicAmount = "1.00"
val fixtures = previewPriceFixtures()
val photos = fixtures.mapIndexed { index, file ->
val url = file.toURI().toString()
FaceSearchResult(index + 1, url, url, url, url)
}
recentBody = Gson().toJson(mapOf("count" to photos.size, "results" to photos))
compose.setContent {
FaceRecognitionResultScreen(
results = if (source == AppRoutes.FACE_RESULT_SOURCE) photos else emptyList(),
source = source,
viewModel = resultVm
)
}
compose.waitUntil(10_000) { resultVm.photoList.value.size == 2 }
compose.onNodeWithText("全选").performClick()
waitForPreviewQuote(selectedCount = 2, printAmount = "4.00", electronicAmount = "2.00")
compose.onNodeWithText("已选择 2 张").assertIsDisplayed()
compose.onNodeWithText("购买打印照片\n4元").assertIsEnabled()
compose.onNodeWithText("购买电子照片\n2元").assertIsEnabled()
compose.onAllNodesWithText("点击预览")[0].performClick()
compose.onNodeWithText("1/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOn().performClick()
waitForPreviewQuote(selectedCount = 1, printAmount = "2.00", electronicAmount = "1.00")
compose.onNodeWithText("1/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff()
compose.runOnIdle { assertEquals(setOf(fixtures[1].toURI().toString()), resultVm.selectedPhotos.value) }
compose.onNodeWithText("下一张").performClick()
compose.onNodeWithText("2/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOn().performClick()
waitForPreviewQuote(selectedCount = 0, printAmount = "0.00", electronicAmount = "0.00")
compose.onNodeWithText("2/2").assertIsDisplayed()
compose.onNodeWithContentDescription("关闭").assertIsDisplayed()
compose.onNodeWithText("上一张").performClick()
compose.onNodeWithText("1/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff().performClick()
waitForPreviewQuote(selectedCount = 1, printAmount = "2.00", electronicAmount = "1.00")
compose.runOnIdle { assertEquals(setOf(fixtures[0].toURI().toString()), resultVm.selectedPhotos.value) }
compose.onNodeWithContentDescription("关闭").performClick()
compose.onNodeWithText("已选择 1 张").assertIsDisplayed()
compose.onNodeWithText("购买打印照片\n2元").assertIsEnabled()
compose.onNodeWithText("购买电子照片\n1元").assertIsEnabled()
// Reopening takes the current selection, rather than retaining the previous session's two photos.
compose.onAllNodesWithText("点击预览")[0].performClick()
compose.onNodeWithText("1/1").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOn().performClick()
waitForPreviewQuote(selectedCount = 0, printAmount = "0.00", electronicAmount = "0.00")
compose.onNodeWithText("1/1").assertIsDisplayed()
compose.onNodeWithContentDescription("关闭").performClick()
compose.onNodeWithText("已选择 0 张").assertIsDisplayed()
compose.onNodeWithText("购买打印照片\n0元").assertIsNotEnabled()
compose.onNodeWithText("购买电子照片\n0元").assertIsNotEnabled()
assertTrue(requests.none { it.url.encodedPath.endsWith("get-pay-url") })
fixtures.forEach { it.delete() }
}
private fun waitForPreviewQuote(selectedCount: Int, printAmount: String, electronicAmount: String) {
compose.waitUntil(10_000) {
resultVm.selectedPhotos.value.size == selectedCount &&
!resultVm.quoteLoading.value && resultVm.totalPrice.value == printAmount &&
resultVm.electronicTotal.value == electronicAmount
}
}
private fun showElectronicSelection(amount: String?) { private fun showElectronicSelection(amount: String?) {
electronicAmount = amount electronicAmount = amount
val image = Bitmap.createBitmap(160, 100, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.BLUE) } val image = Bitmap.createBitmap(160, 100, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.BLUE) }
@@ -0,0 +1,191 @@
package com.yzx.kiosk.ui.upload.view
import android.graphics.Bitmap
import android.graphics.Color
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.assertIsOff
import androidx.compose.ui.test.assertIsOn
import androidx.compose.ui.test.isToggleable
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.platform.app.InstrumentationRegistry
import com.yzx.kiosk.theme.AppTheme
import java.io.File
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
class PhotoPreviewDialogTest {
@get:Rule val compose = createComposeRule()
private val fixtures = mutableListOf<File>()
@After fun deleteFixtures() {
fixtures.forEach { it.delete() }
}
@Test fun cancellingCurrentPhotoKeepsItsPageAndEachPhotoRemembersSelection() {
val photos = photoFixtures(3)
var selectedIds by mutableStateOf(photos.map { it.id }.toSet())
val toggledIds = mutableListOf<Int>()
compose.setContent {
AppTheme {
PhotoPreviewDialog(
photoList = photos,
initialIndex = 1,
selectedPhotoIds = selectedIds,
onToggleSelection = { photo ->
toggledIds.add(photo.id)
selectedIds = if (photo.id in selectedIds) selectedIds - photo.id else selectedIds + photo.id
},
onDismiss = {}
)
}
}
compose.onNodeWithText("2/3").assertIsDisplayed()
val previousBounds = compose.onNodeWithText("上一张").fetchSemanticsNode().boundsInRoot
val selectionBounds = compose.onNode(isToggleable()).fetchSemanticsNode().boundsInRoot
val nextBounds = compose.onNodeWithText("下一张").fetchSemanticsNode().boundsInRoot
assertTrue(previousBounds.center.x < selectionBounds.center.x)
assertTrue(selectionBounds.center.x < nextBounds.center.x)
assertEquals(previousBounds.center.y, selectionBounds.center.y, 1f)
assertEquals(nextBounds.center.y, selectionBounds.center.y, 1f)
compose.onNode(isToggleable()).assertIsOn().performClick()
compose.onNodeWithText("2/3").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff()
compose.runOnIdle {
assertEquals(listOf(photos[1].id), toggledIds)
assertEquals(setOf(photos[0].id, photos[2].id), selectedIds)
}
compose.onNodeWithText("下一张").performClick()
compose.onNodeWithText("3/3").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOn()
compose.onNodeWithText("上一张").performClick()
compose.onNodeWithText("2/3").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff().performClick()
compose.onNodeWithText("2/3").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOn()
compose.runOnIdle { assertEquals(photos.map { it.id }.toSet(), selectedIds) }
}
@Test fun cancellingEveryPhotoLeavesPreviewOpenAndAllowsReselection() {
val photos = photoFixtures(2)
var selectedIds by mutableStateOf(photos.map { it.id }.toSet())
var dismissed = false
compose.setContent {
AppTheme {
PhotoPreviewDialog(
photoList = photos,
initialIndex = 0,
selectedPhotoIds = selectedIds,
onToggleSelection = { photo ->
selectedIds = if (photo.id in selectedIds) selectedIds - photo.id else selectedIds + photo.id
},
onDismiss = { dismissed = true }
)
}
}
compose.onNodeWithText("上一张").assertIsNotEnabled()
compose.onNode(isToggleable()).performClick()
compose.onNodeWithText("下一张").performClick()
compose.onNode(isToggleable()).performClick()
compose.onNodeWithText("2/2").assertIsDisplayed()
compose.onNodeWithText("下一张").assertIsNotEnabled()
compose.onNodeWithContentDescription("关闭").assertIsDisplayed()
compose.runOnIdle {
assertTrue(selectedIds.isEmpty())
assertTrue(!dismissed)
}
compose.onNodeWithText("上一张").performClick()
compose.onNodeWithText("1/2").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff().performClick()
compose.onNode(isToggleable()).assertIsOn()
compose.runOnIdle { assertEquals(setOf(photos[0].id), selectedIds) }
}
@Test fun reopeningUsesTheNewPhotoListAndInitialPage() {
val photos = photoFixtures(3)
var previewPhotos by mutableStateOf(photos)
var selectedIds by mutableStateOf(photos.map { it.id }.toSet())
var initialIndex by mutableStateOf(1)
var visible by mutableStateOf(true)
compose.setContent {
AppTheme {
if (visible) {
PhotoPreviewDialog(
photoList = previewPhotos,
initialIndex = initialIndex,
selectedPhotoIds = selectedIds,
onToggleSelection = { photo ->
selectedIds = if (photo.id in selectedIds) selectedIds - photo.id else selectedIds + photo.id
},
onDismiss = { visible = false }
)
}
}
}
compose.onNodeWithText("2/3").assertIsDisplayed()
compose.onNodeWithContentDescription("关闭").performClick()
compose.onNodeWithContentDescription("关闭").assertDoesNotExist()
compose.runOnIdle {
previewPhotos = listOf(photos[2])
selectedIds = setOf(photos[2].id)
initialIndex = 0
visible = true
}
compose.onNodeWithText("1/1").assertIsDisplayed()
compose.onNodeWithText("上一张").assertIsNotEnabled()
compose.onNodeWithText("下一张").assertIsNotEnabled()
compose.onNode(isToggleable()).assertIsOn().performClick()
compose.onNodeWithText("1/1").assertIsDisplayed()
compose.onNode(isToggleable()).assertIsOff()
compose.runOnIdle { assertTrue(selectedIds.isEmpty()) }
}
@Test fun disabledSelectionDoesNotChangeCurrentPhoto() {
val photos = photoFixtures(1)
var toggleCount = 0
compose.setContent {
AppTheme {
PhotoPreviewDialog(
photoList = photos,
initialIndex = 0,
selectedPhotoIds = setOf(photos[0].id),
onToggleSelection = { toggleCount++ },
selectionEnabled = false,
onDismiss = {}
)
}
}
compose.onNode(isToggleable()).assertIsOn().assertIsNotEnabled().performClick()
compose.onNodeWithText("1/1").assertIsDisplayed()
compose.runOnIdle { assertEquals(0, toggleCount) }
}
private fun photoFixtures(count: Int): List<PhotoPreviewItem> {
val context = InstrumentationRegistry.getInstrumentation().targetContext
return (1..count).map { id ->
val file = File.createTempFile("preview-$id-", ".png", context.cacheDir).also { fixtures.add(it) }
val bitmap = Bitmap.createBitmap(160, 100, Bitmap.Config.ARGB_8888).apply {
eraseColor(if (id % 2 == 0) Color.BLUE else Color.GREEN)
}
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
bitmap.recycle()
PhotoPreviewItem(id = id, url = file.toURI().toString())
}
}
}
@@ -30,6 +30,7 @@ import kotlinx.coroutines.flow.collectLatest
import java.net.URLDecoder import java.net.URLDecoder
import java.net.URLEncoder import java.net.URLEncoder
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable @Composable
fun AppNavHost( fun AppNavHost(
navigator: AppNavigator, navigator: AppNavigator,
@@ -55,6 +55,7 @@ import com.yzx.kiosk.network.model.response.FaceSearchResult
import com.yzx.kiosk.ui.common.view.FullScreenMode import com.yzx.kiosk.ui.common.view.FullScreenMode
import com.yzx.kiosk.ui.face.viewmodel.FaceRecognitionResultViewModel import com.yzx.kiosk.ui.face.viewmodel.FaceRecognitionResultViewModel
import com.yzx.kiosk.ui.upload.view.PhotoPreviewDialog import com.yzx.kiosk.ui.upload.view.PhotoPreviewDialog
import com.yzx.kiosk.ui.upload.view.PhotoPreviewItem
import com.yzx.kiosk.ui.upload.view.RetryableAsyncImage import com.yzx.kiosk.ui.upload.view.RetryableAsyncImage
import com.yzx.kiosk.utils.QrCodeUtils import com.yzx.kiosk.utils.QrCodeUtils
import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collect
@@ -104,6 +105,7 @@ fun FaceRecognitionResultScreen(
// 预览弹框状态 // 预览弹框状态
var showPreviewDialog by remember { mutableStateOf(false) } var showPreviewDialog by remember { mutableStateOf(false) }
var previewInitialIndex by remember { mutableIntStateOf(0) } var previewInitialIndex by remember { mutableIntStateOf(0) }
var previewPhotos by remember { mutableStateOf<List<PhotoPreviewItem>>(emptyList()) }
// 支付弹框状态 // 支付弹框状态
var showPayDialog by remember { mutableStateOf(false) } var showPayDialog by remember { mutableStateOf(false) }
@@ -315,10 +317,13 @@ fun FaceRecognitionResultScreen(
loadState = loadState, loadState = loadState,
onToggleSelection = { viewModel.togglePhotoSelection(photo.url) }, onToggleSelection = { viewModel.togglePhotoSelection(photo.url) },
onPreviewClick = { onPreviewClick = {
// 计算在已选列表中的索引 // 固定本次预览列表,取消选择后仍可查看和重新勾选。
val selectedList = photoList.filter { selectedPhotos.contains(it.url) } val selectedList = photoList
val selectedIndex = selectedList.indexOfFirst { it.url == photo.url } .filter { selectedPhotos.contains(it.url) }
.map { PhotoPreviewItem(id = it.id, url = it.url) }
val selectedIndex = selectedList.indexOfFirst { it.id == photo.id }
if (selectedIndex >= 0) { if (selectedIndex >= 0) {
previewPhotos = selectedList
previewInitialIndex = selectedIndex previewInitialIndex = selectedIndex
showPreviewDialog = true showPreviewDialog = true
} }
@@ -335,13 +340,19 @@ fun FaceRecognitionResultScreen(
} }
} }
// 预览弹框 - 仅预览已选择的图片 // 预览列表在打开时固定,选择状态与网格实时同步。
val selectedPhotoUrls = photoList.filter { selectedPhotos.contains(it.url) }.map { it.url } val selectedPhotoIds = previewPhotos.filter { selectedPhotos.contains(it.url) }.map { it.id }.toSet()
if (showPreviewDialog && selectedPhotoUrls.isNotEmpty()) { if (showPreviewDialog && previewPhotos.isNotEmpty()) {
PhotoPreviewDialog( PhotoPreviewDialog(
photoList = selectedPhotoUrls, photoList = previewPhotos,
initialIndex = previewInitialIndex, initialIndex = previewInitialIndex,
onDismiss = { showPreviewDialog = false } selectedPhotoIds = selectedPhotoIds,
onToggleSelection = { viewModel.togglePhotoSelection(it.url) },
selectionEnabled = !creatingOrder,
onDismiss = {
showPreviewDialog = false
previewPhotos = emptyList()
}
) )
} }
@@ -309,9 +309,9 @@ class FaceRecognitionResultViewModel @Inject constructor(
val revision = quoteRevision.next() val revision = quoteRevision.next()
quoteJob?.cancel() quoteJob?.cancel()
_pricePerPhoto.value = "--" _pricePerPhoto.value = "--"
_totalPrice.value = "--" _totalPrice.value = if (imageIds.isEmpty()) "0.00" else "--"
_electronicPrice.value = "--" _electronicPrice.value = "--"
_electronicTotal.value = "--" _electronicTotal.value = if (imageIds.isEmpty()) "0.00" else "--"
quoteJob = viewModelScope.launch { quoteJob = viewModelScope.launch {
try { try {
val response = netWorkRepository.verifyResult(VerifyResultRequest(2, imageIds.distinct(), videoId = emptyList())).first() val response = netWorkRepository.verifyResult(VerifyResultRequest(2, imageIds.distinct(), videoId = emptyList())).first()
@@ -329,13 +329,13 @@ class FaceRecognitionResultViewModel @Inject constructor(
val printTotal = money(data.amount) val printTotal = money(data.amount)
if (printUnit != null && printTotal != null) { if (printUnit != null && printTotal != null) {
_pricePerPhoto.value = printUnit _pricePerPhoto.value = printUnit
_totalPrice.value = printTotal _totalPrice.value = if (imageIds.isEmpty()) "0.00" else printTotal
} }
val electronicUnit = money(data.priceElectronic) val electronicUnit = money(data.priceElectronic)
val electronicTotal = money(data.amountElectronic) val electronicTotal = money(data.amountElectronic)
if (electronicQuoteAvailable(electronicUnit, electronicTotal, imageIds.isNotEmpty())) { if (electronicQuoteAvailable(electronicUnit, electronicTotal, imageIds.isNotEmpty())) {
_electronicPrice.value = checkNotNull(electronicUnit) _electronicPrice.value = checkNotNull(electronicUnit)
_electronicTotal.value = checkNotNull(electronicTotal) _electronicTotal.value = if (imageIds.isEmpty()) "0.00" else checkNotNull(electronicTotal)
} }
} catch (e: CancellationException) { } catch (e: CancellationException) {
throw e throw e
@@ -92,6 +92,7 @@ fun PosterScreenWithLiveOrSlideshow(
} }
} }
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
@Composable @Composable
private fun PosterLiveStreamLayer( private fun PosterLiveStreamLayer(
url: String, url: String,
@@ -2,10 +2,13 @@ package com.yzx.kiosk.ui.upload.view
import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
@@ -18,8 +21,10 @@ import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
@@ -35,9 +40,11 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
@@ -49,22 +56,33 @@ import com.yzx.kiosk.utils.LogUtils
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
/** 本次预览中的稳定照片标识,不随勾选状态变化。 */
data class PhotoPreviewItem(val id: Int, val url: String)
/** /**
* 图片预览弹框 - 全屏展示,仅预览已选择的图片 * 全屏预览本次打开时选中的照片,购买选择由调用页面实时维护。
*/ */
@OptIn(ExperimentalFoundationApi::class) @OptIn(ExperimentalFoundationApi::class)
@Composable @Composable
fun PhotoPreviewDialog( fun PhotoPreviewDialog(
photoList: List<String>, photoList: List<PhotoPreviewItem>,
initialIndex: Int, initialIndex: Int,
selectedPhotoIds: Set<Int>,
onToggleSelection: (PhotoPreviewItem) -> Unit,
selectionEnabled: Boolean = true,
onDismiss: () -> Unit onDismiss: () -> Unit
) { ) {
if (photoList.isEmpty()) return
val pagerState = rememberPagerState( val pagerState = rememberPagerState(
initialPage = initialIndex, initialPage = initialIndex.coerceIn(0, photoList.lastIndex),
pageCount = { photoList.size } pageCount = { photoList.size }
) )
val coroutineScope = rememberCoroutineScope() val coroutineScope = rememberCoroutineScope()
val currentIndex = pagerState.currentPage val currentIndex = pagerState.currentPage
val currentPhoto = photoList[currentIndex]
val isSelected = currentPhoto.id in selectedPhotoIds
val canToggleSelection = selectionEnabled && !pagerState.isScrollInProgress
Dialog( Dialog(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
@@ -127,15 +145,33 @@ fun PhotoPreviewDialog(
) { ) {
Spacer(modifier = Modifier.height(36.dp)) Spacer(modifier = Modifier.height(36.dp))
// 上一张/下一张按钮 // 翻页与当前照片的勾选集中在同一操作行。
Row( BoxWithConstraints(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 48.dp), .padding(horizontal = 24.dp)
horizontalArrangement = Arrangement.SpaceBetween, ) {
val narrow = maxWidth < 250.dp
val controlFontSize = when {
narrow -> 14.sp
maxWidth < 360.dp -> 17.sp
else -> 21.sp
}
val selectionIndicatorSize = when {
narrow -> 20.dp
maxWidth < 360.dp -> 24.dp
else -> 28.dp
}
val selectionCheckSize = when {
narrow -> 16.dp
maxWidth < 360.dp -> 18.dp
else -> 22.dp
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
// 上一张按钮
Button( Button(
onClick = { onClick = {
if (currentIndex > 0) { if (currentIndex > 0) {
@@ -150,16 +186,62 @@ fun PhotoPreviewDialog(
containerColor = Color(0xFF2196F3), containerColor = Color(0xFF2196F3),
disabledContainerColor = Color(0xFFF4F4F4) disabledContainerColor = Color(0xFFF4F4F4)
), ),
modifier = Modifier.width(111.dp).height(56.dp) contentPadding = PaddingValues(horizontal = 8.dp),
modifier = Modifier.weight(1f).height(56.dp)
) { ) {
Text( Text(
text = "上一张", text = "上一张",
fontSize = 21.sp, fontSize = controlFontSize,
maxLines = 1,
color = if (currentIndex > 0) Color.White else Color(0xFF999999), color = if (currentIndex > 0) Color.White else Color(0xFF999999),
fontWeight = FontWeight.Bold) fontWeight = FontWeight.Bold
)
}
val selectionColor = if (isSelected) Color(0xFF0073FF) else Color(0xFF757575)
Row(
modifier = Modifier
.weight(1.4f)
.height(56.dp)
.clip(RoundedCornerShape(18.dp))
.alpha(if (canToggleSelection) 1f else 0.5f)
.toggleable(
value = isSelected,
enabled = canToggleSelection,
role = Role.Checkbox,
onValueChange = { onToggleSelection(currentPhoto) }
)
.padding(horizontal = 8.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Box(
modifier = Modifier
.size(selectionIndicatorSize)
.clip(CircleShape)
.background(if (isSelected) Color(0xFF0073FF) else Color.Transparent)
.border(1.5.dp, selectionColor, CircleShape),
contentAlignment = Alignment.Center
) {
if (isSelected) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = null,
tint = Color.White,
modifier = Modifier.size(selectionCheckSize)
)
}
}
Spacer(Modifier.width(if (narrow) 6.dp else 8.dp))
Text(
text = if (isSelected) "已选择" else "未选择",
fontSize = controlFontSize,
maxLines = 1,
color = if (isSelected) Color(0xFF0073FF) else Color(0xFF616161),
fontWeight = FontWeight.Bold
)
} }
// 下一张按钮
Button( Button(
onClick = { onClick = {
if (currentIndex < photoList.size - 1) { if (currentIndex < photoList.size - 1) {
@@ -174,13 +256,17 @@ fun PhotoPreviewDialog(
containerColor = Color(0xFF2196F3), containerColor = Color(0xFF2196F3),
disabledContainerColor = Color(0xFFF4F4F4) disabledContainerColor = Color(0xFFF4F4F4)
), ),
modifier = Modifier.width(111.dp).height(56.dp) contentPadding = PaddingValues(horizontal = 8.dp),
modifier = Modifier.weight(1f).height(56.dp)
) { ) {
Text( Text(
text = "下一张", text = "下一张",
fontSize = 21.sp, fontSize = controlFontSize,
maxLines = 1,
color = if (currentIndex < photoList.size - 1) Color.White else Color(0xFF999999), color = if (currentIndex < photoList.size - 1) Color.White else Color(0xFF999999),
fontWeight = FontWeight.Bold) fontWeight = FontWeight.Bold
)
}
} }
} }
@@ -189,6 +275,7 @@ fun PhotoPreviewDialog(
// 图片轮播 // 图片轮播
HorizontalPager( HorizontalPager(
state = pagerState, state = pagerState,
key = { photoList[it].id },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 48.dp) .padding(horizontal = 48.dp)
@@ -200,7 +287,7 @@ fun PhotoPreviewDialog(
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
) { ) {
RetryableAsyncImage( RetryableAsyncImage(
imageUrl = photoList[page], imageUrl = photoList[page].url,
modifier = Modifier.fillMaxWidth().background(color = Color.White, shape = RoundedCornerShape(18.dp)), modifier = Modifier.fillMaxWidth().background(color = Color.White, shape = RoundedCornerShape(18.dp)),
contentScale = ContentScale.Fit, contentScale = ContentScale.Fit,
maxRetries = 10 maxRetries = 10
@@ -208,7 +295,14 @@ fun PhotoPreviewDialog(
} }
} }
Spacer(modifier = Modifier.height(36.dp)) Spacer(modifier = Modifier.height(24.dp))
Text(
text = "已选择 ${selectedPhotoIds.size} 张",
modifier = Modifier.align(Alignment.CenterHorizontally),
fontSize = 18.sp,
color = Color(0xFF666666)
)
Spacer(modifier = Modifier.height(24.dp))
} }
} }
} }
@@ -66,6 +66,7 @@ fun PhotoSelectScreen(
val selectedPhotoIds by viewModel.selectedPhotoIds.collectAsState() val selectedPhotoIds by viewModel.selectedPhotoIds.collectAsState()
val pricePerPhoto by viewModel.pricePerPhoto.collectAsState() // 从接口获取的单价(字符串) val pricePerPhoto by viewModel.pricePerPhoto.collectAsState() // 从接口获取的单价(字符串)
val totalPrice by viewModel.totalPrice.collectAsState() // 从接口获取的总价(字符串) val totalPrice by viewModel.totalPrice.collectAsState() // 从接口获取的总价(字符串)
val quoteLoading by viewModel.quoteLoading.collectAsState()
val selectedCount = selectedPhotoIds.size val selectedCount = selectedPhotoIds.size
val isAllSelected = photoList.isNotEmpty() && selectedPhotoIds.size == photoList.size val isAllSelected = photoList.isNotEmpty() && selectedPhotoIds.size == photoList.size
@@ -73,6 +74,7 @@ fun PhotoSelectScreen(
// 预览弹框状态 // 预览弹框状态
var showPreviewDialog by remember { mutableStateOf(false) } var showPreviewDialog by remember { mutableStateOf(false) }
var previewInitialIndex by remember { mutableIntStateOf(0) } var previewInitialIndex by remember { mutableIntStateOf(0) }
var previewPhotos by remember { mutableStateOf<List<PhotoPreviewItem>>(emptyList()) }
// 支付弹框状态 // 支付弹框状态
var showPayDialog by remember { mutableStateOf(false) } var showPayDialog by remember { mutableStateOf(false) }
@@ -168,10 +170,15 @@ fun PhotoSelectScreen(
.widthIn(min = 180.dp), .widthIn(min = 180.dp),
shape = RoundedCornerShape(18.dp), shape = RoundedCornerShape(18.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF0073FF)), colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF0073FF)),
enabled = selectedCount > 0 enabled = selectedCount > 0 && totalPrice != "--" && !quoteLoading
) { ) {
Text( Text(
text = if (selectedCount > 0) "支付${formatPriceDisplay(totalPrice)}元" else "支付0元", text = when {
selectedCount == 0 -> "支付0元"
quoteLoading -> "正在更新价格…"
totalPrice == "--" -> "价格暂不可用"
else -> "支付${formatPriceDisplay(totalPrice)}元"
},
fontSize = 24.sp, fontSize = 24.sp,
color = Color.White, color = Color.White,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
@@ -242,10 +249,13 @@ fun PhotoSelectScreen(
isSelected = isSelected, isSelected = isSelected,
onToggleSelection = { viewModel.togglePhotoSelection(photo.id) }, onToggleSelection = { viewModel.togglePhotoSelection(photo.id) },
onPreviewClick = { onPreviewClick = {
// 计算在已选列表中的索引 // 固定本次预览列表,取消选择后仍可查看和重新勾选。
val selectedList = photoList.filter { selectedPhotoIds.contains(it.id) } val selectedList = photoList
.filter { selectedPhotoIds.contains(it.id) }
.map { PhotoPreviewItem(id = it.id, url = it.url) }
val selectedIndex = selectedList.indexOfFirst { it.id == photo.id } val selectedIndex = selectedList.indexOfFirst { it.id == photo.id }
if (selectedIndex >= 0) { if (selectedIndex >= 0) {
previewPhotos = selectedList
previewInitialIndex = selectedIndex previewInitialIndex = selectedIndex
showPreviewDialog = true showPreviewDialog = true
} }
@@ -264,13 +274,17 @@ fun PhotoSelectScreen(
) )
} }
// 预览弹框 - 仅预览已选择的图片 // 预览列表在打开时固定,选择状态与网格实时同步。
val selectedPhotoUrls = photoList.filter { selectedPhotoIds.contains(it.id) }.map { it.url } if (showPreviewDialog && previewPhotos.isNotEmpty()) {
if (showPreviewDialog && selectedPhotoUrls.isNotEmpty()) {
PhotoPreviewDialog( PhotoPreviewDialog(
photoList = selectedPhotoUrls, photoList = previewPhotos,
initialIndex = previewInitialIndex, initialIndex = previewInitialIndex,
onDismiss = { showPreviewDialog = false } selectedPhotoIds = selectedPhotoIds,
onToggleSelection = { viewModel.togglePhotoSelection(it.id) },
onDismiss = {
showPreviewDialog = false
previewPhotos = emptyList()
}
) )
} }
@@ -6,6 +6,7 @@ import coil.request.ImageRequest
import coil.size.Size import coil.size.Size
import com.yzx.kiosk.App import com.yzx.kiosk.App
import com.yzx.kiosk.base.BaseViewModel import com.yzx.kiosk.base.BaseViewModel
import com.yzx.kiosk.component.auth.GlobalAuthDialogManager
import com.yzx.kiosk.datastore.AppState import com.yzx.kiosk.datastore.AppState
import com.yzx.kiosk.navigation.AppNavigator import com.yzx.kiosk.navigation.AppNavigator
import com.yzx.kiosk.navigation.routes.AppRoutes import com.yzx.kiosk.navigation.routes.AppRoutes
@@ -13,6 +14,8 @@ import com.yzx.kiosk.network.model.request.GetPayUrlRequest
import com.yzx.kiosk.network.model.request.VerifyResultRequest import com.yzx.kiosk.network.model.request.VerifyResultRequest
import com.yzx.kiosk.network.repository.NetWorkRepository import com.yzx.kiosk.network.repository.NetWorkRepository
import com.yzx.kiosk.network.result.asResult import com.yzx.kiosk.network.result.asResult
import com.yzx.kiosk.ui.face.viewmodel.QuoteRevision
import com.yzx.kiosk.ui.face.viewmodel.money
import com.yzx.kiosk.utils.ToastUtils import com.yzx.kiosk.utils.ToastUtils
import com.yzx.kiosk.websocket.WebSocketService import com.yzx.kiosk.websocket.WebSocketService
import com.yzx.kiosk.websocket.UploadPhotoEvent import com.yzx.kiosk.websocket.UploadPhotoEvent
@@ -23,13 +26,16 @@ import com.yzx.kiosk.datastore.AppStoreDataSource
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
import com.yzx.kiosk.utils.LogUtils import com.yzx.kiosk.utils.LogUtils
@@ -97,9 +103,14 @@ class PhotoSelectViewModel @Inject constructor(
val pricePerPhoto: StateFlow<String> = _pricePerPhoto.asStateFlow() val pricePerPhoto: StateFlow<String> = _pricePerPhoto.asStateFlow()
// 总价(从接口获取) // 总价(从接口获取)
private val _totalPrice = MutableStateFlow("--") private val _totalPrice = MutableStateFlow("0.00")
val totalPrice: StateFlow<String> = _totalPrice.asStateFlow() val totalPrice: StateFlow<String> = _totalPrice.asStateFlow()
private val _quoteLoading = MutableStateFlow(false)
val quoteLoading: StateFlow<Boolean> = _quoteLoading.asStateFlow()
private val quoteRevision = QuoteRevision()
private var quoteJob: Job? = null
// 支付二维码URL // 支付二维码URL
private val _payQrCodeUrl = MutableStateFlow<String?>(null) private val _payQrCodeUrl = MutableStateFlow<String?>(null)
val payQrCodeUrl: StateFlow<String?> = _payQrCodeUrl.asStateFlow() val payQrCodeUrl: StateFlow<String?> = _payQrCodeUrl.asStateFlow()
@@ -155,6 +166,7 @@ class PhotoSelectViewModel @Inject constructor(
// 如果没有传入数据,清空列表 // 如果没有传入数据,清空列表
_photoList.value = emptyList() _photoList.value = emptyList()
_selectedPhotoIds.value = emptySet() _selectedPhotoIds.value = emptySet()
verifyResult(emptyList())
return return
} }
@@ -226,6 +238,7 @@ class PhotoSelectViewModel @Inject constructor(
if (initialPhotos.isEmpty()) { if (initialPhotos.isEmpty()) {
_photoList.value = emptyList() _photoList.value = emptyList()
_selectedPhotoIds.value = emptySet() _selectedPhotoIds.value = emptySet()
verifyResult(emptyList())
return@launch return@launch
} }
@@ -403,50 +416,39 @@ class PhotoSelectViewModel @Inject constructor(
* @param imageIds 选中的图片ID数组 * @param imageIds 选中的图片ID数组
*/ */
private fun verifyResult(imageIds: List<Int>) { private fun verifyResult(imageIds: List<Int>) {
viewModelScope.launch { val revision = quoteRevision.next()
quoteJob?.cancel()
// 选择变化后,旧金额立即失效;空选择始终显示 0。
_totalPrice.value = if (imageIds.isEmpty()) "0.00" else "--"
_quoteLoading.value = true
quoteJob = viewModelScope.launch {
try { try {
val request = VerifyResultRequest( // 直接在当前 Job 收集,取消时同时取消实际报价请求。
type = 1, val response = netWorkRepository.verifyResult(
imageId = imageIds VerifyResultRequest(type = 1, imageId = imageIds)
) ).first()
if (!quoteRevision.isCurrent(revision)) return@launch
handleResultWithData( if (response.isTokenFailed) {
flow = netWorkRepository.verifyResult(request).asResult(), GlobalAuthDialogManager.show()
showToast = false, return@launch
onData = { response -> }
// 更新单价(使用接口返回的 price_image) if (!response.isSucceeded || response.data == null) {
val priceImage = response.priceImage LogUtils.e("PhotoSelectViewModel", "验证结果失败: ${response.message}")
if (!priceImage.isNullOrEmpty()) { return@launch
_pricePerPhoto.value = priceImage
} else {
_pricePerPhoto.value = "--"
} }
// 更新总价(使用接口返回的 amount) val data = response.data
val amount = response.amount // 初始化的空列表请求仍用于取得单价,不让服务端金额覆盖空选择的 0。
if (!amount.isNullOrEmpty()) { _pricePerPhoto.value = money(data.priceImage) ?: "--"
_totalPrice.value = amount _totalPrice.value = if (imageIds.isEmpty()) "0.00" else money(data.amount) ?: "--"
} else { LogUtils.d("PhotoSelectViewModel", "验证结果成功 - 单价: ${data.priceImage}, 总价: ${data.amount}")
_totalPrice.value = "--" } catch (e: CancellationException) {
} throw e
LogUtils.d("PhotoSelectViewModel", "验证结果成功 - 单价: $priceImage, 总价: $amount")
},
onError = { msg, _ ->
LogUtils.e("PhotoSelectViewModel", "验证结果失败: $msg")
// 接口失败时,保持当前值或设置为默认值
if (_selectedPhotoIds.value.isEmpty()) {
_pricePerPhoto.value = "--"
_totalPrice.value = "--"
}
}
)
} catch (e: Exception) { } catch (e: Exception) {
LogUtils.e("PhotoSelectViewModel", "验证结果异常: ${e.message}") LogUtils.e("PhotoSelectViewModel", "验证结果异常: ${e.message}")
if (_selectedPhotoIds.value.isEmpty()) { } finally {
_pricePerPhoto.value = "--" // 旧请求的完成/取消不能结束当前请求的加载状态。
_totalPrice.value = "--" if (quoteRevision.isCurrent(revision)) _quoteLoading.value = false
}
} }
} }
} }
@@ -461,6 +463,10 @@ class PhotoSelectViewModel @Inject constructor(
ToastUtils.show("请选择要打印的照片") ToastUtils.show("请选择要打印的照片")
return@launch return@launch
} }
if (_quoteLoading.value || money(_totalPrice.value) == null) {
ToastUtils.show(if (_quoteLoading.value) "正在更新价格,请稍候" else "价格获取失败,请重新选择照片")
return@launch
}
try { try {
val request = GetPayUrlRequest( val request = GetPayUrlRequest(
Binary file not shown.

Before

Width:  |  Height:  |  Size: 814 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 630 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 656 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 766 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 657 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 806 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 912 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 726 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 778 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 922 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 810 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 926 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 850 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 862 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 770 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 864 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 706 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 902 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 750 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 740 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 796 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 816 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 884 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 862 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 832 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 810 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 704 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 924 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1016 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 822 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 998 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 972 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 874 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 920 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 914 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 966 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 638 B

Some files were not shown because too many files have changed in this diff Show More