feat(xiaoyi): add super-admin product presets to the project wizard
This commit is contained in:
parent
414a3e87bc
commit
c2112aa9de
@ -34,7 +34,7 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
|
||||
else throw new DesktopClientError('接口不存在',404)
|
||||
}else{
|
||||
const auth=await requireDesktop(request),ownerId=auth.account.id
|
||||
if(parts[0]==='session'&&parts.length===1){if(method==='GET')value={account:auth.account,expiresAt:auth.expiresAt};else if(method==='DELETE'){await revokeDesktop(auth.id,ownerId);value={revoked:true}}else throw new DesktopClientError('接口不存在',404)}
|
||||
if(parts[0]==='session'&&parts.length===1){if(method==='GET')value={account:{...auth.account,isSuperAdmin:auth.isSuperAdmin},expiresAt:auth.expiresAt};else if(method==='DELETE'){await revokeDesktop(auth.id,ownerId);value={revoked:true}}else throw new DesktopClientError('接口不存在',404)}
|
||||
else if(parts[0]==='knowledge'&&parts[1]==='session'&&parts.length===2&&method==='GET'){
|
||||
const {issueKnowledgeSession}=await import('@/lib/desktop-client/knowledge-session')
|
||||
value=issueKnowledgeSession(ownerId,auth.expiresAt,auth.isSuperAdmin)
|
||||
|
||||
@ -2431,6 +2431,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let project_busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let catalog_reads = reads::ReadPool::catalog();
|
||||
let image_reads = reads::ReadPool::images();
|
||||
let test_preset_reads = reads::ReadPool::with_limits(1, 1);
|
||||
let project_reads = reads::ReadPool::catalog();
|
||||
let prompt_ops = reads::ReadPool::catalog();
|
||||
let agent_queue_ops = reads::ReadPool::catalog();
|
||||
@ -2844,7 +2845,15 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let task_method = method.clone();
|
||||
let reference = json!({"readId":input["readId"],"doc":input["doc"],"accountId":backend.auth["account"]["id"],"origin":backend.origin,"kind":input["kind"],"id":input["id"],"query":input["query"],"brandId":input["brandId"],"categoryId":input["categoryId"],"maxEdge":input["maxEdge"]});
|
||||
let task_reference = reference.clone();
|
||||
let pool = if matches!(method.as_str(), "preview" | "creation-thumbnail") { &image_reads } else { &catalog_reads };
|
||||
let pool = if method == "creation-catalog"
|
||||
&& matches!(input["kind"].as_str(), Some("test-product-presets" | "test-product-preset-import"))
|
||||
{
|
||||
&test_preset_reads
|
||||
} else if matches!(method.as_str(), "preview" | "creation-thumbnail") {
|
||||
&image_reads
|
||||
} else {
|
||||
&catalog_reads
|
||||
};
|
||||
if let Err(error) = pool.submit(move || {
|
||||
let result = if task_method == "preview" {
|
||||
reader.material_asset(&task_method, &input, &task_events)
|
||||
@ -2854,12 +2863,17 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
reader.action(&task_method, &input, &task_events, &task_ctx)
|
||||
};
|
||||
if task_method != "preview" || result.is_err() {
|
||||
let result = if material_read {
|
||||
Ok(bound_material_read(result, &task_reference))
|
||||
let value = if material_read {
|
||||
bound_material_read(result, &task_reference)
|
||||
} else {
|
||||
Ok(bound_creation_read(result, &task_reference))
|
||||
bound_creation_read(result, &task_reference)
|
||||
};
|
||||
let _ = task_events.send(Event::Json(task_method, result));
|
||||
if let Some(images) = value["presetBrief"]["images"].as_array() {
|
||||
let _ = task_events.send(Event::Json(task_method, Ok(value.clone())));
|
||||
reader.creation_image_previews(&value, images.iter(), &task_events);
|
||||
} else {
|
||||
let _ = task_events.send(Event::Json(task_method, Ok(value)));
|
||||
}
|
||||
}
|
||||
task_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}) {
|
||||
|
||||
@ -7,6 +7,8 @@ mod model;
|
||||
pub(super) use model::{delivery_spu, detail_barcode, production_brief, require_detail_barcode, variant_barcodes};
|
||||
#[path = "jiansun_composer_attachments.rs"]
|
||||
pub(super) mod composer_attachments;
|
||||
#[path = "jiansun_test_presets.rs"]
|
||||
mod test_presets;
|
||||
|
||||
pub(super) fn validated_brief(value: &Value) -> R<Value> {
|
||||
let mut brief = model::brief(value)?;
|
||||
@ -640,6 +642,11 @@ impl Backend {
|
||||
"creation-read" => self.creation_result(doc, &dir),
|
||||
"creation-attachment-import" | "creation-attachment-import-data" => self.composer_import(method, input, doc, &dir),
|
||||
"creation-catalog" => {
|
||||
match input["kind"].as_str() {
|
||||
Some("test-product-presets") => return self.test_product_presets(input),
|
||||
Some("test-product-preset-import") => return self.import_test_product_preset(input, &dir),
|
||||
_ => {}
|
||||
}
|
||||
// The authenticated catalogue GET rechecks the live account and ACL.
|
||||
let kind = input["kind"].as_str().filter(|s| matches!(*s, "brands" | "categories" | "materials" | "products" | "templates" | "resource-set" | "resource-component")).ok_or("资料目录类型无效")?;
|
||||
if matches!(kind,"brands"|"categories"|"templates"|"resource-set"|"resource-component") {
|
||||
@ -1326,11 +1333,15 @@ fn apply_platform_catalog(brief: &mut Value, items: &Value, brand_name: &str, ca
|
||||
|
||||
impl Backend {
|
||||
pub(super) fn platform_previews(&self, receipt: &Value, events: &mpsc::Sender<Event>) {
|
||||
self.creation_image_previews(receipt, receipt["platformBrief"]["images"].as_array().into_iter().flatten()
|
||||
.filter(|image| image["platformImage"] == true), events);
|
||||
}
|
||||
|
||||
pub(super) fn creation_image_previews<'a>(&self, receipt: &Value, images: impl Iterator<Item = &'a Value>, events: &mpsc::Sender<Event>) {
|
||||
let Some(doc) = receipt["doc"].as_u64() else { return };
|
||||
let Ok(dir) = self.project_dir(doc) else { return };
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for source in receipt["platformBrief"]["images"].as_array().into_iter().flatten()
|
||||
.filter(|image| image["platformImage"] == true).filter_map(|image| image["source"].as_str()) {
|
||||
for source in images.filter_map(|image| image["source"].as_str()) {
|
||||
if !seen.insert(source) { continue; }
|
||||
if let Ok(file) = assets_file(&dir, source) && let Ok(bytes) = fs::read(file)
|
||||
&& let Ok(image) = reference_thumbnail(&bytes, REFERENCE_THUMBNAIL_EDGE) {
|
||||
|
||||
@ -0,0 +1,224 @@
|
||||
use super::{Backend, Path, R, STANDARD, Value, draft_store, image_copy, json, validated_brief};
|
||||
use base64::Engine as _;
|
||||
|
||||
const JPEG_DATA_URL: &str = "data:image/jpeg;base64,";
|
||||
|
||||
fn preset_assets(preset: &Value) -> R<&[Value]> {
|
||||
let images = preset["productBrief"]["images"].as_array().ok_or("测试商品图片清单无效")?;
|
||||
let assets = preset["imageAssets"]
|
||||
.as_array()
|
||||
.filter(|assets| !assets.is_empty() && assets.len() == images.len() && assets.len() <= 8)
|
||||
.ok_or("测试商品图片清单无效")?;
|
||||
if images.iter().any(|image| {
|
||||
!assets.iter().any(|asset| {
|
||||
asset["source"] == image["source"] && asset["contentType"] == "image/jpeg" && asset["base64"].as_str().is_some_and(|data| !data.is_empty())
|
||||
})
|
||||
}) {
|
||||
return Err("测试商品图片缺失".into());
|
||||
}
|
||||
Ok(assets)
|
||||
}
|
||||
|
||||
fn parse_presets(response: &Value) -> R<&[Value]> {
|
||||
let presets = response["presets"].as_array().ok_or("测试商品资料格式无效")?;
|
||||
for preset in presets {
|
||||
let brief = &preset["productBrief"];
|
||||
if ["id", "label"].iter().any(|key| preset[*key].as_str().is_none_or(str::is_empty))
|
||||
|| !brief["intake"].is_object()
|
||||
|| brief["barcodeEntries"].as_array().is_none_or(Vec::is_empty)
|
||||
{
|
||||
return Err("测试商品资料不完整".into());
|
||||
}
|
||||
validated_brief(brief)?;
|
||||
preset_assets(preset)?;
|
||||
}
|
||||
Ok(presets)
|
||||
}
|
||||
|
||||
fn import_preset(dir: &Path, preset: &Value) -> R<Value> {
|
||||
draft_store::plain_path(&dir.join("creation-assets"))?;
|
||||
let assets = preset_assets(preset)?;
|
||||
let mut brief = validated_brief(&preset["productBrief"])?;
|
||||
let images = brief["images"].as_array_mut().ok_or("测试商品图片清单无效")?;
|
||||
for image in images {
|
||||
let asset = assets.iter().find(|asset| asset["source"] == image["source"]).ok_or("测试商品图片缺失")?;
|
||||
let data = asset["base64"].as_str().ok_or("测试商品图片编码无效")?;
|
||||
let bytes = STANDARD.decode(data.strip_prefix(JPEG_DATA_URL).unwrap_or(data)).map_err(|_| "测试商品图片编码无效")?;
|
||||
if photocraft_codecs::detect(&bytes) != Some(photocraft_codecs::Format::Jpeg) {
|
||||
return Err("测试商品图片格式无效".into());
|
||||
}
|
||||
let name = image["name"].as_str().ok_or("测试商品图片名称无效")?;
|
||||
let imported = image_copy(dir, &bytes, name)?;
|
||||
image["source"] = imported["source"].clone();
|
||||
}
|
||||
Ok(brief)
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
fn authorize_test_preset(&self, input: &Value) -> R<()> {
|
||||
self.check_dispatch()?;
|
||||
let account = &self.auth["account"];
|
||||
if !account["id"].is_string() || account["isSuperAdmin"] != true || account["id"] != input["accountId"] || input["origin"] != self.origin {
|
||||
return Err("测试商品资料不可用".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn test_product_presets(&self, input: &Value) -> R<Value> {
|
||||
self.authorize_test_preset(input)?;
|
||||
// The preset endpoint checks the live role. A failure is local to this
|
||||
// optional picker, including an expired login or an older server.
|
||||
let response = self.portal_json("test-product-presets").map_err(|failure| failure.message)?;
|
||||
Ok(json!({"catalog":{"items":parse_presets(&response)?}}))
|
||||
}
|
||||
|
||||
pub(super) fn import_test_product_preset(&self, input: &Value, dir: &Path) -> R<Value> {
|
||||
self.authorize_test_preset(input)?;
|
||||
Ok(json!({"presetBrief":import_preset(dir, &input["preset"])?}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::assets_file;
|
||||
use super::*;
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::TcpListener,
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
fn preset(id: &str, photos: &[&str]) -> Value {
|
||||
let schema: Value = serde_json::from_str(include_str!("../../../../../lib/desktop-client/test-preset-intake.json")).unwrap();
|
||||
let photos_json: Value = serde_json::from_str(include_str!("../../../../../lib/desktop-client/test-preset-images.json")).unwrap();
|
||||
let mut entries = Vec::new();
|
||||
let mut variants = Vec::new();
|
||||
let mut bindings = json!({});
|
||||
let mut barcode_values = json!({});
|
||||
let mut images = Vec::new();
|
||||
let mut assets = Vec::new();
|
||||
for (index, photo) in photos.iter().enumerate() {
|
||||
let barcode = format!("02000000200{index}9");
|
||||
let variant = format!("dd6f9c0b-6f6a-4a0e-9fb2-88d50aa7d00{index}");
|
||||
let dimensions = json!({"length":"480","width":"380","height":"420","unit":"mm"});
|
||||
entries.push(json!({"id":barcode,"variantId":variant,"barcode":barcode,"colorName":"燕麦米","material":"亚麻混纺",
|
||||
"boardType":"胶合板","dimensions":dimensions}));
|
||||
variants.push(json!({"id":variant,"name":"窄版","colorName":"燕麦米","colorMaterialId":"","images":[]}));
|
||||
bindings[&variant] = json!([barcode]);
|
||||
barcode_values[&barcode] = json!({"colorName":"燕麦米","material":"亚麻混纺","boardType":"胶合板","length":"480","width":"380","height":"420"});
|
||||
let raw = &photos_json[*photo];
|
||||
let source = format!("local:{}", raw["sha256"].as_str().unwrap());
|
||||
let name = "../../不作为文件路径.jpg";
|
||||
images.push(json!({"source":source,"name":name,"purpose":"product","kind":"whiteBackground","barcode":barcode}));
|
||||
let base64 = raw["base64"].as_str().unwrap();
|
||||
let data = if index == 0 { base64.to_owned() } else { format!("{JPEG_DATA_URL}{base64}") };
|
||||
assets.push(json!({"source":source,"name":name,"contentType":"image/jpeg","base64":data}));
|
||||
}
|
||||
json!({"id":id,"label":"预置储物凳","imageAssets":assets,"productBrief":{
|
||||
"source":"upload","name":"翻盖亚麻储物凳","brandId":"ekb:brand:小壹测试","brandName":"小壹测试",
|
||||
"categoryId":"ekb:category:链路验收","categoryName":"链路验收","identifierType":"spu","identifier":"XYQA-OT-002",
|
||||
"variant":"燕麦米 · 48 cm","colorName":"燕麦米","colorMaterialId":"","dimensions":entries[0]["dimensions"],
|
||||
"note":"翻盖可收纳毯子","detailBarcode":entries[0]["barcode"],"variants":variants,"barcodeBindings":bindings,
|
||||
"barcodeEntries":entries,"images":images,"intake":{"templateId":"QA-FAST-001","schema":schema,
|
||||
"productValues":{"productBrand":"栖序家居(演示)","description":"翻盖可收纳毯子",
|
||||
"sellingPoints":"合上可作换鞋凳","specifications":"480 × 380 × 420 mm"},"barcodeValues":barcode_values}
|
||||
}})
|
||||
}
|
||||
|
||||
fn serve_presets(status: &str, body: String) -> (String, thread::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let status = status.to_owned();
|
||||
let server = thread::spawn(move || {
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
conn.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let mut request = BufReader::new(&mut conn).lines().map(Result::unwrap);
|
||||
assert_eq!(request.next().unwrap(), "GET /api/desktop/test-product-presets HTTP/1.1");
|
||||
assert!(request.take_while(|line| !line.is_empty()).any(|line| line.eq_ignore_ascii_case("authorization: Bearer fixture-token")));
|
||||
write!(conn, "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
|
||||
});
|
||||
(origin, server)
|
||||
}
|
||||
|
||||
fn test_backend(scratch: &Path) -> Backend {
|
||||
let root = scratch.join("profile");
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
super::super::write_json(&root.join("settings.json"), &json!({"origin":origin})).unwrap();
|
||||
Backend::new(root).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_product_presets_fetch_and_import_the_selected_brief_and_real_jpegs() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let mut backend = test_backend(scratch.path());
|
||||
backend.auth = json!({"account":{"id":"qa","isSuperAdmin":true},"access_token":"fixture-token"});
|
||||
let response = json!({"presets":[
|
||||
preset("single", &["oak-stool"]),
|
||||
preset("double", &["linen-sand", "linen-charcoal"])
|
||||
]});
|
||||
let (origin, server) = serve_presets("200 OK", response.to_string());
|
||||
backend.origin = origin.clone();
|
||||
let input = json!({"doc":0,"accountId":"qa","origin":origin,"kind":"test-product-presets"});
|
||||
let (events, _receiver) = std::sync::mpsc::channel();
|
||||
let ctx = egui::Context::default();
|
||||
let catalog = backend.creation_action("creation-catalog", &input, None, &events, &ctx).unwrap();
|
||||
server.join().unwrap();
|
||||
assert_eq!(catalog["catalog"]["items"], response["presets"]);
|
||||
|
||||
backend.bind_new(1);
|
||||
let dir = backend.project_dir(1).unwrap();
|
||||
assert!(!dir.join("creation-assets").exists(), "listing does not import any pictures");
|
||||
let mut apply = input;
|
||||
apply["doc"] = json!(1);
|
||||
apply["kind"] = json!("test-product-preset-import");
|
||||
apply["preset"] = catalog["catalog"]["items"][1].clone();
|
||||
let receipt = backend.creation_action("creation-catalog", &apply, None, &events, &ctx).unwrap();
|
||||
let brief = &receipt["presetBrief"];
|
||||
let expected = &apply["preset"]["productBrief"];
|
||||
for key in ["name", "brandName", "categoryName", "note", "intake", "barcodeBindings", "barcodeEntries"] {
|
||||
assert_eq!(brief[key], expected[key]);
|
||||
}
|
||||
assert_eq!(brief["images"].as_array().unwrap().len(), 2);
|
||||
let assets_dir = dir.join("creation-assets");
|
||||
assert_eq!(fs::read_dir(&assets_dir).unwrap().count(), 2);
|
||||
for (actual, transported) in brief["images"].as_array().unwrap().iter().zip(expected["images"].as_array().unwrap()) {
|
||||
assert_eq!(actual["barcode"], transported["barcode"]);
|
||||
assert_eq!(actual["kind"], "whiteBackground");
|
||||
assert_ne!(actual["source"], transported["source"]);
|
||||
let file = assets_file(&dir, actual["source"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(file.parent(), Some(assets_dir.as_path()));
|
||||
assert_eq!(photocraft_codecs::detect(&fs::read(file).unwrap()), Some(photocraft_codecs::Format::Png));
|
||||
}
|
||||
assert!(!scratch.path().join("不作为文件路径.jpg").exists());
|
||||
|
||||
apply["preset"] = catalog["catalog"]["items"][0].clone();
|
||||
let first = backend.creation_action("creation-catalog", &apply, None, &events, &ctx).unwrap();
|
||||
assert_eq!(first["presetBrief"]["images"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(first, backend.creation_action("creation-catalog", &apply, None, &events, &ctx).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_product_presets_reject_missing_role_and_bad_responses() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let mut backend = test_backend(scratch.path());
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
backend.origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
let input = json!({"accountId":"qa","origin":backend.origin});
|
||||
for account in [json!({"id":"qa","isSuperAdmin":false}), json!({"id":"qa","isDepartmentAdmin":true}), Value::Null] {
|
||||
backend.auth = json!({"account":account,"access_token":"fixture-token"});
|
||||
assert!(backend.test_product_presets(&input).is_err());
|
||||
assert_eq!(listener.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock);
|
||||
}
|
||||
backend.auth["account"] = json!({"id":"qa","isSuperAdmin":true});
|
||||
for (status, body) in [("403 Forbidden", "{}"), ("404 Not Found", "{}"), ("200 OK", "{\"presets\":[{}]}")] {
|
||||
let (origin, server) = serve_presets(status, body.to_owned());
|
||||
backend.origin = origin.clone();
|
||||
assert!(backend.test_product_presets(&json!({"accountId":"qa","origin":origin})).is_err());
|
||||
server.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -11,7 +11,7 @@ const PICKER_ROW_HEIGHT: f32 = 36.0;
|
||||
const MATERIAL_THUMB_SIDE: f32 = 32.0;
|
||||
const REFERENCE_DROP_HINT: &str = "请将图片拖入素材上传框内";
|
||||
|
||||
use super::creation_reads::wizard::{self, WizardFooterOutcome, WizardFooterState};
|
||||
use super::creation_reads::{TEST_PRESETS, wizard::{self, WizardFooterOutcome, WizardFooterState}};
|
||||
pub use wizard::CreationStage;
|
||||
|
||||
const WIZARD_WIDTH: f32 = 800.0;
|
||||
@ -2188,6 +2188,7 @@ impl Workspace {
|
||||
});
|
||||
self.creation_reads.staged_new_project = false;
|
||||
self.creation_reads.staged_prior_draft = None;
|
||||
self.creation_reads.new_project_doc = None;
|
||||
self.creation_reads.wizard_stage = Some((self.creation_field_scope_for(doc, doc), stage));
|
||||
self.set_creation_destination(0);
|
||||
}
|
||||
@ -2383,6 +2384,8 @@ impl Workspace {
|
||||
}
|
||||
self.creation_restore_draft = Value::Null;
|
||||
self.creation_reads.staged_new_project = true;
|
||||
self.creation_reads.new_project_doc = None;
|
||||
self.reset_test_presets();
|
||||
self.creation_reads.wizard_stage = None;
|
||||
self.library = false;
|
||||
self.material = false;
|
||||
@ -2426,6 +2429,7 @@ impl Workspace {
|
||||
app.run("file.new", json!({"name": doc_name, "width": 1440, "height": 1800}))?;
|
||||
let doc_id = app.session.active().map(|state| state.doc.id.0);
|
||||
self.creation_doc = doc_id;
|
||||
self.creation_reads.new_project_doc = doc_id;
|
||||
self.reference_intro_doc = doc_id;
|
||||
self.creation_reads.staged_new_project = false;
|
||||
self.creation_reads.staged_prior_draft = None;
|
||||
@ -2803,6 +2807,9 @@ impl Workspace {
|
||||
let editable = form_editable(self.busy.as_deref(), self.unknown && !self.scoped_production_pending());
|
||||
ui.add_enabled_ui(editable, |ui| {
|
||||
let width = ui.available_width();
|
||||
if stage != CreationStage::Template {
|
||||
self.test_preset_ui(app, ui);
|
||||
}
|
||||
match stage {
|
||||
CreationStage::Source => self.wizard_source_ui(app, ui, scope, width),
|
||||
CreationStage::Template => {
|
||||
@ -2827,6 +2834,7 @@ impl Workspace {
|
||||
let next = match (stage, action) {
|
||||
(_, WizardFooterOutcome::Cancel) => {
|
||||
self.retain_creation_ui_draft(app);
|
||||
self.creation_reads.new_project_doc = None;
|
||||
if self.creation_reads.staged_new_project {
|
||||
self.creation_reads.staged_new_project = false;
|
||||
self.creation_restore_draft = self.creation_reads.staged_prior_draft.take().unwrap_or(Value::Null);
|
||||
@ -2848,6 +2856,100 @@ impl Workspace {
|
||||
self.creation_reads.wizard_stage = Some((scope, next));
|
||||
}
|
||||
|
||||
fn test_preset_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
if !self.can_use_test_presets(app) {
|
||||
return;
|
||||
}
|
||||
if !self.creation_catalog.contains_key(TEST_PRESETS)
|
||||
&& self.creation_catalog_error(TEST_PRESETS).is_none()
|
||||
&& !self.creation_catalog_loading(TEST_PRESETS)
|
||||
{
|
||||
self.request_creation_catalog(app, TEST_PRESETS, String::new(), false);
|
||||
}
|
||||
let Some(presets) = self.creation_catalog.get(TEST_PRESETS).filter(|rows| !rows.is_empty()) else {
|
||||
return;
|
||||
};
|
||||
let importing = self.test_preset_import_pending();
|
||||
let label = if importing { "正在填入测试商品…" } else { "一键填入测试商品(超管)" };
|
||||
let button = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !importing)
|
||||
.on_hover_text("选择后替换当前商品资料和参考图");
|
||||
let mut chosen = None;
|
||||
egui::Popup::menu(&button).style(stitch_ui::scoped_popup_style(ui))
|
||||
.frame(stitch_ui::command_menu_frame(ui.ctx())).show(|ui| {
|
||||
for preset in presets {
|
||||
if stitch_ui::action_button(ui, preset["label"].as_str().unwrap_or(""), stitch_ui::ButtonRole::Quiet, true).clicked() {
|
||||
chosen = Some(preset.clone());
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(preset) = chosen {
|
||||
self.select_test_preset(app, ui.ctx(), preset);
|
||||
}
|
||||
ui.add_space(space::SM);
|
||||
}
|
||||
|
||||
fn select_test_preset(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, preset: Value) {
|
||||
if !self.can_use_test_presets(app) || self.test_preset_import_pending() {
|
||||
return;
|
||||
}
|
||||
let staged = self.creation_reads.staged_new_project;
|
||||
if self.ensure_creation_document(app).is_err() {
|
||||
return;
|
||||
}
|
||||
if staged {
|
||||
// Detach the old project before queuing the import. The new native
|
||||
// document has no saved draft to restore on the next frame.
|
||||
let doc = self.creation_doc;
|
||||
let brief = std::mem::take(&mut self.creation_brief);
|
||||
let dirty = self.creation_dirty;
|
||||
self.switch_project_projection(app, ctx, None);
|
||||
self.observed_doc = doc;
|
||||
self.loaded_draft = doc;
|
||||
self.creation_doc = doc;
|
||||
self.creation_ui_scope = self.current_creation_ui_scope(app);
|
||||
self.project_view_parked = false;
|
||||
self.creation_brief = brief;
|
||||
self.creation = json!({"brief":empty_brief()});
|
||||
self.creation_dirty = dirty;
|
||||
}
|
||||
// Carry the same picker across the staged draft's first image import.
|
||||
let presets = self.creation_catalog.remove(TEST_PRESETS);
|
||||
self.creation_read_scope(app);
|
||||
if let Some(presets) = presets {
|
||||
self.creation_catalog.insert(TEST_PRESETS.into(), presets);
|
||||
}
|
||||
self.request_test_preset_import(app, preset);
|
||||
}
|
||||
|
||||
pub(super) fn apply_test_preset(&mut self, app: &PhotocraftApp, mut brief: Value) {
|
||||
let selected = &self.creation_brief["templateSelection"];
|
||||
let taxonomy_changed = self.creation_brief["brandId"] != brief["brandId"]
|
||||
|| self.creation_brief["categoryId"] != brief["categoryId"];
|
||||
let keep_template = template_identity(selected)
|
||||
&& selected["id"] == brief["intake"]["templateId"]
|
||||
&& !taxonomy_changed;
|
||||
if keep_template {
|
||||
brief["templateSelection"] = selected.clone();
|
||||
} else if self.creation_reads.wizard_stage.is_some_and(|(_, stage)| stage == CreationStage::Details) {
|
||||
self.creation_reads.wizard_stage = Some((self.creation_field_scope(app), CreationStage::Template));
|
||||
}
|
||||
if taxonomy_changed {
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
self.creation_catalog.remove("categories");
|
||||
self.creation_catalog.remove("templates");
|
||||
}
|
||||
self.creation_brief = brief;
|
||||
self.creation_reads.manual_edited_fields.clear();
|
||||
self.creation_reads.inline_errors.clear();
|
||||
self.creation_reads.reference_import_error.clear();
|
||||
self.creation_reads.scroll_to_field = None;
|
||||
self.creation_dirty = true;
|
||||
self.sync_dirty = true;
|
||||
self.draft_changed = true;
|
||||
}
|
||||
|
||||
fn reference_drop_warning_ui(&mut self, ui: &mut Ui) {
|
||||
if self.creation_reads.reference_import_error == REFERENCE_DROP_HINT {
|
||||
let status = stitch_ui::status_label(ui, REFERENCE_DROP_HINT, stitch_ui::StatusTone::Warning);
|
||||
@ -4680,6 +4782,8 @@ impl Workspace {
|
||||
"refinement": refinement,
|
||||
})) {
|
||||
self.error = error;
|
||||
} else {
|
||||
self.creation_reads.new_project_doc = None;
|
||||
}
|
||||
}
|
||||
|
||||
@ -6071,6 +6175,149 @@ mod tests {
|
||||
use photocraft_doc::LayerContent;
|
||||
use std::sync::{Arc, mpsc};
|
||||
|
||||
const TEST_PRESET_PICKER_LABEL: &str = "一键填入测试商品(超管)";
|
||||
|
||||
fn test_preset_wizard(
|
||||
account: Value,
|
||||
width: f32,
|
||||
) -> (egui_kittest::Harness<'static, (Workspace, PhotocraftApp)>, mpsc::Receiver<Request>) {
|
||||
let (mut w, app, requests) = brief_fixture();
|
||||
w.account = account;
|
||||
w.reduce_motion = true;
|
||||
w.observed_doc = w.creation_doc;
|
||||
w.project_context = json!({"localId":"previous-project"});
|
||||
w.begin_staged_new_project(&app);
|
||||
let harness = egui_kittest::Harness::builder()
|
||||
.with_size(vec2(width, 850.0))
|
||||
.with_context_setup(|ctx| {
|
||||
PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium);
|
||||
crate::cjk_fonts::install_system_provider_for_tests(ctx);
|
||||
})
|
||||
.build_ui_state(|ui, (w, app): &mut (Workspace, PhotocraftApp)| {
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| w.creation_ui(app, ui));
|
||||
}, (w, app));
|
||||
(harness, requests)
|
||||
}
|
||||
|
||||
fn request_for_test_product_preset(requests: &mpsc::Receiver<Request>, kind: &str) -> Option<Value> {
|
||||
requests.try_iter().find_map(|request| match request {
|
||||
Request::Action(method, input) if method == "creation-catalog" && input["kind"] == kind => Some(input),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_product_presets_hide_the_picker_and_skip_the_request_without_super_admin() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
for account in [
|
||||
json!({"id":"qa","isSuperAdmin":false}),
|
||||
json!({"id":"qa","isDepartmentAdmin":true}),
|
||||
json!({"id":"qa","isSuperAdmin":"true"}),
|
||||
Value::Null,
|
||||
] {
|
||||
let (mut harness, requests) = test_preset_wizard(account, 460.0);
|
||||
harness.run_steps(3);
|
||||
assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none());
|
||||
assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none());
|
||||
assert!(harness.query_by_label("选择文件夹").is_some(), "the normal form remains available");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_product_presets_fill_and_replace_the_editable_draft_from_picker_selection() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let (mut harness, requests) = test_preset_wizard(json!({"id":"qa","isSuperAdmin":true}), 460.0);
|
||||
harness.run_steps(3);
|
||||
let initial_catalogs = requests.try_iter().filter_map(|request| match request {
|
||||
Request::Action(method, input) if method == "creation-catalog" => Some(input),
|
||||
_ => None,
|
||||
}).collect::<Vec<_>>();
|
||||
let mut brands = initial_catalogs.iter().find(|input| input["kind"] == "brands").unwrap().clone();
|
||||
let mut response = initial_catalogs.into_iter().find(|input| input["kind"] == TEST_PRESETS).unwrap();
|
||||
assert_eq!(response["doc"], 0);
|
||||
assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none());
|
||||
assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none(), "wait for the authorized response");
|
||||
{
|
||||
let (w, app) = harness.state_mut();
|
||||
brands["catalog"]["items"] = json!([]);
|
||||
assert!(w.creation_read_received(app, "creation-catalog", &brands));
|
||||
assert!(request_for_test_product_preset(&requests, "materials").is_some());
|
||||
}
|
||||
response["catalog"]["items"] = json!([
|
||||
{"id":"oak","label":"橡木换鞋凳"},{"id":"linen","label":"亚麻储物凳"}
|
||||
]);
|
||||
{
|
||||
let (w, app) = harness.state_mut();
|
||||
assert!(w.creation_read_received(app, "creation-catalog", &response));
|
||||
}
|
||||
harness.run_steps(3);
|
||||
|
||||
for (index, (id, name, barcode)) in [("oak", "橡木换鞋凳", "0200000010010"), ("linen", "亚麻储物凳", "0200000020019")].into_iter().enumerate() {
|
||||
let picker = harness.get_by_label(TEST_PRESET_PICKER_LABEL);
|
||||
assert!(picker.rect().width() > 0.0 && picker.rect().right() < 460.0);
|
||||
picker.click();
|
||||
harness.run_steps(3);
|
||||
harness.get_by_label(name).click();
|
||||
harness.run_steps(3);
|
||||
let mut receipt = request_for_test_product_preset(&requests, "test-product-preset-import").unwrap();
|
||||
assert_eq!(receipt["id"], id);
|
||||
assert_ne!(receipt["doc"], 0);
|
||||
let mut brief = empty_brief();
|
||||
brief["name"] = json!(name);
|
||||
brief["identifier"] = json!("XYQA-ST-001");
|
||||
brief["brandId"] = json!("ekb:brand:小壹测试");
|
||||
brief["brandName"] = json!("小壹测试");
|
||||
brief["categoryId"] = json!("ekb:category:链路验收");
|
||||
brief["categoryName"] = json!("链路验收");
|
||||
brief["note"] = json!("适用于玄关");
|
||||
brief["intake"] = json!({"productValues":{"productBrand":"测试品牌","sellingPoints":"圆角座面","description":"可收纳",
|
||||
"specifications":"480 × 380 × 420 mm"},"barcodeValues":{barcode:{"length":"480"}}});
|
||||
brief["barcodeEntries"] = json!([{"id":barcode,"barcode":barcode}]);
|
||||
brief["detailBarcode"] = json!(barcode);
|
||||
brief["images"] = json!([{"source":format!("local:{}", if index == 0 { "a" } else { "b" }.repeat(64)),
|
||||
"name":format!("{name}.jpg"),"purpose":"product","barcode":barcode}]);
|
||||
receipt["presetBrief"] = brief.clone();
|
||||
let (w, app) = harness.state_mut();
|
||||
if index == 0 {
|
||||
assert!(w.project_context["localId"].is_null());
|
||||
} else {
|
||||
w.project_context["localId"] = json!("new-draft");
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
assert!(w.tick_context(app, &ctx));
|
||||
assert_eq!(w.observed_doc, receipt["doc"].as_u64());
|
||||
assert!(w.creation_read_received(app, "creation-catalog", &receipt));
|
||||
assert_eq!(w.creation_brief, brief);
|
||||
assert!(w.creation_dirty && w.sync_dirty);
|
||||
assert_eq!(app.session.documents().len(), 2, "reselecting keeps the same draft document");
|
||||
let template = json!({"id":"QA-FAST-001","version":"1.0","contentHash":"a".repeat(64)});
|
||||
assert!(canvas_entry_missing(&w.creation_brief, &template).is_empty());
|
||||
w.creation_brief["note"] = json!("手改后仍然可编辑");
|
||||
assert_eq!(w.creation_brief["note"], "手改后仍然可编辑");
|
||||
harness.run_steps(3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_product_presets_hide_failed_responses_without_changing_the_normal_form() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
for error in [json!({"error":"HTTP 403"}), json!({"error":"HTTP 404"}), json!({"catalog":{"items":null}})] {
|
||||
let (mut harness, requests) = test_preset_wizard(json!({"id":"qa","isSuperAdmin":true}), 900.0);
|
||||
harness.run_steps(3);
|
||||
let mut response = request_for_test_product_preset(&requests, TEST_PRESETS).unwrap();
|
||||
let (w, app) = harness.state_mut();
|
||||
let before = w.creation_brief.clone();
|
||||
response.as_object_mut().unwrap().extend(error.as_object().unwrap().clone());
|
||||
assert!(w.creation_read_received(app, "creation-catalog", &response));
|
||||
assert_eq!(w.creation_brief, before);
|
||||
assert!(w.error.is_empty());
|
||||
harness.run_steps(3);
|
||||
assert!(harness.query_by_label(TEST_PRESET_PICKER_LABEL).is_none());
|
||||
assert!(harness.query_by_label("选择文件夹").is_some());
|
||||
assert!(request_for_test_product_preset(&requests, TEST_PRESETS).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unhinted_creation_field_has_a_meaningful_accessible_name() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
|
||||
@ -7,6 +7,8 @@ use std::collections::{HashMap, HashSet, VecDeque};
|
||||
const READ_WAIT: Duration = Duration::from_secs(45);
|
||||
const CACHE_LIMIT: usize = 48;
|
||||
const QUEUE_LIMIT: usize = 128;
|
||||
pub(super) const TEST_PRESETS: &str = "test-product-presets";
|
||||
const TEST_PRESET_IMPORT: &str = "test-product-preset-import";
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Scope {
|
||||
@ -51,6 +53,7 @@ pub(super) struct UiState {
|
||||
pub(super) resource_image: Option<(String, egui::TextureHandle)>,
|
||||
pub(super) staged_new_project: bool,
|
||||
pub(super) staged_prior_draft: Option<Value>,
|
||||
pub(super) new_project_doc: Option<u64>,
|
||||
pub(super) wizard_stage: Option<(egui::Id, wizard::CreationStage)>,
|
||||
pub(super) inline_errors: HashMap<String, String>,
|
||||
pub(super) scroll_to_field: Option<String>,
|
||||
@ -72,6 +75,9 @@ fn thumbnail(request: &Queued) -> bool {
|
||||
fn kind(request: &Queued) -> &str {
|
||||
request.input["kind"].as_str().unwrap_or("")
|
||||
}
|
||||
fn test_preset(request: &Queued) -> bool {
|
||||
matches!(kind(request), TEST_PRESETS | TEST_PRESET_IMPORT)
|
||||
}
|
||||
fn id(request: &Queued) -> &str {
|
||||
request.input["id"].as_str().unwrap_or("")
|
||||
}
|
||||
@ -110,11 +116,15 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
pub(super) fn creation_read_scope(&mut self, app: &PhotocraftApp) {
|
||||
let doc = self.creation_read_doc(app);
|
||||
let new_project = self.creation_reads.staged_new_project
|
||||
|| self.account["isSuperAdmin"] == true
|
||||
&& doc.is_some_and(|doc| self.creation_reads.new_project_doc == Some(doc));
|
||||
let scope = Scope {
|
||||
account: self.account["id"].as_str().unwrap_or("").into(),
|
||||
origin: self.origin.clone(),
|
||||
doc: self.creation_read_doc(app),
|
||||
project: if self.creation_reads.staged_new_project {
|
||||
doc,
|
||||
project: if new_project {
|
||||
"staged-new".into()
|
||||
} else {
|
||||
self.project_context["localId"].as_str().unwrap_or("").into()
|
||||
@ -167,9 +177,38 @@ impl Workspace {
|
||||
fn creation_read_input(&self, app: &PhotocraftApp, kind: &str, id: Value, query: &str) -> Value {
|
||||
json!({"doc":self.creation_read_doc(app),"accountId":self.account["id"],"origin":self.origin,"kind":kind,"id":id,"query":query})
|
||||
}
|
||||
|
||||
pub(super) fn can_use_test_presets(&self, app: &PhotocraftApp) -> bool {
|
||||
self.account["id"].is_string() && self.account["isSuperAdmin"] == true
|
||||
&& self.authority_active() && !self.library_blocked() && self.editing_product_brief()
|
||||
&& (self.creation_reads.staged_new_project || self.creation_reads.new_project_doc
|
||||
.is_some_and(|doc| self.creation_doc == Some(doc) && self.creation_read_doc(app) == Some(doc)))
|
||||
}
|
||||
|
||||
pub(super) fn test_preset_import_pending(&self) -> bool {
|
||||
self.creation_catalog_loading(TEST_PRESET_IMPORT)
|
||||
}
|
||||
|
||||
pub(super) fn reset_test_presets(&mut self) {
|
||||
self.creation_catalog.remove(TEST_PRESETS);
|
||||
self.creation_reads.catalog_errors.remove(TEST_PRESETS);
|
||||
self.creation_reads.queue.retain(|request| !test_preset(request));
|
||||
self.creation_reads.pending.retain(|_, pending| !test_preset(&pending.request));
|
||||
}
|
||||
|
||||
pub(super) fn request_test_preset_import(&mut self, app: &PhotocraftApp, preset: Value) {
|
||||
let mut input = self.creation_read_input(app, TEST_PRESET_IMPORT, preset["id"].clone(), "");
|
||||
input["preset"] = preset;
|
||||
input["brief"] = self.creation_brief.clone();
|
||||
self.queue_creation_catalog(TEST_PRESET_IMPORT, input);
|
||||
}
|
||||
|
||||
pub(super) fn request_creation_catalog(&mut self, app: &PhotocraftApp, kind: &str, query: String, refresh: bool) {
|
||||
self.creation_read_scope(app);
|
||||
if !["brands", "categories", "materials", "products", "templates", "resource-set", "resource-component"].contains(&kind) || query.chars().count() > if kind == "resource-component" { 512 } else { 120 } {
|
||||
if kind == TEST_PRESETS && !self.can_use_test_presets(app) {
|
||||
return;
|
||||
}
|
||||
if !["brands", "categories", "materials", "products", "templates", "resource-set", "resource-component", TEST_PRESETS].contains(&kind) || query.chars().count() > if kind == "resource-component" { 512 } else { 120 } {
|
||||
self.creation_reads.catalog_errors.insert(kind.into(), "目录查询参数无效".into());
|
||||
return;
|
||||
}
|
||||
@ -201,6 +240,9 @@ impl Workspace {
|
||||
input["identifierType"] = self.creation_brief["identifierType"].clone();
|
||||
input["identifier"] = self.creation_brief["identifier"].clone();
|
||||
}
|
||||
self.queue_creation_catalog(kind, input);
|
||||
}
|
||||
fn queue_creation_catalog(&mut self, kind: &str, input: Value) {
|
||||
let signature = input.to_string();
|
||||
self.creation_reads.desired.insert(kind.into(), signature.clone());
|
||||
self.creation_reads.catalog_errors.remove(kind);
|
||||
@ -354,6 +396,10 @@ impl Workspace {
|
||||
if !thumbnail(&request) && self.creation_reads.desired.get(kind(&request)) != Some(&request.signature) {
|
||||
return;
|
||||
}
|
||||
if kind(&request) == TEST_PRESET_IMPORT {
|
||||
self.creation_catalog.remove(TEST_PRESETS);
|
||||
self.creation_reads.catalog_errors.insert(TEST_PRESETS.into(), error.into());
|
||||
}
|
||||
if queue_busy && request.attempts < 3 {
|
||||
request.ready = Instant::now() + Duration::from_millis(250 * u64::from(request.attempts.max(1)));
|
||||
self.creation_reads.queue.push_back(request);
|
||||
@ -369,8 +415,17 @@ impl Workspace {
|
||||
}
|
||||
loop {
|
||||
let images = self.creation_reads.pending.values().filter(|p| thumbnail(&p.request)).count();
|
||||
let catalogs = self.creation_reads.pending.len() - images;
|
||||
let Some(index) = self.creation_reads.queue.iter().position(|r| r.ready <= Instant::now() && if thumbnail(r) { images < 2 } else { catalogs < 1 })
|
||||
let presets = self.creation_reads.pending.values().filter(|p| test_preset(&p.request)).count();
|
||||
let catalogs = self.creation_reads.pending.len() - images - presets;
|
||||
let Some(index) = self.creation_reads.queue.iter().position(|request| {
|
||||
request.ready <= Instant::now() && if thumbnail(request) {
|
||||
images < 2
|
||||
} else if test_preset(request) {
|
||||
presets == 0
|
||||
} else {
|
||||
catalogs == 0
|
||||
}
|
||||
})
|
||||
else {
|
||||
break;
|
||||
};
|
||||
@ -442,11 +497,25 @@ impl Workspace {
|
||||
let Some(pending) = self.creation_reads.pending.remove(&serial) else {
|
||||
return false;
|
||||
};
|
||||
let kind = kind(&pending.request);
|
||||
if test_preset(&pending.request) && !self.can_use_test_presets(app) {
|
||||
self.pump_creation_reads();
|
||||
return true;
|
||||
}
|
||||
if let Some(error) = value["error"].as_str() {
|
||||
self.creation_read_failed(pending.request, error, value["readError"] == "queue_busy");
|
||||
} else if self.creation_reads.desired.get(kind(&pending.request)) == Some(&pending.request.signature) {
|
||||
} else if self.creation_reads.desired.get(kind) == Some(&pending.request.signature) {
|
||||
if kind == TEST_PRESET_IMPORT {
|
||||
if !value["presetBrief"].is_object() {
|
||||
self.creation_read_failed(pending.request, "测试商品资料格式无效", false);
|
||||
} else if self.creation_brief == pending.request.input["brief"] {
|
||||
self.apply_test_preset(app, value["presetBrief"].clone());
|
||||
}
|
||||
self.pump_creation_reads();
|
||||
return true;
|
||||
}
|
||||
if let Some(items) = value["catalog"]["items"].as_array() {
|
||||
if kind(&pending.request) == "templates" {
|
||||
if kind == "templates" {
|
||||
let selected = &self.creation_brief["templateSelection"];
|
||||
if let Some(row) = items.iter().find(|row| row["id"] == selected["id"]
|
||||
&& row["version"] == selected["version"] && row["contentHash"] == selected["contentHash"])
|
||||
@ -454,8 +523,8 @@ impl Workspace {
|
||||
self.creation_dirty |= wizard::refresh_intake_schema_from_catalog(&mut self.creation_brief, row);
|
||||
}
|
||||
}
|
||||
self.creation_catalog.insert(kind(&pending.request).into(), items.clone());
|
||||
self.creation_reads.catalog_errors.remove(kind(&pending.request));
|
||||
self.creation_catalog.insert(kind.into(), items.clone());
|
||||
self.creation_reads.catalog_errors.remove(kind);
|
||||
} else {
|
||||
self.creation_read_failed(pending.request, "目录返回格式无效,原结果保留", false);
|
||||
}
|
||||
|
||||
@ -45,14 +45,14 @@ export async function exchangeDesktop(input: Record<string, any>) {
|
||||
desktopAssert(grant && grant.redirectUri === input.redirect_uri, '授权已失效,请重新登录', 400, 'invalid_grant')
|
||||
const challenge = createHash('sha256').update(input.code_verifier).digest('base64url')
|
||||
desktopAssert(challenge.length === grant.challenge.length && timingSafeEqual(Buffer.from(challenge), Buffer.from(grant.challenge)), '授权校验未通过,请重新登录', 400, 'invalid_grant')
|
||||
const account = await desktopUser(grant.ownerId)
|
||||
const { account, isSuperAdmin } = await desktopIdentity(grant.ownerId)
|
||||
const token = 'dcs_' + randomBytes(48).toString('base64url'), id = randomUUID(), expiresAt = new Date(Date.now() + SESSION_TTL_MS)
|
||||
await db.$transaction(async tx => {
|
||||
const consumed = await tx.$executeRawUnsafe('UPDATE desktop_client_grants SET used_at=NOW() WHERE id=$1 AND used_at IS NULL AND expires_at>NOW()', grant.id)
|
||||
desktopAssert(consumed === 1, '授权码已使用,请重新登录', 400, 'invalid_grant')
|
||||
await tx.$executeRawUnsafe('INSERT INTO desktop_client_sessions(id,token_hash,owner_id,device_name,expires_at) VALUES($1,$2,$3,$4,$5)', id, hash(token), account.id, '详情页工作台', expiresAt)
|
||||
})
|
||||
return { access_token: token, token_type: 'Bearer', expires_at: expiresAt.toISOString(), account, scope: DESKTOP_SCOPES.join(' ') }
|
||||
return { access_token: token, token_type: 'Bearer', expires_at: expiresAt.toISOString(), account: { ...account, isSuperAdmin }, scope: DESKTOP_SCOPES.join(' ') }
|
||||
}
|
||||
export async function requireDesktop(request: Request) {
|
||||
const token = request.headers.get('authorization')?.match(/^Bearer (dcs_[\w-]{64})$/)?.[1]
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user