subscription.rs 170 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027
  1. //! 订阅维护与升降配承接(第 3 册 §5)。
  2. //!
  3. //! ## 本轮口径(设计列已在册 ⇒ 只读派生列一律⛔ 接受入参)
  4. //!
  5. //! * **六项只读派生**(`annual_price_cents`/`monthly_settle_cents`/`end_date`/`line_exits`/
  6. //! `sub_mode`/`order_no`+`actual_opened_at`)+变更链指针 `replaces_subscription_id` 只属于
  7. //! `/change`:载荷出现即 `11103` 点名(§5.2「手工填价与手工改到期日=数据污染的入口」)。
  8. //! 唯一可录的周期入参=`term`(`yearly`/`quarterly`/`monthly`,缺省按年)。
  9. //! * **快照六列**(`plan_name`/`plan_kind`/`plan_owner_customer_id`/`line_exits`+`line_exit_key`/
  10. //! `term`/`sub_mode`)由档位与条目折算后落库=当时值(§2.3「改档⛔ 追溯改历史订阅」),
  11. //! 读侧⛔ 现取 `catalog_plan`(`to_json` 的 `plan_name` 走快照列)。
  12. //! * 金额与状态一律走 [`bos_invariant`]:`monthly_settle_of`=月结算唯一折算点、
  13. //! `subscription_status_of`=状态唯一判据、`in_use_quota_sum_batch`=额度求和唯一实现、
  14. //! I6 已于 2026-11-19 停用(D-15:`sub_mode` 不再派生),码位 `KLT-M224` 保留不复用。
  15. //!
  16. //! ## 写侧事务落点(§5.2 六步)
  17. //!
  18. //! UDS 只暴露 `/dml/batch@v1`(整批原子提交、⛔ 批内条件中止、⛔ 行锁、⛔ 回读行集),故六步
  19. //! 落成**一次 `dml_batch`**:截原 → 新行 INSERT → `catalog_plan.first_referred_at` 打点 →
  20. //! 客户额度对齐;每步的前置条件写进 `WHERE` 谓词,影响行数**事后自检**,异常即
  21. //! `BosError::internal` 点名已提交的形态(⛔ 静默)。`SELECT … FOR UPDATE` 无能力 ⇒ 「锁条目行」
  22. //! 落成带谓词的守卫更新,差异登 18 册。
  23. //!
  24. //! ⚠️ 工单事实、账单明细、套餐月成本三枚跨册只读口本轮⛔ 未接线 ⇒ 一律 `CrossRead::Unconfigured`
  25. //! +响应点名(⛔ 塌成「无阻塞」「未配置=零成本」)。
  26. //!
  27. //! ⛔ 日终到期翻转任务(`SUB-EFF`)本轮不做:状态在读侧按三要素推导(`status_display`)。
  28. use axum::extract::State;
  29. use axum::response::Response;
  30. use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
  31. use bos_api::AppState;
  32. use bos_core::page::PageQuery;
  33. use bos_core::{BosError, KltCode, RoleCode};
  34. use bos_invariant::{
  35. check_i12b_same_customer, check_i13_trial_months, check_plan_available,
  36. check_subscription_deletable, contracts_opened, in_use_quota_sum_batch, monthly_settle_of,
  37. normalize_line_exits, subscription_status_of, CrossRead,
  38. NormalizedExits, Opened, OpenedProbe, PlanFamily, PlanRef, SubscriptionBlocks,
  39. };
  40. use bos_platform::clients::uds::{de, DmlStatement};
  41. use chrono::{Datelike, NaiveDate};
  42. use serde::Deserialize;
  43. use serde_json::{json, Map, Value};
  44. use std::collections::{HashMap, HashSet};
  45. use super::listq::{
  46. as_num, as_opt_num, count_by, next_seq, pairs_by, push_in, total, Params,
  47. };
  48. use super::partner::customer_scope_pred;
  49. /// 补列后已无缺列(⛔ 删键=前端类型会缺字段)。
  50. const COLUMNS_PENDING: &[&str] = &[];
  51. /// 订阅时长值域(§2.3 `term`;⛔ 落库成月数,月数只是折算中间量)。
  52. const TERMS: [&str; 3] = ["yearly", "quarterly", "monthly"];
  53. /// 在用状态(§4 额度口径:仅待生效与生效中占额度)。
  54. pub(crate) const IN_USE_STATUS: [&str; 2] = ["pending", "active"];
  55. /// 六项只读派生列+变更链指针:新建载荷出现即 `11103`(§5.2 段 3/4、§2.3)。
  56. const CREATE_READ_ONLY: [&str; 10] = [
  57. "annual_price_cents",
  58. "monthly_settle_cents",
  59. "end_date",
  60. "line_exits",
  61. "sub_mode",
  62. "order_no",
  63. "actual_opened_at",
  64. "early_stopped_at",
  65. "replaces_subscription_id",
  66. // D-15:`item_family` 随所引合同条目带入并冻结(合同侧载荷已拒传),订阅侧⛔ 再收一份。
  67. "item_family",
  68. ];
  69. /// 升降配额外只读项:⛔ 换客户(`customer_id` 只做一致性校验),用途分类跟着新档位走
  70. /// (需求明文「不换分类另建」)。⚠️ 2026-11-16 修正:`contract_id`/`contract_item_id` 由
  71. /// 契约(`openapi.yaml` `/subscription/change@v1`)列为必填「新合同/新条目」,此前误入拒收表
  72. /// ⇒ 前端按契约提交必吃 `KLT-S20004`,升降配在界面与接口两侧都不可用(P5-D1)。
  73. const CHANGE_READ_ONLY: [&str; 9] = [
  74. "plan_family",
  75. "annual_price_cents",
  76. "monthly_settle_cents",
  77. "end_date",
  78. "line_exits",
  79. "sub_mode",
  80. "order_no",
  81. "actual_opened_at",
  82. "early_stopped_at",
  83. ];
  84. /// 修改白名单:只有这两列可改(§5.7)。
  85. const UPDATE_WHITELIST: [&str; 2] = ["trial_months", "discount_monthly_cents"];
  86. /// 修改里点名 `KLT-M229` 的越权列(换套餐/换合同=改订语义)。
  87. const UPDATE_M229_KEYS: [&str; 3] = ["plan_id", "contract_id", "contract_item_id"];
  88. /// 账单明细只读口未接线的原文说明(§5.5「未配置=不可判定,⛔ 当成无阻塞」)。
  89. const BILLING_UNCONFIGURED_NOTE: &str = "账单明细只读口本轮未接线(`billing_state=unconfigured`):\
  90. 「账单阻塞=无」是取数未配置的回落值,不构成无阻塞结论,删除须由人工复核账单。";
  91. /// 套餐月成本只读口未接线的原文说明(§5.4 段 2)。
  92. const COST_UNCONFIGURED_NOTE: &str = "套餐月成本只读口本轮未接线(`plan_cost_state=unconfigured`):\
  93. `plan_cost_item` 在册但成本折算属第 4 册口径,不以 0 冒充无成本。";
  94. /// 开户工单只读口未接线的原文说明(§2.1/§5.2 第 6 步)。
  95. pub(crate) const TICKET_UNCONFIGURED_NOTE: &str = "开户工单只读口本轮未接线(`open_tickets=unconfigured`):\
  96. 开通态判定只用了本域自读的 `actual_opened_at` 一维,不据此认定合同未开通;\
  97. 新订第 6 步「回写开户工单号与订单号」同样未接线,本轮未回写。";
  98. /// 统一取列(写侧回读、列表、详情、I6 取数共用一份列集=⛔ 三处漂移)。
  99. const SELECT_COLS: &str = "SELECT s.subscription_id, s.customer_id, s.contract_id, s.contract_item_id, \
  100. s.plan_id, s.plan_name, s.plan_kind, s.plan_owner_customer_id, s.status, s.plan_family, s.sub_mode, \
  101. s.line_exits, s.line_exit_key, s.start_date, s.end_date, s.term, s.trial_months, \
  102. s.discount_monthly_cents, s.annual_price_cents, s.monthly_settle_cents, s.quota_slots, \
  103. s.quantity, s.parent_subscription_id, s.replaces_subscription_id, s.order_no, s.actual_opened_at, \
  104. s.early_stopped_at, s.effective_date, s.expire_date, s.created_at, s.row_version";
  105. /// 档位取列(`p`=`catalog_plan`)。`plan_family` 是条目/订阅形态的**唯一来源**;
  106. /// 派生档整链已删(D-15)⇒ 不再有 `derived_from_contract_item_id`。
  107. const PLAN_COLS: &str = "SELECT p.plan_id, p.plan_name, p.plan_kind, p.customer_id, p.status, \
  108. p.plan_family, p.sub_account_quota, p.annual_price_cents, \
  109. p.monthly_settle_cents, p.line_exits, p.first_referred_at";
  110. // ───────────────────────── 入参 ─────────────────────────
  111. /// 新建载荷:`rest` 捕获未建模的键,用于把只读派生列点名拒收(⛔ 静默忽略)。
  112. #[derive(Deserialize)]
  113. pub struct SubscriptionCreateReq {
  114. pub customer_id: String,
  115. pub plan_id: String,
  116. /// 可空**只是为了给出业务文案**(TC-CU-51 步骤 2):缺键时 `serde` 原本直接回
  117. /// `missing field contract_id`,页面无法把它渲染成「请选择合同编号」这一句。
  118. /// 语义仍是必填(见 [`create`] 的首段校验)。
  119. pub contract_id: Option<String>,
  120. /// 与 `contract_id` 同现同空(§2.3);合同内一条匹配条目都没有时可空(§5.2 末段)。
  121. pub contract_item_id: Option<String>,
  122. /// 缺省=当天(§5.2「开始日(默当天)」)。
  123. pub start_date: Option<String>,
  124. /// 唯一可录的周期入参;缺省按年(§5.2)。
  125. pub term: Option<String>,
  126. /// 交付形态(只读确认位):只能与所选档位的 `plan_family` 相同,不同即 `11103`。
  127. pub plan_family: Option<String>,
  128. pub trial_months: Option<i64>,
  129. pub discount_monthly_cents: Option<i64>,
  130. /// 档位份数(2026-11-17):缺省 1;仅可叠加档(叠加增值)允许 > 1,其余档给 > 1 即拒。
  131. /// 一份合同条目仍只生一份订阅——数量是订阅自身的份数,不是条目数。
  132. pub quantity: Option<i64>,
  133. #[serde(flatten)]
  134. pub rest: Map<String, Value>,
  135. }
  136. /// 升降配载荷:⛔ 换客户(`customer_id` 仅用于一致性校验);合同与条目按契约可另选新合同
  137. /// (`contract_id` 缺省时沿用原订阅合同,兼容旧调用)。
  138. #[derive(Deserialize)]
  139. pub struct SubscriptionChangeReq {
  140. /// 被替换的原订阅,至多被指向一次(§5.3)。
  141. pub replaces_subscription_id: String,
  142. pub plan_id: String,
  143. /// 新合同(契约明写「不得沿用原合同」;缺省=沿用原订阅合同)。
  144. pub contract_id: Option<String>,
  145. /// 新合同服务条目(缺省=按新档位在合同内反查)。
  146. pub contract_item_id: Option<String>,
  147. /// 仅做一致性校验:与原订阅客户不同即拒。
  148. pub customer_id: Option<String>,
  149. /// 缺省=当天(截原基线)。
  150. pub start_date: Option<String>,
  151. pub term: Option<String>,
  152. pub trial_months: Option<i64>,
  153. pub discount_monthly_cents: Option<i64>,
  154. /// 乐观锁作用于**原订阅行**。
  155. pub row_version: Option<i64>,
  156. #[serde(flatten)]
  157. pub rest: Map<String, Value>,
  158. }
  159. /// 修改载荷:白名单两列+乐观锁,其余键一律拒收(§5.7)。
  160. #[derive(Deserialize)]
  161. pub struct SubscriptionUpdateReq {
  162. pub subscription_id: String,
  163. pub row_version: i64,
  164. pub trial_months: Option<i64>,
  165. pub discount_monthly_cents: Option<i64>,
  166. #[serde(flatten)]
  167. pub rest: Map<String, Value>,
  168. }
  169. #[derive(Deserialize)]
  170. pub struct SubscriptionIdReq {
  171. pub subscription_id: String,
  172. }
  173. #[derive(Deserialize)]
  174. pub struct SubscriptionOptionsReq {
  175. pub customer_id: String,
  176. /// 只读列表用关键字(⛔ 客户名称/合同编号检索)。
  177. pub keyword: Option<String>,
  178. }
  179. /// 列表入参(`get_list` 与 `list_all` 共用=同一实现只差入参)。
  180. #[derive(Deserialize)]
  181. pub struct SubscriptionListReq {
  182. #[serde(flatten)]
  183. pub pg: PageQuery,
  184. /// 命中套餐名快照/订阅号/订单号/客户名/合同号(LEFT JOIN customer/contract)。
  185. pub keyword: Option<String>,
  186. pub customer_id: Option<String>,
  187. pub contract_id: Option<String>,
  188. pub status: Option<String>,
  189. /// 套餐类型:`fixed`/`custom`(快照列 `subscription.plan_kind`)。
  190. pub plan_kind: Option<String>,
  191. /// 线路出口名称(命中 `line_exits` 快照 JSON 文本)。
  192. pub line_exit: Option<String>,
  193. /// 快到期:止期落在 `[today, today+N]`(含边界;已到期不算)。
  194. pub expiring_within_days: Option<i64>,
  195. /// 区域筛选=按客户挂载区域展开成客户集合(§5.7)。
  196. pub region_ids: Option<Vec<String>>,
  197. #[serde(flatten)]
  198. pub rest: Map<String, Value>,
  199. }
  200. #[derive(Deserialize)]
  201. pub struct SubscriptionGetReq {
  202. pub subscription_id: String,
  203. }
  204. #[derive(Deserialize)]
  205. pub struct SubscriptionStackReq {
  206. pub subscription_id: Option<String>,
  207. pub end_date: Option<String>,
  208. pub annual_price_cents: Option<i64>,
  209. pub monthly_settle_cents: Option<i64>,
  210. /// 以下五列只属于 openapi 的「叠加新建」分支,本轮⛔ 新建行 ⇒ 带上就点名未落库。
  211. pub customer_id: Option<String>,
  212. pub plan_id: Option<String>,
  213. pub contract_id: Option<String>,
  214. pub contract_item_id: Option<String>,
  215. pub start_date: Option<String>,
  216. pub row_version: Option<i64>,
  217. }
  218. // ───────────────────────── 共用小件 ─────────────────────────
  219. fn trimmed(raw: &str) -> String {
  220. raw.trim().to_string()
  221. }
  222. /// 必填串;空白=显式失败(⛔ 落成空串)。
  223. pub(crate) fn req_field(field: &str, raw: &str) -> Result<String, BosError> {
  224. let s = trimmed(raw);
  225. if s.is_empty() {
  226. return Err(BosError::bad_params(format!("{field} 必填")));
  227. }
  228. Ok(s)
  229. }
  230. /// `YYYY-MM-DD` 解析(同时兜住「日期不可比」与「非法值传给 `::date` 后 UDS 报错」两种失效形态)。
  231. pub(crate) fn parse_date(field: &str, raw: &str) -> Result<NaiveDate, BosError> {
  232. NaiveDate::parse_from_str(raw.trim(), "%Y-%m-%d")
  233. .map_err(|_| BosError::bad_params(format!("{field} 须为 YYYY-MM-DD,实得 {raw}")))
  234. }
  235. pub(crate) fn date_text(d: NaiveDate) -> String {
  236. d.format("%Y-%m-%d").to_string()
  237. }
  238. pub(crate) fn today() -> String {
  239. chrono::Local::now().format("%Y-%m-%d").to_string()
  240. }
  241. pub(crate) fn opt_trim(v: Option<&String>) -> Option<&str> {
  242. v.map(String::as_str).map(str::trim).filter(|s| !s.is_empty())
  243. }
  244. /// 只读派生列出现在载荷里 ⇒ `11103` 逐列点名(⛔ 忽略、⛔ 只取服务端值而不告知)。
  245. fn reject_read_only(rest: &Map<String, Value>, keys: &[&str]) -> Result<(), BosError> {
  246. let hit: Vec<&str> = keys.iter().copied().filter(|k| rest.contains_key(*k)).collect();
  247. if hit.is_empty() {
  248. return Ok(());
  249. }
  250. Err(BosError::bad_params(format!(
  251. "以下只读派生列不接受入参(服务端按档位/条目折算落库):{}",
  252. hit.join("、")
  253. )))
  254. }
  255. /// 月数折算(§2.3:年=12/季=3/月=1)。
  256. pub(crate) fn term_months(term: &str) -> Result<u32, BosError> {
  257. match term {
  258. "yearly" => Ok(12),
  259. "quarterly" => Ok(3),
  260. "monthly" => Ok(1),
  261. other => Err(BosError::bad_params(format!(
  262. "term 须∈ {TERMS:?},实得 {other}"
  263. ))),
  264. }
  265. }
  266. /// 加 `n` 个月并把不存在的日期折到月末(§5.2「该月无对应日取月末」)。
  267. pub(crate) fn add_months_clamped(d: NaiveDate, n: u32) -> NaiveDate {
  268. let total = d.year() as u64 * 12 + (d.month0() as u64) + n as u64;
  269. let year = (total / 12) as i64;
  270. let month = ((total % 12) + 1) as u32;
  271. let dim = days_in_month(year, u64::from(month));
  272. let day = d.day().min(dim);
  273. NaiveDate::from_ymd_opt(year as i32, month, day).unwrap_or(d)
  274. }
  275. fn days_in_month(year: i64, month: u64) -> u32 {
  276. let m = month as u32;
  277. match m {
  278. 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
  279. 4 | 6 | 9 | 11 => 30,
  280. 2 => {
  281. if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
  282. 29
  283. } else {
  284. 28
  285. }
  286. }
  287. _ => 30,
  288. }
  289. }
  290. /// 年订阅价格=`term` × 月结算标准金额(季=月×3、月=月;年取档位年价原值)。
  291. pub(crate) fn annual_by_term(plan_annual: i64, monthly: i64, term: &str) -> i64 {
  292. match term {
  293. "monthly" => monthly,
  294. "quarterly" => monthly.saturating_mul(3),
  295. _ => plan_annual,
  296. }
  297. }
  298. /// JSONB 出口列 → 字符串数组(dev 用 JSONB 承载 `TEXT[]`,可能回数组也可能回 JSON 串)。
  299. pub(crate) fn exits_of(v: Option<&Value>, field: &str) -> Result<Vec<String>, BosError> {
  300. let bad = || BosError::bad_params(format!("{field} 须为字符串数组(线路出口原值)"));
  301. match v {
  302. None | Some(Value::Null) => Ok(Vec::new()),
  303. Some(Value::String(s)) => serde_json::from_str::<Vec<String>>(s)
  304. .map_err(|_| BosError::bad_params(format!("{field} 不是字符串数组的 JSON:{s}"))),
  305. Some(Value::Array(arr)) => arr
  306. .iter()
  307. .map(|x| {
  308. x.as_str()
  309. .map(str::to_string)
  310. .filter(|s| !s.trim().is_empty())
  311. .ok_or_else(bad)
  312. })
  313. .collect(),
  314. Some(_) => Err(bad()),
  315. }
  316. }
  317. /// 出口列出参:JSONB 原样回(⛔ 摊平、⛔ 用摘要冒充原值)。
  318. pub(crate) fn exits_json(v: Option<&Value>) -> Value {
  319. match v {
  320. Some(Value::String(s)) => serde_json::from_str::<Value>(s).unwrap_or(Value::Null),
  321. Some(x) => x.clone(),
  322. None => Value::Null,
  323. }
  324. }
  325. /// 读侧的日期口径:设计列 → 一期骨架列(存量种子只有旧列有值)。
  326. pub(crate) fn start_text(r: &SubRow) -> Option<String> {
  327. opt_trim(r.start_date.as_ref())
  328. .or_else(|| opt_trim(r.effective_date.as_ref()))
  329. .map(|s| s.to_string())
  330. }
  331. pub(crate) fn end_text(r: &SubRow) -> Option<String> {
  332. opt_trim(r.end_date.as_ref())
  333. .or_else(|| opt_trim(r.expire_date.as_ref()))
  334. .map(|s| s.to_string())
  335. }
  336. /// 状态三态的读侧落点:库里的终态(`cancelled`/`replaced`/`early_stopped`)原样保留,
  337. /// 其余按三要素推导。
  338. ///
  339. /// 为什么不直接回库值:库里 `status` 由日终任务翻转,而 `SUB-EFF` 本轮⛔ 未做 ⇒ 直接回库值
  340. /// 会把「已到期」显示成「生效中」;也不⛔ 在日期不可判时硬套三态(会凭空判成到期)。
  341. /// `early_stopped`=提前停机:起止日不变,⛔ 再按日期推回生效中。
  342. pub(crate) fn status_display(r: &SubRow, today: &str) -> (String, String, Option<String>) {
  343. let terminal = |s: &str| s == "cancelled" || s == "replaced" || s == "early_stopped";
  344. let label = |k: &str| match k {
  345. "pending" => "待生效",
  346. "active" => "生效中",
  347. "expired" => "已到期",
  348. "replaced" => "已替换",
  349. "cancelled" => "已退订",
  350. "early_stopped" => "提前停机",
  351. _ => "未知",
  352. };
  353. if terminal(r.status.as_str()) {
  354. return (r.status.clone(), label(r.status.as_str()).to_string(), None);
  355. }
  356. match (start_text(r), end_text(r)) {
  357. (Some(s), Some(e)) => {
  358. let k = subscription_status_of(&s, &e, today).as_str().to_string();
  359. (k.clone(), label(&k).to_string(), None)
  360. }
  361. _ => (
  362. r.status.clone(),
  363. label(&r.status).to_string(),
  364. Some(format!(
  365. "订阅 {0} 的 start_date/end_date 不完整,状态不按三要素推导,原样回库里 status。",
  366. r.subscription_id
  367. )),
  368. ),
  369. }
  370. }
  371. /// 行级可操作性:到期/已替换/已退订的订阅⛔ 升降配、修改、删除(§5.3/§5.7)。
  372. fn editability(r: &SubRow, display_key: &str) -> (bool, Option<String>) {
  373. if display_key != "pending" && display_key != "active" {
  374. return (
  375. false,
  376. Some(format!(
  377. "订阅状态={},不升降配/续订/修改/删除",
  378. display_key
  379. )),
  380. );
  381. }
  382. if opt_trim(r.contract_id.as_ref()).is_none() {
  383. return (
  384. true,
  385. Some("该订阅未关联合同(仅升降配不),合同开通态一栏显示「—」且不显示未开通。".to_string()),
  386. );
  387. }
  388. (true, None)
  389. }
  390. // ───────────────────────── 行与出参 ─────────────────────────
  391. /// 订阅行(读侧快照):`succession` 公共层与合同写口共用同一形态 ⇒ 字段 `pub(crate)`。
  392. #[derive(Clone, Deserialize)]
  393. pub(crate) struct SubRow {
  394. #[serde(deserialize_with = "de::as_string")]
  395. pub(crate) subscription_id: String,
  396. #[serde(deserialize_with = "de::as_string")]
  397. pub(crate) customer_id: String,
  398. #[serde(deserialize_with = "de::as_opt_string")]
  399. pub(crate) contract_id: Option<String>,
  400. #[serde(deserialize_with = "de::as_opt_string")]
  401. pub(crate) contract_item_id: Option<String>,
  402. #[serde(deserialize_with = "de::as_opt_string")]
  403. pub(crate) plan_id: Option<String>,
  404. #[serde(deserialize_with = "de::as_opt_string")]
  405. pub(crate) plan_name: Option<String>,
  406. #[serde(deserialize_with = "de::as_opt_string")]
  407. pub(crate) plan_kind: Option<String>,
  408. #[serde(deserialize_with = "de::as_opt_string")]
  409. pub(crate) plan_owner_customer_id: Option<String>,
  410. #[serde(deserialize_with = "de::as_string")]
  411. pub(crate) status: String,
  412. #[serde(deserialize_with = "de::as_opt_string")]
  413. pub(crate) plan_family: Option<String>,
  414. /// 历史值:三分类收敛后新行恒 `NULL`(I6 停用),读侧只做只读回显。
  415. #[serde(deserialize_with = "de::as_opt_string")]
  416. pub(crate) sub_mode: Option<String>,
  417. pub(crate) line_exits: Option<Value>,
  418. #[serde(deserialize_with = "de::as_opt_string")]
  419. pub(crate) line_exit_key: Option<String>,
  420. #[serde(deserialize_with = "de::as_opt_string")]
  421. pub(crate) start_date: Option<String>,
  422. #[serde(deserialize_with = "de::as_opt_string")]
  423. pub(crate) end_date: Option<String>,
  424. #[serde(deserialize_with = "de::as_opt_string")]
  425. pub(crate) term: Option<String>,
  426. #[serde(deserialize_with = "de::as_opt_string")]
  427. pub(crate) trial_months: Option<String>,
  428. #[serde(deserialize_with = "de::as_opt_string")]
  429. pub(crate) discount_monthly_cents: Option<String>,
  430. #[serde(deserialize_with = "de::as_opt_string")]
  431. pub(crate) annual_price_cents: Option<String>,
  432. #[serde(deserialize_with = "de::as_opt_string")]
  433. pub(crate) monthly_settle_cents: Option<String>,
  434. #[serde(deserialize_with = "de::as_string")]
  435. pub(crate) quota_slots: String,
  436. #[serde(deserialize_with = "de::as_opt_string")]
  437. pub(crate) replaces_subscription_id: Option<String>,
  438. #[serde(deserialize_with = "de::as_opt_string")]
  439. pub(crate) order_no: Option<String>,
  440. #[serde(deserialize_with = "de::as_opt_string")]
  441. pub(crate) actual_opened_at: Option<String>,
  442. /// 提前停机日(`service_stop` 回填生效写入;起止日不变)。
  443. #[serde(deserialize_with = "de::as_opt_string")]
  444. pub(crate) early_stopped_at: Option<String>,
  445. #[serde(deserialize_with = "de::as_opt_string")]
  446. pub(crate) effective_date: Option<String>,
  447. #[serde(deserialize_with = "de::as_opt_string")]
  448. pub(crate) expire_date: Option<String>,
  449. /// 订阅份数(`subscription.quantity`,2026-11-17 落列):可叠加档可 > 1,其余恒 1。
  450. #[serde(deserialize_with = "de::as_string")]
  451. pub(crate) quantity: String,
  452. /// 附加订阅的父订阅(D-2/D-9):`addon` 必有父、`link` 恒空;父可属另一份合同。
  453. #[serde(deserialize_with = "de::as_opt_string")]
  454. pub(crate) parent_subscription_id: Option<String>,
  455. #[serde(deserialize_with = "de::as_string")]
  456. pub(crate) created_at: String,
  457. #[serde(deserialize_with = "de::as_string")]
  458. pub(crate) row_version: String,
  459. }
  460. /// 列表行的钱列形态(§5.2 段 4「¥20,000(折算 ¥1,667/月)」)。
  461. fn money_json(r: &SubRow) -> Value {
  462. let annual = as_opt_num(r.annual_price_cents.as_deref());
  463. let monthly = as_opt_num(r.monthly_settle_cents.as_deref());
  464. let display = match (&annual, &monthly) {
  465. (Value::Number(a), Value::Number(m)) => Some(format!("{a}(折算 {m}/月)")),
  466. _ => None,
  467. };
  468. json!({
  469. "annual_price_cents": annual,
  470. "monthly_settle_cents": monthly,
  471. "monthly_settle_display": display,
  472. "trial_months": as_opt_num(r.trial_months.as_deref()),
  473. "discount_monthly_cents": as_opt_num(r.discount_monthly_cents.as_deref()),
  474. })
  475. }
  476. /// 列表/详情共用的行出参:`plan_name` 走**快照列**(⛔ 现取 `catalog_plan`)。
  477. fn to_json(
  478. r: &SubRow,
  479. customer_name: Option<&str>,
  480. contract_no: Option<&str>,
  481. today: &str,
  482. ) -> Value {
  483. let (key, label, note) = status_display(r, today);
  484. let (editable, reason) = editability(r, &key);
  485. json!({
  486. "subscription_id": r.subscription_id,
  487. "customer_id": r.customer_id,
  488. "customer_name": customer_name,
  489. "contract_id": r.contract_id,
  490. "contract_no": contract_no,
  491. "contract_item_id": r.contract_item_id,
  492. "plan_id": r.plan_id,
  493. "plan_name": r.plan_name,
  494. "plan_kind": r.plan_kind,
  495. "plan_owner_customer_id": r.plan_owner_customer_id,
  496. "status": r.status,
  497. "status_display": { "key": key, "label": label, "note": note },
  498. "plan_family": r.plan_family,
  499. "sub_mode": r.sub_mode,
  500. "line_exits": exits_json(r.line_exits.as_ref()),
  501. "line_exit_key": r.line_exit_key,
  502. "term": r.term,
  503. "start_date": start_text(r),
  504. "end_date": end_text(r),
  505. "annual_price_cents": as_opt_num(r.annual_price_cents.as_deref()),
  506. "monthly_settle_cents": as_opt_num(r.monthly_settle_cents.as_deref()),
  507. "trial_months": as_opt_num(r.trial_months.as_deref()),
  508. "discount_monthly_cents": as_opt_num(r.discount_monthly_cents.as_deref()),
  509. "quota_slots": as_num(&r.quota_slots),
  510. "quantity": as_num(&r.quantity),
  511. "parent_subscription_id": r.parent_subscription_id,
  512. "replaces_subscription_id": r.replaces_subscription_id,
  513. "order_no": r.order_no,
  514. "actual_opened_at": r.actual_opened_at,
  515. "early_stopped_at": r.early_stopped_at,
  516. "effective_date": r.effective_date,
  517. "expire_date": r.expire_date,
  518. "created_at": r.created_at,
  519. "row_version": as_num(&r.row_version),
  520. "editable": editable,
  521. "reason": reason,
  522. })
  523. }
  524. // ───────────────────────── 取数小件 ─────────────────────────
  525. #[derive(Deserialize)]
  526. struct IdRow {
  527. #[serde(deserialize_with = "de::as_string")]
  528. v: String,
  529. }
  530. #[derive(Deserialize)]
  531. struct CountRow {
  532. #[serde(deserialize_with = "de::as_string")]
  533. c: String,
  534. }
  535. /// 按 ID+可见范围取整行。
  536. async fn scoped_sub(
  537. state: &AppState,
  538. auth: &bos_scope::AuthContext,
  539. sub_id: &str,
  540. ) -> Result<Option<SubRow>, BosError> {
  541. let mut p = Params::default();
  542. let mut w: Vec<String> = Vec::new();
  543. w.push(customer_scope_pred(state, auth, &mut p, "s.customer_id").await?);
  544. let s = p.push(Value::String(sub_id.to_string()));
  545. w.push(format!("s.subscription_id = {s}::text"));
  546. let sql = format!("{SELECT_COLS} FROM subscription s {}", p.where_clause(&w));
  547. state.db.query_one::<SubRow>(&sql, p.values()).await
  548. }
  549. /// 客户在册**且**落在当前账号可见范围(§5.2 第 1 步;越权=`KLT-M221`)。
  550. async fn customer_visible(
  551. state: &AppState,
  552. auth: &bos_scope::AuthContext,
  553. customer_id: &str,
  554. ) -> Result<Option<String>, BosError> {
  555. let mut p = Params::default();
  556. let mut w: Vec<String> = Vec::new();
  557. w.push(customer_scope_pred(state, auth, &mut p, "c.customer_id").await?);
  558. let c = p.push(Value::String(customer_id.to_string()));
  559. w.push(format!("c.customer_id = {c}::text AND c.deleted_at IS NULL"));
  560. let sql = format!(
  561. "SELECT c.customer_name AS v FROM customer c {}",
  562. p.where_clause(&w)
  563. );
  564. Ok(state
  565. .db
  566. .query_one::<IdRow>(&sql, p.values())
  567. .await?
  568. .map(|r| r.v))
  569. }
  570. /// 可见范围谓词由 [`customer_scope_pred`] 统一给出(区域展开出的客户同样受该谓词约束),
  571. /// 本模块⛔ 另取一份「可见客户集合」=两份口径迟早分叉。
  572. /// 区域 → 客户集合展开(§5.7「区域筛选按客户挂载区域展开」=本册⛔ 按区域列查本册表)。
  573. ///
  574. /// 挂载表只有**直接父节点**,故须经 `dim_node_ancestor` 把筛选节点向下展开一层
  575. /// (`ancestor_id = 筛选节点` 的整棵子树都命中)。
  576. async fn customers_under_regions(state: &AppState, region_ids: &[String]) -> Result<Vec<String>, BosError> {
  577. let ids: Vec<String> = region_ids.iter().map(|s| trimmed(s)).filter(|s| !s.is_empty()).collect();
  578. if ids.is_empty() {
  579. return Ok(Vec::new());
  580. }
  581. let mut p = Params::default();
  582. let r = push_in(&mut p, "a.ancestor_id", &ids, "text");
  583. let sql = format!(
  584. "SELECT DISTINCT m.customer_id AS v FROM customer_region_mount m \
  585. JOIN dim_node_ancestor a ON a.node_id = m.parent_node_id \
  586. WHERE {r} AND m.customer_id IS NOT NULL ORDER BY 1"
  587. );
  588. Ok(state
  589. .db
  590. .query_all::<IdRow>(&sql, p.values())
  591. .await?
  592. .into_iter()
  593. .map(|r| r.v)
  594. .collect())
  595. }
  596. /// 某客户的全部订阅(I6/额度对齐/变更链的取数底座)。
  597. pub(crate) async fn subs_of_customer(state: &AppState, customer_id: &str) -> Result<Vec<SubRow>, BosError> {
  598. let mut p = Params::default();
  599. let c = p.push(Value::String(customer_id.to_string()));
  600. let sql = format!(
  601. "{SELECT_COLS} FROM subscription s WHERE s.customer_id = {c}::text ORDER BY s.subscription_id"
  602. );
  603. state.db.query_all::<SubRow>(&sql, p.values()).await
  604. }
  605. /// 档位行(含可用区间与首次引用打点)。`succession` 公共层读同一形态 ⇒ 字段 `pub(crate)`。
  606. #[derive(Deserialize)]
  607. pub(crate) struct PlanRow {
  608. #[serde(deserialize_with = "de::as_string")]
  609. pub(crate) plan_id: String,
  610. #[serde(deserialize_with = "de::as_string")]
  611. pub(crate) plan_name: String,
  612. #[serde(deserialize_with = "de::as_string")]
  613. pub(crate) plan_kind: String,
  614. #[serde(deserialize_with = "de::as_opt_string")]
  615. pub(crate) customer_id: Option<String>,
  616. #[serde(deserialize_with = "de::as_string")]
  617. pub(crate) status: String,
  618. /// 交付形态 `link`/`addon`:条目与订阅的形态**只从这里来**(库上 `ck_plan_family` 兜底)。
  619. #[serde(deserialize_with = "de::as_opt_string")]
  620. pub(crate) plan_family: Option<String>,
  621. #[serde(deserialize_with = "de::as_opt_string")]
  622. pub(crate) sub_account_quota: Option<String>,
  623. #[serde(deserialize_with = "de::as_string")]
  624. pub(crate) annual_price_cents: String,
  625. #[serde(deserialize_with = "de::as_opt_string")]
  626. pub(crate) monthly_settle_cents: Option<String>,
  627. pub(crate) line_exits: Option<Value>,
  628. /// 首次引用打点:`Some` ⇒ 该档已被引用过(§5.2「已引用过的档位⛔ 下架」同源)。
  629. #[serde(deserialize_with = "de::as_opt_string")]
  630. pub(crate) first_referred_at: Option<String>,
  631. }
  632. impl PlanRow {
  633. /// 交付形态(库上 `ck_plan_family` 已保证只有两值;缺失/脏值按 `link` 处理并落读侧告警)。
  634. pub(crate) fn family(&self) -> PlanFamily {
  635. match self.plan_family.as_deref().map(PlanFamily::parse) {
  636. Some(Ok(f)) => f,
  637. _ => {
  638. tracing::warn!(plan_id = %self.plan_id, raw = ?self.plan_family, "档位交付形态缺失/非法,按 link 处理");
  639. PlanFamily::Link
  640. }
  641. }
  642. }
  643. pub(crate) fn to_ref(&self) -> PlanRef {
  644. PlanRef {
  645. plan_id: self.plan_id.clone(),
  646. plan_name: self.plan_name.clone(),
  647. plan_kind: self.plan_kind.clone(),
  648. owner_customer_id: opt_trim(self.customer_id.as_ref()).map(str::to_string),
  649. plan_family: self.family(),
  650. sub_account_quota: self
  651. .sub_account_quota
  652. .as_deref()
  653. .and_then(|s| s.trim().parse::<i64>().ok())
  654. .unwrap_or(0),
  655. annual_price_cents: self
  656. .annual_price_cents
  657. .trim()
  658. .parse::<i64>()
  659. .unwrap_or(0),
  660. monthly_settle_cents: self
  661. .monthly_settle_cents
  662. .as_deref()
  663. .and_then(|s| s.trim().parse::<i64>().ok()),
  664. available: self.status == "active",
  665. }
  666. }
  667. pub(crate) fn monthly(&self) -> i64 {
  668. monthly_settle_of(self.monthly_settle_cents.as_deref().and_then(|s| s.trim().parse().ok()), self.annual_price_cents.trim().parse().unwrap_or(0))
  669. }
  670. }
  671. pub(crate) async fn plan_rows(state: &AppState, ids: &[String]) -> Result<Vec<PlanRow>, BosError> {
  672. if ids.is_empty() {
  673. return Ok(Vec::new());
  674. }
  675. let mut p = Params::default();
  676. let in_pred = push_in(&mut p, "p.plan_id", ids, "text");
  677. let sql = format!("{PLAN_COLS} FROM catalog_plan p WHERE {in_pred}");
  678. state.db.query_all::<PlanRow>(&sql, p.values()).await
  679. }
  680. pub(crate) async fn plan_row(state: &AppState, plan_id: &str) -> Result<Option<PlanRow>, BosError> {
  681. Ok(plan_rows(state, &[plan_id.to_string()]).await?.pop())
  682. }
  683. /// 合同行。
  684. #[derive(Deserialize)]
  685. pub(crate) struct ContractRow {
  686. #[serde(deserialize_with = "de::as_string")]
  687. pub(crate) contract_id: String,
  688. #[serde(deserialize_with = "de::as_string")]
  689. pub(crate) customer_id: String,
  690. #[serde(deserialize_with = "de::as_string")]
  691. pub(crate) contract_no: String,
  692. #[serde(deserialize_with = "de::as_opt_string")]
  693. pub(crate) external_no: Option<String>,
  694. #[serde(deserialize_with = "de::as_string")]
  695. pub(crate) status: String,
  696. #[serde(deserialize_with = "de::as_opt_string")]
  697. pub(crate) end_date: Option<String>,
  698. /// 合同总额(`contract.amount_cents`,分)。可空 ⇒ 客户端「总金额」列显「—」,
  699. /// ⛔ 回落 `subscription.annual_price_cents`(那是订阅价,升降配后必然不等)。
  700. #[serde(default, deserialize_with = "de::as_opt_string")]
  701. pub(crate) amount_cents: Option<String>,
  702. #[serde(deserialize_with = "de::as_opt_string")]
  703. pub(crate) attachment_url: Option<String>,
  704. }
  705. const CONTRACT_COLS: &str = "SELECT k.contract_id, k.customer_id, k.contract_no, k.external_no, k.status, \
  706. k.end_date, k.amount_cents, k.attachment_url";
  707. pub(crate) async fn contracts_of_customer(
  708. state: &AppState,
  709. customer_id: &str,
  710. ) -> Result<Vec<ContractRow>, BosError> {
  711. let mut p = Params::default();
  712. let c = p.push(Value::String(customer_id.to_string()));
  713. let sql = format!(
  714. "{CONTRACT_COLS} FROM contract k WHERE k.customer_id = {c}::text ORDER BY k.contract_id"
  715. );
  716. state.db.query_all::<ContractRow>(&sql, p.values()).await
  717. }
  718. pub(crate) async fn contract_row(state: &AppState, contract_id: &str) -> Result<Option<ContractRow>, BosError> {
  719. let mut p = Params::default();
  720. let c = p.push(Value::String(contract_id.to_string()));
  721. let sql = format!("{CONTRACT_COLS} FROM contract k WHERE k.contract_id = {c}::text");
  722. state.db.query_one::<ContractRow>(&sql, p.values()).await
  723. }
  724. /// 合同服务构成条目(`plan_id` 必填:条目只剩「档位 × 份数」)。`succession` 共用 ⇒ 字段 `pub(crate)`。
  725. #[derive(Deserialize)]
  726. pub(crate) struct ItemRow {
  727. #[serde(deserialize_with = "de::as_string")]
  728. pub(crate) item_id: String,
  729. #[serde(deserialize_with = "de::as_string")]
  730. pub(crate) contract_id: String,
  731. #[serde(deserialize_with = "de::as_opt_string")]
  732. pub(crate) plan_id: Option<String>,
  733. /// 档位份数(2026-11-17:随条目带入订阅 `subscription.quantity`)。
  734. #[serde(deserialize_with = "de::as_opt_string")]
  735. pub(crate) quantity: Option<String>,
  736. /// 交付形态(落库列;=所引档位的 `plan_family`,应用层已校验一致)。
  737. #[serde(deserialize_with = "de::as_opt_string")]
  738. pub(crate) item_family: Option<String>,
  739. /// 条目形态(D-9):`new`/`increment`。
  740. #[serde(deserialize_with = "de::as_opt_string")]
  741. pub(crate) item_mode: Option<String>,
  742. /// 父条目(D-7/D-2):附加条目指向同合同的 `link` 条目;增量条目恒空。
  743. #[serde(deserialize_with = "de::as_opt_string")]
  744. pub(crate) serves_item_id: Option<String>,
  745. /// 增量条目的既有链路订阅(D-9):父订阅可属另一份合同。
  746. #[serde(deserialize_with = "de::as_opt_string")]
  747. pub(crate) ref_subscription_id: Option<String>,
  748. pub(crate) line_exits: Option<Value>,
  749. }
  750. const ITEM_COLS: &str = "SELECT i.item_id, i.contract_id, i.plan_id, i.quantity, \
  751. i.item_family, i.item_mode, i.serves_item_id, i.ref_subscription_id, i.line_exits";
  752. pub(crate) async fn items_of_contracts(
  753. state: &AppState,
  754. contract_ids: &[String],
  755. ) -> Result<Vec<ItemRow>, BosError> {
  756. if contract_ids.is_empty() {
  757. return Ok(Vec::new());
  758. }
  759. let mut p = Params::default();
  760. let in_pred = push_in(&mut p, "i.contract_id", contract_ids, "text");
  761. let sql = format!("{ITEM_COLS} FROM contract_service_item i WHERE {in_pred} ORDER BY i.item_id");
  762. state.db.query_all::<ItemRow>(&sql, p.values()).await
  763. }
  764. /// 开通态探测(§5.2 段 5:工单一维本轮未接线=`Unconfigured`;本域自读 `actual_opened_at`)。
  765. ///
  766. /// 取数失败 ⇒ `KLT-S406` 整体失败,⛔ 降级成「全部未开通」(那会把已交付合同摆进候选、
  767. /// 再经 `KLT-M223` 永久封死补录路径)。
  768. async fn opened_map_for(
  769. state: &AppState,
  770. contracts: &[ContractRow],
  771. ) -> Result<HashMap<String, Opened>, BosError> {
  772. let ids: Vec<String> = contracts.iter().map(|c| c.contract_id.clone()).collect();
  773. let mut actual: HashMap<String, Vec<Option<String>>> = HashMap::new();
  774. if !ids.is_empty() {
  775. let mut p = Params::default();
  776. let in_pred = push_in(&mut p, "s.contract_id", &ids, "text");
  777. let sql = format!(
  778. "SELECT s.contract_id AS k, s.actual_opened_at AS v FROM subscription s WHERE {in_pred}"
  779. );
  780. #[derive(Deserialize)]
  781. struct Pair {
  782. #[serde(deserialize_with = "de::as_string")]
  783. k: String,
  784. #[serde(deserialize_with = "de::as_opt_string")]
  785. v: Option<String>,
  786. }
  787. let rows = state.db.query_all::<Pair>(&sql, p.values()).await.map_err(|e| {
  788. BosError::klt(
  789. KltCode::S406,
  790. format!("读取订阅实际开通日失败,开通态不可判定(不降级成「未开通」):{e}"),
  791. )
  792. })?;
  793. for r in rows {
  794. actual.entry(r.k).or_default().push(r.v);
  795. }
  796. }
  797. let probes: Vec<(String, OpenedProbe)> = contracts
  798. .iter()
  799. .map(|c| {
  800. (
  801. c.contract_id.clone(),
  802. OpenedProbe {
  803. open_tickets: CrossRead::Unconfigured,
  804. subscription_actual_opened_at: actual
  805. .get(&c.contract_id)
  806. .cloned()
  807. .unwrap_or_default(),
  808. },
  809. )
  810. })
  811. .collect();
  812. contracts_opened(&probes).map_err(|e| {
  813. BosError::klt(KltCode::S406, format!("开通态判定失败(不降级成「未开通」):{e}"))
  814. })
  815. }
  816. // ───────────────────────── §5.2 套餐候选 ─────────────────────────
  817. /// `POST /subscription/plan_options@v1`。
  818. ///
  819. /// 两段候选=本客户自定义档 + 全部固定档,⛔ 他客户自定义档;
  820. /// 每行带只读 `plan_family`(交付形态)与可选性/不可选原因。
  821. pub async fn plan_options(
  822. State(state): State<AppState>,
  823. RequireAuth(auth): RequireAuth,
  824. DataBody(body): DataBody<SubscriptionOptionsReq>,
  825. ) -> Response {
  826. if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
  827. return json_err(e);
  828. }
  829. let cid = match req_field("customer_id", &body.customer_id) {
  830. Ok(v) => v,
  831. Err(e) => return json_err(e),
  832. };
  833. // 读口同样把客户当不可信输入重算 ⇒ `KLT-M221`(一次判定,⛔ 重复查库)
  834. if let Err(e) = require_customer(&state, &auth, &cid).await {
  835. return json_err(e);
  836. }
  837. let kw = opt_trim(body.keyword.as_ref());
  838. let mut p = Params::default();
  839. let mut w: Vec<String> = vec![format!(
  840. "(p.plan_kind = {}::text OR (p.plan_kind = {}::text AND p.customer_id = {}::text))",
  841. p.push(Value::String("fixed".to_string())),
  842. p.push(Value::String("custom".to_string())),
  843. p.push(Value::String(cid.clone()))
  844. )];
  845. if let Some(k) = p.push_like(kw) {
  846. w.push(format!("p.plan_name LIKE {k}"));
  847. }
  848. let sql = format!(
  849. "{PLAN_COLS} FROM catalog_plan p {} ORDER BY p.plan_kind, p.plan_name, p.plan_id",
  850. p.where_clause(&w)
  851. );
  852. let rows = match state.db.query_all::<PlanRow>(&sql, p.values()).await {
  853. Ok(r) => r,
  854. Err(e) => return json_err(e),
  855. };
  856. // 引用次数单独取(⛔ 相关子查询混进档位行),与本册其它计数同源走 `listq::count_by`
  857. let plan_ids: Vec<String> = rows.iter().map(|r| r.plan_id.clone()).collect();
  858. let referred = match count_by(state.db.as_ref(), "subscription", "plan_id", &plan_ids).await {
  859. Ok(m) => m,
  860. Err(e) => return json_err(e),
  861. };
  862. let items: Vec<Value> = rows
  863. .iter()
  864. .map(|o| {
  865. let pr = o.to_ref();
  866. let (available, reason) = plan_selectability(&pr, &cid);
  867. let rc = referred.get(&o.plan_id).copied().unwrap_or(0);
  868. json!({
  869. "plan_id": o.plan_id,
  870. "plan_name": o.plan_name,
  871. "plan_kind": o.plan_kind,
  872. "owner_customer_id": o.customer_id,
  873. "plan_family": pr.plan_family.as_str(),
  874. "annual_price_cents": as_num(&o.annual_price_cents),
  875. "monthly_settle_cents": as_num(&o.monthly().to_string()),
  876. "sub_account_quota": as_opt_num(o.sub_account_quota.as_deref()),
  877. "line_exits": exits_json(o.line_exits.as_ref()),
  878. "referred_count": rc,
  879. "first_referred": o.first_referred_at.is_some(),
  880. "available": available,
  881. "unavailable_reason": reason,
  882. })
  883. })
  884. .collect();
  885. json_ok(json!({
  886. "customer_id": cid,
  887. "items": items,
  888. "total": items.len(),
  889. "notes": [
  890. "「交付形态」(link/addon)与额度、带宽、出口一并随档位,前端不重实现;\
  891. 叠加服务额度恒 0,条目/订阅份数 ≥1;跨境链路份数恒 1。",
  892. TICKET_UNCONFIGURED_NOTE,
  893. ],
  894. "columns_pending": COLUMNS_PENDING,
  895. }))
  896. }
  897. /// 档位可选性(§5.2「不可选=KLT-M228」的读侧同源判据;写侧兜底仍走 I12a/I12b)。
  898. ///
  899. /// ⚠️ 档位⛔ 有「可用日期窗口」列(`catalog_plan` 在册列只到 `status`/`first_referred_at`,
  900. /// 设计稿未给 `available_from`/`available_to`)⇒ 停用只按 `status` 判,⛔ 造列。
  901. pub(crate) fn plan_selectability(pr: &PlanRef, customer_id: &str) -> (bool, Option<String>) {
  902. if !pr.available {
  903. return (false, Some("档位已停用,不被新订阅选中".to_string()));
  904. }
  905. if let Some(owner) = pr.owner_customer_id.as_deref() {
  906. if owner != customer_id {
  907. return (false, Some(format!("自定义档归属客户 {owner},不跨客户选用")));
  908. }
  909. }
  910. (true, None)
  911. }
  912. // ───────────────────── 后置审计(§4.11/08 册 §8.1·§8.3)─────────────────────
  913. /// 订阅审计快照的**统一取值面**(§8.2:同一字段前后必须同型 ⇒ 新增/编辑/叠加/换约/删除共用)。
  914. ///
  915. /// 金额一律按「分」记(§8.1);`line_exits` 记编码数组;⛔ 把整表原文塞进审计。
  916. #[derive(Clone)]
  917. pub(crate) struct SubAuditView {
  918. subscription_id: String,
  919. customer_id: String,
  920. status: String,
  921. plan_id: Option<String>,
  922. plan_name: Option<String>,
  923. plan_family: Option<String>,
  924. sub_mode: Option<String>,
  925. line_exits: Option<Value>,
  926. term: Option<String>,
  927. start_date: Option<String>,
  928. end_date: Option<String>,
  929. trial_months: Option<i64>,
  930. discount_monthly_cents: Option<i64>,
  931. annual_price_cents: Option<i64>,
  932. monthly_settle_cents: Option<i64>,
  933. contract_id: Option<String>,
  934. contract_item_id: Option<String>,
  935. order_no: Option<String>,
  936. replaces_subscription_id: Option<String>,
  937. }
  938. impl SubAuditView {
  939. pub(crate) fn of_row(r: &SubRow) -> Self {
  940. Self {
  941. subscription_id: r.subscription_id.clone(),
  942. customer_id: r.customer_id.clone(),
  943. status: r.status.clone(),
  944. plan_id: r.plan_id.clone(),
  945. plan_name: r.plan_name.clone(),
  946. plan_family: r.plan_family.clone(),
  947. sub_mode: r.sub_mode.clone(),
  948. line_exits: r.line_exits.clone(),
  949. term: r.term.clone(),
  950. start_date: r.start_date.clone(),
  951. end_date: r.end_date.clone(),
  952. trial_months: as_opt_num(r.trial_months.as_deref()).as_i64(),
  953. discount_monthly_cents: as_opt_num(r.discount_monthly_cents.as_deref()).as_i64(),
  954. annual_price_cents: as_opt_num(r.annual_price_cents.as_deref()).as_i64(),
  955. monthly_settle_cents: as_opt_num(r.monthly_settle_cents.as_deref()).as_i64(),
  956. contract_id: r.contract_id.clone(),
  957. contract_item_id: r.contract_item_id.clone(),
  958. order_no: r.order_no.clone(),
  959. replaces_subscription_id: r.replaces_subscription_id.clone(),
  960. }
  961. }
  962. pub(crate) fn to_json(&self) -> Value {
  963. json!({
  964. "subscription_id": self.subscription_id,
  965. "customer_id": self.customer_id,
  966. "status": self.status,
  967. "plan_id": self.plan_id,
  968. "plan_name": self.plan_name,
  969. "plan_family": self.plan_family,
  970. "sub_mode": self.sub_mode,
  971. "line_exits": self.line_exits,
  972. "term": self.term,
  973. "start_date": self.start_date,
  974. "end_date": self.end_date,
  975. "trial_months": self.trial_months,
  976. "discount_monthly_cents": self.discount_monthly_cents,
  977. "annual_price_cents": self.annual_price_cents,
  978. "monthly_settle_cents": self.monthly_settle_cents,
  979. "contract_id": self.contract_id,
  980. "contract_item_id": self.contract_item_id,
  981. "order_no": self.order_no,
  982. "replaces_subscription_id": self.replaces_subscription_id,
  983. })
  984. }
  985. /// 同型快照 ⇒ 字段级 diff(§8.1 CU-18:记改了哪些字段+原值→新值)
  986. fn diff(&self, before: &SubAuditView) -> Value {
  987. let (b, a) = (before.to_json(), self.to_json());
  988. let (Some(b), Some(a)) = (b.as_object(), a.as_object()) else {
  989. return json!([]);
  990. };
  991. let mut m = serde_json::Map::new();
  992. for k in b.keys().chain(a.keys()) {
  993. if k == "subscription_id" {
  994. continue;
  995. }
  996. let (bv, av) = (b.get(k), a.get(k));
  997. if bv != av {
  998. m.insert(k.clone(), json!({ "old": bv, "new": av }));
  999. }
  1000. }
  1001. Value::Object(m)
  1002. }
  1003. }
  1004. /// 写一条订阅后置审计(§4.11:`write_audit` 是唯一写入口;动作名走 08 册 §8.3 登记表:
  1005. /// `subscription.create`/`subscription.replace`/`subscription.update`/`subscription.delete`)。
  1006. ///
  1007. /// 与其余域同口径:业务短批落库后同请求内补写,⛔ 审计失败把主流程带崩 ⇒ 只回 `audit_written:false`。
  1008. pub(crate) async fn write_sub_audit(
  1009. state: &AppState,
  1010. auth: &bos_scope::AuthContext,
  1011. action: &str,
  1012. subscription_id: &str,
  1013. before: Option<Value>,
  1014. after: Option<Value>,
  1015. detail: Value,
  1016. ) -> bool {
  1017. let ev = bos_platform::audit::AuditEvent {
  1018. actor_user_id: auth.user_id.clone(),
  1019. action: action.to_string(),
  1020. resource_type: "subscription".to_string(),
  1021. resource_id: subscription_id.to_string(),
  1022. before,
  1023. after,
  1024. detail: Some(detail),
  1025. };
  1026. match state.db.write_audit(&ev).await {
  1027. Ok(()) => true,
  1028. Err(e) => {
  1029. tracing::warn!(
  1030. "subscription 后置审计未写入(action={action},subscription_id={subscription_id}):{e}"
  1031. );
  1032. false
  1033. }
  1034. }
  1035. }
  1036. // ───────────────────────── 合同候选 ─────────────────────────
  1037. /// 合同候选的契约空态文案(TC-CU-50 步骤 1 逐字:下拉里出现的就是这一句)
  1038. const CONTRACT_OPTIONS_EMPTY_TEXT: &str = "—(该客户没有可选的未开通合同)";
  1039. /// 合同是否已到期(TC-CU-51 步骤 1:已开通与**已到期**的⛔ 出现在候选里)。
  1040. ///
  1041. /// 一律按**服务端当日**判定(⛔ 信前端传值);日期取前 10 字符(`YYYY-MM-DD`)做字典序比较。
  1042. /// 缺失或形态不可用 ⇒ `false`(⛔ 当成已到期剔除,与 §4.9 `lifecycle()` 的「⛔ 猜」同口径)。
  1043. fn contract_expired(end_date: Option<&String>, today: &str) -> bool {
  1044. let Some(raw) = opt_trim(end_date) else {
  1045. return false;
  1046. };
  1047. let key: String = raw.chars().take(10).collect();
  1048. let b = key.as_bytes();
  1049. b.len() == 10 && b[4] == b'-' && b[7] == b'-' && key.as_str() < today
  1050. }
  1051. /// `POST /subscription/contract_options@v1`。
  1052. ///
  1053. /// 只出「未开通」合同(开通态=开户工单 ∪ 关联订阅 `actual_opened_at`),两级=合同 → 尚未有订阅的
  1054. /// 条目;`custom_spec` 条目带其派生档。⛔ 月结算标准金额出现在本口出参。
  1055. pub async fn contract_options(
  1056. State(state): State<AppState>,
  1057. RequireAuth(auth): RequireAuth,
  1058. DataBody(body): DataBody<SubscriptionOptionsReq>,
  1059. ) -> Response {
  1060. if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
  1061. return json_err(e);
  1062. }
  1063. let cid = match req_field("customer_id", &body.customer_id) {
  1064. Ok(v) => v,
  1065. Err(e) => return json_err(e),
  1066. };
  1067. // 取数失败⛔ 判成「不可见」(M221 会掩盖故障):可见性只由 `require_customer` 一处给出
  1068. if let Err(e) = require_customer(&state, &auth, &cid).await {
  1069. return json_err(e);
  1070. }
  1071. let contracts = match contracts_of_customer(&state, &cid).await {
  1072. Ok(v) => v,
  1073. Err(e) => return json_err(e),
  1074. };
  1075. let opened = match opened_map_for(&state, &contracts).await {
  1076. Ok(m) => m,
  1077. Err(e) => return json_err(e),
  1078. };
  1079. // 候选过滤(TC-CU-51 步骤 1):已开通 ⇒ 剔除;**已到期** ⇒ 同样剔除(此前只看 `not_opened`
  1080. // ⇒ 期间已过的合同仍进候选,换一份数据就能建出错订阅=D-68)。到期按服务端当日算。
  1081. let t = today();
  1082. let mut opened_n = 0usize;
  1083. let mut expired_n = 0usize;
  1084. let mut undetermined_n = 0usize;
  1085. let mut free: Vec<&ContractRow> = Vec::new();
  1086. for c in &contracts {
  1087. match opened.get(&c.contract_id) {
  1088. Some(Opened::NotOpened) if contract_expired(c.end_date.as_ref(), &t) => expired_n += 1,
  1089. Some(Opened::NotOpened) => free.push(c),
  1090. Some(_) => opened_n += 1,
  1091. // 开通态取不到=不可判定 ⇒ ⛔ 放进候选(与原先只认 `not_opened` 的保守口径一致)
  1092. None => undetermined_n += 1,
  1093. }
  1094. }
  1095. if free.is_empty() {
  1096. // TC-CU-50 步骤 1:一个都没有 ⇒ 下拉给空态句。空态是**正常结果**、⛔ 错误(写入侧的拦截
  1097. // 仍走 `KLT-M222`),这里回 200 + 机器可读标记 + 契约文案,前端直接渲染空态。
  1098. let reason = if contracts.is_empty() {
  1099. "no_contract"
  1100. } else if opened_n == 0 && undetermined_n == 0 {
  1101. "all_expired"
  1102. } else if expired_n == 0 && undetermined_n == 0 {
  1103. "all_opened"
  1104. } else {
  1105. "all_excluded"
  1106. };
  1107. return json_ok(json!({
  1108. "customer_id": cid,
  1109. "items": [],
  1110. "total": 0,
  1111. "empty_state": true,
  1112. "empty_text": CONTRACT_OPTIONS_EMPTY_TEXT,
  1113. "empty_reason": reason,
  1114. "excluded": {
  1115. "opened": opened_n,
  1116. "expired": expired_n,
  1117. "undetermined": undetermined_n
  1118. },
  1119. "notes": [
  1120. "一期「未开通」=该合同无任何名下订阅(含已取消);已到期合同同样不进候选(TC-CU-51)",
  1121. "到期判定按服务端当日比较合同止期,不采信前端传入的日期",
  1122. "工单侧读口未接线 ⇒ opened_state=unconfigured,本结论仅覆盖「是否已有订阅」+止期"
  1123. ]
  1124. }));
  1125. }
  1126. let ids: Vec<String> = free.iter().map(|c| c.contract_id.clone()).collect();
  1127. let items = match items_of_contracts(&state, &ids).await {
  1128. Ok(v) => v,
  1129. Err(e) => return json_err(e),
  1130. };
  1131. // 已被订阅引用的条目⛔ 再被选(§5.2「尚未有订阅的条目」)。
  1132. let mut referenced: HashSet<String> = HashSet::new();
  1133. if !ids.is_empty() {
  1134. let mut p = Params::default();
  1135. let in_pred = match push_in_owned(&mut p, "s.contract_id", &ids) {
  1136. Ok(v) => v,
  1137. Err(e) => return json_err(e),
  1138. };
  1139. let sql = format!(
  1140. "SELECT s.contract_item_id AS v FROM subscription s \
  1141. WHERE {in_pred} AND s.contract_item_id IS NOT NULL"
  1142. );
  1143. match state.db.query_all::<IdRow>(&sql, p.values()).await {
  1144. Ok(rows) => referenced = rows.into_iter().map(|r| r.v).collect(),
  1145. Err(e) => return json_err(e),
  1146. }
  1147. }
  1148. let plan_ids: Vec<String> = items.iter().filter_map(|i| i.plan_id.clone()).collect();
  1149. let plans = match plan_rows(&state, &plan_ids).await {
  1150. Ok(v) => v,
  1151. Err(e) => return json_err(e),
  1152. };
  1153. let plan_by_id: HashMap<&str, &PlanRow> = plans.iter().map(|r| (r.plan_id.as_str(), r)).collect();
  1154. let mut out: Vec<Value> = Vec::new();
  1155. for c in free {
  1156. let rows: Vec<Value> = items
  1157. .iter()
  1158. .filter(|i| i.contract_id == c.contract_id && !referenced.contains(&i.item_id))
  1159. .map(|i| {
  1160. let pid = opt_trim(i.plan_id.as_ref());
  1161. let pr = pid.and_then(|id| plan_by_id.get(id)).map(|r| r.to_ref());
  1162. let (available, reason) = match pr.as_ref() {
  1163. Some(pr) => plan_selectability(pr, &cid),
  1164. None => (false, Some("该条目未关联可选档位".to_string())),
  1165. };
  1166. json!({
  1167. "item_id": i.item_id,
  1168. "plan_id": pid,
  1169. "plan_name": pr.as_ref().map(|p| p.plan_name.clone()),
  1170. "item_family": i.item_family,
  1171. // 份数仍在条目上(订阅 `quantity` 由它带入;`addon` 可 > 1,`link` 恒 1)。
  1172. // ⚠️ DB 列经 `as_opt_string` 读成文本;此处必须 `as_opt_num` 下成 JSON 数值,
  1173. // 否则前端原样回填 `/subscription/create@v1` 会被 serde 拒成
  1174. // `invalid type: string "1", expected i64`(D-02 / KLT-S20004)。
  1175. "quantity": as_opt_num(i.quantity.as_deref()),
  1176. // 价格随所引档位(条目上不再有价格列)⇒ 一律从档位投影。
  1177. "annual_price_cents": pr.as_ref().map(|p| p.annual_price_cents),
  1178. "line_exits": exits_json(i.line_exits.as_ref()),
  1179. "available": available,
  1180. "unavailable_reason": reason,
  1181. })
  1182. })
  1183. .collect();
  1184. // D-33:`contract_no` 保持既有前端在用的「外部单号优先」旧口径(⛔ 直接改口径打断前端);
  1185. // 真合同号在 `internal_no`。同客户多份合同共用一个外部单号时下拉会出现同名选项 ⇒
  1186. // 前端下拉改渲染 `option_label`(内部合同号为主、外部单号括注 ⇒ 天然唯一)。
  1187. let option_label = match opt_trim(c.external_no.as_ref()) {
  1188. Some(e) => format!("{}(外部单号 {e})", c.contract_no),
  1189. None => c.contract_no.clone(),
  1190. };
  1191. out.push(json!({
  1192. "contract_id": c.contract_id,
  1193. "contract_no": opt_trim(c.external_no.as_ref()).unwrap_or(c.contract_no.as_str()),
  1194. "internal_no": c.contract_no,
  1195. "external_no": opt_trim(c.external_no.as_ref()),
  1196. "option_label": option_label,
  1197. "status": c.status,
  1198. "end_date": c.end_date,
  1199. "attachment_url": c.attachment_url,
  1200. "opened": false,
  1201. "items": rows,
  1202. }));
  1203. }
  1204. json_ok(json!({
  1205. "customer_id": cid,
  1206. "items": out,
  1207. "total": out.len(),
  1208. "empty_state": false,
  1209. "empty_text": Value::Null,
  1210. "notes": [
  1211. "出参不出现「月结算标准金额」:月结算只在选定档位后由 monthly_settle_of 折算并只读显示。",
  1212. TICKET_UNCONFIGURED_NOTE,
  1213. ],
  1214. "columns_pending": COLUMNS_PENDING,
  1215. }))
  1216. }
  1217. /// `push_in` 的空集保险版(调用方已保证非空,空集=内部错误而非「不过滤」)。
  1218. fn push_in_owned(p: &mut Params, col: &str, ids: &[String]) -> Result<String, BosError> {
  1219. if ids.is_empty() {
  1220. return Err(BosError::internal("push_in_owned 不接受空 ID 集合(空集会退化成不过滤)"));
  1221. }
  1222. Ok(push_in(p, col, ids, "text"))
  1223. }
  1224. // ───────────────────────── 写侧:共用折算 ─────────────────────────
  1225. /// 交付形态:**只读档位**(D-15:条目/订阅都不再是第二来源)。
  1226. ///
  1227. /// 载荷里带了不同值 ⇒ `11103`(⛔ 静默改写);带了同值=确认回显,放行。
  1228. fn family_of(payload: Option<&String>, plan: &PlanRow) -> Result<PlanFamily, BosError> {
  1229. let plan_family = plan.family();
  1230. if let Some(raw) = opt_trim(payload) {
  1231. let got = PlanFamily::parse(raw)?;
  1232. if got != plan_family {
  1233. return Err(BosError::bad_params(format!(
  1234. "plan_family 由套餐带入({}),不改写为 {}",
  1235. plan_family.as_str(),
  1236. got.as_str()
  1237. )));
  1238. }
  1239. }
  1240. Ok(plan_family)
  1241. }
  1242. /// 周期与价格的派生结果(§5.2 段 3/4)。`succession` 公共层共用 ⇒ 字段 `pub(crate)`。
  1243. #[derive(Clone)]
  1244. pub(crate) struct Period {
  1245. pub(crate) term: String,
  1246. pub(crate) start: String,
  1247. pub(crate) end: String,
  1248. pub(crate) annual: i64,
  1249. pub(crate) monthly: i64,
  1250. }
  1251. /// `term` → 起止与年费/月结算的唯一折算点(⛔ 落库月数、⛔ 手工填价、⛔ 手工改到期日)。
  1252. ///
  1253. /// 实现收口在 [`super::succession::derive_period_of`]:合同新建页的逐条替换同样要按档位派生,
  1254. /// 两处共用一份算式(⛔ 各写一套)。
  1255. pub(crate) fn derive_period(
  1256. plan: &PlanRow,
  1257. term_raw: Option<&String>,
  1258. start_raw: Option<&String>,
  1259. contract_end: Option<&str>,
  1260. today: &str,
  1261. price_factor_scaled: i64,
  1262. ) -> Result<Period, BosError> {
  1263. super::succession::derive_period_of(
  1264. plan.annual_price_cents.trim().parse::<i64>().unwrap_or(0),
  1265. plan.monthly(),
  1266. &plan.plan_id,
  1267. term_raw,
  1268. start_raw,
  1269. super::succession::EndMode::TermMonths(contract_end),
  1270. today,
  1271. price_factor_scaled,
  1272. )
  1273. }
  1274. /// 按归一化出口键取目录系数(缺席/空集 ⇒ 默认 1)。
  1275. pub(crate) fn factor_scaled_for_exits(
  1276. map: &std::collections::HashMap<String, i64>,
  1277. exits: &bos_invariant::NormalizedExits,
  1278. ) -> i64 {
  1279. use bos_invariant::PRICE_FACTOR_SCALE;
  1280. exits
  1281. .line_exits
  1282. .first()
  1283. .and_then(|k| map.get(k).copied())
  1284. .filter(|v| *v > 0)
  1285. .unwrap_or(PRICE_FACTOR_SCALE)
  1286. }
  1287. /// 出口集合的解析+归一化(条目优先,缺省取档位;空集合=`KLT-L216`)。
  1288. pub(crate) fn derive_exits(item: Option<&ItemRow>, plan: &PlanRow) -> Result<NormalizedExits, BosError> {
  1289. let raw = match item {
  1290. Some(i) => exits_of(i.line_exits.as_ref(), "合同条目 line_exits")?,
  1291. None => Vec::new(),
  1292. };
  1293. let raw = if raw.is_empty() {
  1294. exits_of(plan.line_exits.as_ref(), "档位 line_exits")?
  1295. } else {
  1296. raw
  1297. };
  1298. if raw.is_empty() {
  1299. return Err(BosError::klt(
  1300. KltCode::L216,
  1301. format!("出口集合为空,不可保存/提交(档位 {} 与所选条目均无线路出口)", plan.plan_id),
  1302. ));
  1303. }
  1304. normalize_line_exits(&raw)
  1305. }
  1306. /// 额度对齐目标(§5.6 唯一求和实现=`in_use_quota_sum_batch`,⛔ 本口另实现一套计数)。
  1307. ///
  1308. /// `extra_plan` = 本次要写入/要摘除的订阅所引档位:`Some` 计入(新订、升降配),
  1309. /// 摘除一行时由调用方先从 `rows` 里剔掉再求和(§5.7 第 6 步回退对齐)。
  1310. pub(crate) async fn quota_target(
  1311. state: &AppState,
  1312. customer_id: &str,
  1313. rows: &[SubRow],
  1314. ) -> Result<i64, BosError> {
  1315. let plan_ids: Vec<String> = rows.iter().filter_map(|r| r.plan_id.clone()).collect();
  1316. let plans = plan_rows(state, &plan_ids).await?;
  1317. let mut quota_of_plan: HashMap<String, i64> = HashMap::new();
  1318. for p in plans {
  1319. if let Some(q) = opt_trim(p.sub_account_quota.as_ref()).and_then(|s| s.trim().parse::<i64>().ok()) {
  1320. quota_of_plan.insert(p.plan_id.clone(), q);
  1321. }
  1322. }
  1323. let pairs: Vec<(&str, &str)> = rows
  1324. .iter()
  1325. .filter(|r| IN_USE_STATUS.contains(&r.status.as_str()))
  1326. .filter_map(|r| {
  1327. r.plan_id
  1328. .as_deref()
  1329. .map(|pid| (r.customer_id.as_str(), pid))
  1330. })
  1331. .collect();
  1332. let sums = in_use_quota_sum_batch(&[customer_id], &pairs, &quota_of_plan)?;
  1333. Ok(sums.get(customer_id).copied().unwrap_or(0))
  1334. }
  1335. pub(crate) async fn customer_quota(state: &AppState, customer_id: &str) -> Result<i64, BosError> {
  1336. let mut p = Params::default();
  1337. let c = p.push(Value::String(customer_id.to_string()));
  1338. let sql = format!("SELECT c.quota_cents AS v FROM customer c WHERE c.customer_id = {c}::text");
  1339. Ok(state
  1340. .db
  1341. .query_one::<IdRow>(&sql, p.values())
  1342. .await?
  1343. .map(|r| r.v.trim().parse::<i64>().unwrap_or(0))
  1344. .unwrap_or(0))
  1345. }
  1346. /// 额度对齐语句(§5.7 第 3/6 步:与库里现值不符 ⇒ 以应占额度为准修正)。
  1347. pub(crate) fn quota_stmt(customer_id: &str, target: i64) -> DmlStatement {
  1348. let mut p = Params::default();
  1349. let c = p.push(Value::String(customer_id.to_string()));
  1350. let q = p.push(Value::from(target));
  1351. DmlStatement::new(
  1352. format!(
  1353. "UPDATE customer SET quota_cents = {q}::bigint, updated_at = NOW() WHERE customer_id = {c}::text"
  1354. ),
  1355. p.values().to_vec(),
  1356. )
  1357. }
  1358. /// 额度调整的**业务变更历史**(订单§5.5/客户§2.2:`customer_field_history(field_key='quota')`
  1359. /// 写前后额度;与审计同事务双写、口径不互替)。
  1360. ///
  1361. /// 存在理由(TC-CU-53 步骤 5):此前额度只改 `customer.quota_cents`,客户「归属变更」页
  1362. /// 看不到这次调整,审计也只有订单动作 ⇒ 额度从 0 变 5 在后置校验里查无实据。
  1363. fn quota_history_stmt(customer_id: &str, before: i64, after: i64, actor: &str) -> DmlStatement {
  1364. let mut p = Params::default();
  1365. let id = p.push(Value::String(ops::ids::snowflake().to_string()));
  1366. let c = p.push(Value::String(customer_id.to_string()));
  1367. let o = p.push(Value::String(before.to_string()));
  1368. let n = p.push(Value::String(after.to_string()));
  1369. let a = p.push(Value::String(actor.to_string()));
  1370. DmlStatement::new(
  1371. format!(
  1372. "INSERT INTO customer_field_history (id, customer_id, field_key, old_display, \
  1373. new_display, operator_user_id, changed_at) \
  1374. VALUES ({id}::bigint, {c}::text, 'quota'::text, {o}::text, {n}::text, {a}::text, now())"
  1375. ),
  1376. p.values().to_vec(),
  1377. )
  1378. }
  1379. /// 后置额度对齐结果(`SUB-EFF` 用:订阅§12.1.3 `C44`)。
  1380. pub(crate) struct QuotaAlignOutcome {
  1381. /// `(customer_id, 对齐前, 对齐后)`——只记真正发生写入的客户。
  1382. pub updated: Vec<(String, i64, i64)>,
  1383. /// `(customer_id, 失败原因)`——只失败该客户,其余客户继续。
  1384. pub failed: Vec<(String, String)>,
  1385. }
  1386. /// `SUB-EFF` 后置额度对齐:按客户重算 `customer.quota_cents` 目标值(订阅§5.5/§12.1.3)。
  1387. ///
  1388. /// 入参是**候选集命中的客户**,不是「实际翻转成功」的客户:翻转已提交而对齐失败时,
  1389. /// 下一轮 `changed=0` 仍需重算,否则额度永远偏高且无报错。
  1390. ///
  1391. /// 求和唯一实现=[`in_use_quota_sum_batch`];本函数不自己数订阅、不自己算缺口。
  1392. /// 逐客户调用(⛔ 整批一把),一个客户缺档位额度只失败该客户。
  1393. pub(crate) async fn align_quota_for_customers(
  1394. state: &AppState,
  1395. customer_ids: &[String],
  1396. ) -> Result<QuotaAlignOutcome, BosError> {
  1397. let mut out = QuotaAlignOutcome {
  1398. updated: Vec::new(),
  1399. failed: Vec::new(),
  1400. };
  1401. if customer_ids.is_empty() {
  1402. return Ok(out);
  1403. }
  1404. // 1) 在册在用订阅(额度计入 pending 与 active)+引用档位
  1405. let mut p = Params::default();
  1406. let in_c = push_in(&mut p, "s.customer_id", customer_ids, "text");
  1407. let in_s: Vec<String> = IN_USE_STATUS.iter().map(|s| s.to_string()).collect();
  1408. let in_s = push_in(&mut p, "s.status", &in_s, "text");
  1409. let sql = format!(
  1410. "SELECT s.customer_id, s.plan_id, s.subscription_id, s.quota_slots FROM subscription s \
  1411. WHERE {in_c} AND {in_s} AND s.plan_id IS NOT NULL"
  1412. );
  1413. #[derive(Deserialize)]
  1414. struct SubPlanRow {
  1415. #[serde(deserialize_with = "de::as_string")]
  1416. customer_id: String,
  1417. #[serde(deserialize_with = "de::as_string")]
  1418. plan_id: String,
  1419. #[serde(deserialize_with = "de::as_string")]
  1420. subscription_id: String,
  1421. #[serde(deserialize_with = "de::as_string")]
  1422. quota_slots: String,
  1423. }
  1424. let sub_rows = state.db.query_all::<SubPlanRow>(&sql, p.values()).await?;
  1425. // 2) 档位额度快照(缺列/取不到=该客户失败,⛔ 回落成 0)
  1426. let plan_ids: Vec<String> = sub_rows
  1427. .iter()
  1428. .map(|r| r.plan_id.clone())
  1429. .collect::<HashSet<_>>()
  1430. .into_iter()
  1431. .collect();
  1432. let mut quota_of_plan: HashMap<String, i64> = HashMap::new();
  1433. if !plan_ids.is_empty() {
  1434. let mut pp = Params::default();
  1435. let in_p = push_in(&mut pp, "p.plan_id", &plan_ids, "text");
  1436. let psql = format!(
  1437. "SELECT p.plan_id, p.sub_account_quota FROM catalog_plan p WHERE {in_p}"
  1438. );
  1439. #[derive(Deserialize)]
  1440. struct PlanQuotaRow {
  1441. #[serde(deserialize_with = "de::as_string")]
  1442. plan_id: String,
  1443. #[serde(deserialize_with = "de::as_opt_string")]
  1444. sub_account_quota: Option<String>,
  1445. }
  1446. for row in state.db.query_all::<PlanQuotaRow>(&psql, pp.values()).await? {
  1447. if let Some(q) = opt_trim(row.sub_account_quota.as_ref()).and_then(|v| v.trim().parse::<i64>().ok()) {
  1448. quota_of_plan.insert(row.plan_id, q);
  1449. }
  1450. }
  1451. }
  1452. // 3) 逐客户:现算目标 → 与库值不符才写
  1453. for cid in customer_ids {
  1454. let pairs: Vec<(&str, &str)> = sub_rows
  1455. .iter()
  1456. .filter(|r| r.customer_id == *cid)
  1457. .map(|r| (r.customer_id.as_str(), r.plan_id.as_str()))
  1458. .collect();
  1459. let target = match in_use_quota_sum_batch(&[cid.as_str()], &pairs, &quota_of_plan) {
  1460. Ok(mut m) => m.remove(cid.as_str()).unwrap_or(0),
  1461. Err(e) => {
  1462. out.failed.push((cid.clone(), e.to_string()));
  1463. continue;
  1464. }
  1465. };
  1466. let before = match customer_quota(state, cid).await {
  1467. Ok(v) => v,
  1468. Err(e) => {
  1469. out.failed.push((cid.clone(), e.to_string()));
  1470. continue;
  1471. }
  1472. };
  1473. // D-41(需求§4.2)+M4:席位按**订阅**补建(同一客户多份订阅各管各的席位包)。
  1474. // ⛔ 只在「额度发生变化」时才补(主账号晚于订阅开通、上一轮补建失败的订阅,都靠这里
  1475. // 在后续轮次收敛),且**只补不删**(缩减侧只记说明)。失败⛔ 影响额度结论。
  1476. for r in sub_rows.iter().filter(|r| r.customer_id == *cid) {
  1477. let t = r.quota_slots.trim().parse::<i64>().unwrap_or(0);
  1478. let seats = super::sub_provision::align_seats_of(state, &r.subscription_id, t).await;
  1479. if let Some(reason) = &seats.failed {
  1480. out.failed.push((
  1481. cid.clone(),
  1482. format!("订阅 {} 分账号补建:{reason}", r.subscription_id),
  1483. ));
  1484. }
  1485. }
  1486. if before == target {
  1487. continue;
  1488. }
  1489. let stmt = quota_stmt(cid, target);
  1490. match state.db.dml(&stmt.sql, &stmt.params).await {
  1491. Ok(1) => out.updated.push((cid.clone(), before, target)),
  1492. Ok(n) => out.failed.push((
  1493. cid.clone(),
  1494. format!("客户额度对齐命中 {n} 行(≠ 1),按失败记账等下一轮收敛"),
  1495. )),
  1496. Err(e) => out.failed.push((cid.clone(), e.to_string())),
  1497. }
  1498. }
  1499. Ok(out)
  1500. }
  1501. /// 组装新订阅 INSERT 的列与占位值(无条件/条件插共用)。
  1502. fn insert_cols_vals(v: &NewValues, p: &mut Params) -> (Vec<&'static str>, Vec<String>) {
  1503. let ph = |p: &mut Params, val: Value, cast: &str| -> String {
  1504. let s = p.push(val);
  1505. if cast.is_empty() {
  1506. s
  1507. } else {
  1508. format!("{s}::{cast}")
  1509. }
  1510. };
  1511. let mut cols: Vec<&str> = vec![
  1512. "subscription_id",
  1513. "customer_id",
  1514. "status",
  1515. "plan_id",
  1516. "plan_name",
  1517. "plan_kind",
  1518. "plan_owner_customer_id",
  1519. "plan_family",
  1520. "sub_mode",
  1521. "line_exits",
  1522. "line_exit_key",
  1523. "term",
  1524. "start_date",
  1525. "end_date",
  1526. "annual_price_cents",
  1527. "monthly_settle_cents",
  1528. "quota_slots",
  1529. "quantity",
  1530. ];
  1531. let mut vals: Vec<String> = vec![
  1532. ph(p, Value::String(v.subscription_id.clone()), "text"),
  1533. ph(p, Value::String(v.customer_id.clone()), "text"),
  1534. ph(p, Value::String(v.status.clone()), "text"),
  1535. ph(p, Value::String(v.plan_id.clone()), "text"),
  1536. ph(p, Value::String(v.plan_name.clone()), "text"),
  1537. ph(p, Value::String(v.plan_kind.clone()), "text"),
  1538. ph(
  1539. p,
  1540. v.plan_owner_customer_id.clone().map(Value::String).unwrap_or(Value::Null),
  1541. "text",
  1542. ),
  1543. ph(p, Value::String(v.plan_family.clone()), "text"),
  1544. ph(p, v.sub_mode.clone().map(Value::String).unwrap_or(Value::Null), "text"),
  1545. ph(p, v.line_exits.clone(), "text::jsonb"),
  1546. ph(p, Value::String(v.line_exit_key.clone()), "text"),
  1547. ph(p, Value::String(v.term.clone()), "text"),
  1548. ph(p, Value::String(v.start_date.clone()), "date"),
  1549. ph(p, Value::String(v.end_date.clone()), "date"),
  1550. ph(p, Value::from(v.annual_price_cents), "bigint"),
  1551. ph(p, Value::from(v.monthly_settle_cents), "bigint"),
  1552. ph(p, Value::from(v.quota_slots), "int"),
  1553. ph(p, Value::from(v.quantity), "int"),
  1554. ];
  1555. if let Some(cid) = v.contract_id.as_ref() {
  1556. cols.push("contract_id");
  1557. vals.push(ph(p, Value::String(cid.clone()), "text"));
  1558. }
  1559. if let Some(iid) = v.contract_item_id.as_ref() {
  1560. cols.push("contract_item_id");
  1561. vals.push(ph(p, Value::String(iid.clone()), "text"));
  1562. }
  1563. if let Some(t) = v.trial_months {
  1564. cols.push("trial_months");
  1565. vals.push(ph(p, Value::from(t), "int"));
  1566. }
  1567. if let Some(d) = v.discount_monthly_cents {
  1568. cols.push("discount_monthly_cents");
  1569. vals.push(ph(p, Value::from(d), "bigint"));
  1570. }
  1571. if let Some(rid) = v.replaces_subscription_id.as_ref() {
  1572. cols.push("replaces_subscription_id");
  1573. vals.push(ph(p, Value::String(rid.clone()), "text"));
  1574. }
  1575. if let Some(pid) = v.parent_subscription_id.as_ref() {
  1576. cols.push("parent_subscription_id");
  1577. vals.push(ph(p, Value::String(pid.clone()), "text"));
  1578. }
  1579. (cols, vals)
  1580. }
  1581. /// 新订阅行 INSERT(六项快照+派生价格;`order_no`/`actual_opened_at` 由工单竣工回传,本轮留空)。
  1582. pub(crate) fn insert_stmt(v: &NewValues) -> DmlStatement {
  1583. let mut p = Params::default();
  1584. let (cols, vals) = insert_cols_vals(v, &mut p);
  1585. DmlStatement::new(
  1586. format!(
  1587. "INSERT INTO subscription ({}) VALUES ({})",
  1588. cols.join(", "),
  1589. vals.join(", ")
  1590. ),
  1591. p.values().to_vec(),
  1592. )
  1593. }
  1594. /// 升降配替换专用:仅当截原已落地(原行 `expired` 且 `end_date=prev_end`)才插入新订阅。
  1595. ///
  1596. /// UDS 短批原子提交但**不因前句 0 行中止**(见 `uds.rs`);无条件 INSERT 会在错 `row_version`
  1597. /// 时仍落新行(D-03)。条件插与工单侧「条件写+条件插」同法——截原失败 ⇒ INSERT 0 行。
  1598. pub(crate) fn insert_replacement_stmt(v: &NewValues, orig_id: &str, prev_end: &str) -> DmlStatement {
  1599. let mut p = Params::default();
  1600. let (cols, vals) = insert_cols_vals(v, &mut p);
  1601. let orig = p.push(Value::String(orig_id.to_string()));
  1602. let cust = p.push(Value::String(v.customer_id.clone()));
  1603. let prev = p.push(Value::String(prev_end.to_string()));
  1604. DmlStatement::new(
  1605. format!(
  1606. "INSERT INTO subscription ({}) SELECT {} WHERE EXISTS (\
  1607. SELECT 1 FROM subscription s \
  1608. WHERE s.subscription_id = {orig}::text \
  1609. AND s.customer_id = {cust}::text \
  1610. AND s.status = 'expired' \
  1611. AND s.end_date = {prev}::date)",
  1612. cols.join(", "),
  1613. vals.join(", ")
  1614. ),
  1615. p.values().to_vec(),
  1616. )
  1617. }
  1618. /// 首次引用打点(§5.2 第 4 步:同事务打点=引用冻结的生效点,⛔ 提交后异步补写)。
  1619. ///
  1620. /// ⚠️ 写侧影响行数恒为 1:早期写的是 `… WHERE plan_id = $1 AND first_referred_at IS NULL`,
  1621. /// 同一档位被**第二份**订阅引用时该语句命中 0 行,[`assert_batch`] 便判「打点=0(期望 1)」
  1622. /// 并回 `KLT-S20007`——而短批已原子提交(新订阅早已落库),调用方看到失败却查得到数据。
  1623. /// ⇒ 用 `COALESCE(first_referred_at, NOW())`:已打点的档位写回原值(⛔ 追溯改首次引用时间),
  1624. /// 命中行数恒为 1,语义仍是「首次引用时刻」。
  1625. pub(crate) fn first_referred_stmt(plan_id: &str) -> DmlStatement {
  1626. let mut p = Params::default();
  1627. let a = p.push(Value::String(plan_id.to_string()));
  1628. DmlStatement::new(
  1629. format!(
  1630. "UPDATE catalog_plan SET first_referred_at = COALESCE(first_referred_at, NOW()) \
  1631. WHERE plan_id = {a}::text"
  1632. ),
  1633. p.values().to_vec(),
  1634. )
  1635. }
  1636. /// 待写入的新订阅行(已折算完全部派生值)。
  1637. #[derive(Clone)]
  1638. pub(crate) struct NewValues {
  1639. /// 服务端发号(`SUB-{6位}`);[`insert_stmt`] 的 `subscription_id` 列靠它落库。
  1640. pub(crate) subscription_id: String,
  1641. pub(crate) customer_id: String,
  1642. pub(crate) status: String,
  1643. pub(crate) plan_id: String,
  1644. pub(crate) plan_name: String,
  1645. pub(crate) plan_kind: String,
  1646. pub(crate) plan_owner_customer_id: Option<String>,
  1647. pub(crate) plan_family: String,
  1648. /// 历史列:三分类收敛后新行恒 `None`(I6 停用,不再派生订阅方式)。
  1649. pub(crate) sub_mode: Option<String>,
  1650. pub(crate) line_exits: Value,
  1651. pub(crate) line_exit_key: String,
  1652. pub(crate) term: String,
  1653. pub(crate) start_date: String,
  1654. pub(crate) end_date: String,
  1655. pub(crate) annual_price_cents: i64,
  1656. pub(crate) monthly_settle_cents: i64,
  1657. pub(crate) quota_slots: i64,
  1658. /// 订阅份数(2026-11-17):可叠加档可 > 1,其余恒 1。
  1659. pub(crate) quantity: i64,
  1660. pub(crate) contract_id: Option<String>,
  1661. pub(crate) contract_item_id: Option<String>,
  1662. pub(crate) trial_months: Option<i64>,
  1663. pub(crate) discount_monthly_cents: Option<i64>,
  1664. pub(crate) replaces_subscription_id: Option<String>,
  1665. /// 附加订阅的父订阅(D-2/D-9):`link` 恒空;`addon` 必填(库上 `ck_sub_parent` 兜底)。
  1666. pub(crate) parent_subscription_id: Option<String>,
  1667. }
  1668. /// 发号(`SUB-000123`,与 customer/import_batch 的发号器同一张表)。
  1669. pub(crate) async fn new_subscription_id(state: &AppState) -> Result<String, BosError> {
  1670. let year = chrono::Local::now()
  1671. .format("%Y")
  1672. .to_string()
  1673. .parse::<i32>()
  1674. .map_err(|e| BosError::internal(format!("取当年年份失败:{e}")))?;
  1675. let n = next_seq(state.db.as_ref(), "subscription", "subscription", year).await?;
  1676. Ok(format!("SUB-{n:06}"))
  1677. }
  1678. /// 六步短批的事后自检(UDS ⛔ 批内条件中止 ⇒ 只能事后核影响行数并如实点名)。
  1679. pub(crate) fn assert_batch(results: &[bos_platform::clients::uds::DmlStatementResult], want: &[(&str, u64)]) -> Result<(), BosError> {
  1680. let hit = |i: usize| results.get(i).and_then(|r| r.affected_rows).unwrap_or(0);
  1681. let mut bad: Vec<String> = Vec::new();
  1682. for (i, (label, n)) in want.iter().enumerate() {
  1683. if hit(i) != *n {
  1684. bad.push(format!("{label}={}(期望 {n})", hit(i)));
  1685. }
  1686. }
  1687. if bad.is_empty() {
  1688. return Ok(());
  1689. }
  1690. Err(BosError::internal(format!(
  1691. "写侧短批影响行数异常:{};整批已原子提交,须人工核对",
  1692. bad.join(";")
  1693. )))
  1694. }
  1695. /// 写入后的统一回读出参。
  1696. async fn row_out(
  1697. state: &AppState,
  1698. sub_id: &str,
  1699. op: &str,
  1700. notes: Vec<String>,
  1701. extra: Value,
  1702. ) -> Result<Value, BosError> {
  1703. let mut p = Params::default();
  1704. let s = p.push(Value::String(sub_id.to_string()));
  1705. let sql = format!("{SELECT_COLS} FROM subscription s WHERE s.subscription_id = {s}::text");
  1706. let r = state
  1707. .db
  1708. .query_one::<SubRow>(&sql, p.values())
  1709. .await?
  1710. .ok_or_else(|| {
  1711. BosError::internal(format!("写入后回读未在册:订阅 {sub_id}(短批已提交,须人工核对)"))
  1712. })?;
  1713. let names = pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &[r.customer_id.clone()]).await?;
  1714. let contract_no = match opt_trim(r.contract_id.as_ref()) {
  1715. Some(cid) => contract_row(state, cid)
  1716. .await?
  1717. .map(|c| opt_trim(c.external_no.as_ref()).unwrap_or(c.contract_no.as_str()).to_string()),
  1718. None => None,
  1719. };
  1720. let t = today();
  1721. let mut v = to_json(
  1722. &r,
  1723. names.get(&r.customer_id).and_then(|x| x.first()).map(String::as_str),
  1724. contract_no.as_deref(),
  1725. &t,
  1726. );
  1727. v["op"] = json!(op);
  1728. v["notes"] = json!(notes);
  1729. v["columns_pending"] = json!(COLUMNS_PENDING);
  1730. if let Some(obj) = extra.as_object() {
  1731. for (k, val) in obj {
  1732. v[k.clone()] = val.clone();
  1733. }
  1734. }
  1735. Ok(v)
  1736. }
  1737. async fn row_out_resp(state: &AppState, sub_id: &str, op: &str, notes: Vec<String>, extra: Value) -> Response {
  1738. match row_out(state, sub_id, op, notes, extra).await {
  1739. Ok(v) => json_ok(v),
  1740. Err(e) => json_err(e),
  1741. }
  1742. }
  1743. // ───────────────────────── 写侧:新订 ─────────────────────────
  1744. /// 附加订阅的父订阅解析(D-2/D-9)。
  1745. ///
  1746. /// 两条来源,按 `item_mode` 分:
  1747. /// 1. `increment`(增量合同)⇒ 条目自带的 `ref_subscription_id`(可属**另一份合同**);
  1748. /// 2. 普通附加条目 ⇒ `serves_item_id` 指向本合同里的 `link` 条目,再找该条目落成的 `link` 订阅
  1749. /// (由台账先建;本合同可能还没建,则本条报错,而不是建一条无父的附加订阅)。
  1750. ///
  1751. /// 三条硬口径(与库层 `ck_sub_parent` 互补):同客户 ∧ 父为 `link` ∧ 父**在期**
  1752. /// (`status IN ('pending','active')` ∧ 未过结束日)。⛔ 校验「父子同合同」——D-9 明确父可跨合同。
  1753. async fn resolve_parent_sub(
  1754. state: &AppState,
  1755. customer_id: &str,
  1756. item: Option<&ItemRow>,
  1757. items: &[ItemRow],
  1758. today: &str,
  1759. ) -> Result<String, BosError> {
  1760. #[derive(Deserialize)]
  1761. struct P {
  1762. #[serde(deserialize_with = "de::as_string")]
  1763. subscription_id: String,
  1764. #[serde(default, deserialize_with = "de::as_opt_string")]
  1765. family: Option<String>,
  1766. #[serde(default, deserialize_with = "de::as_opt_string")]
  1767. status: Option<String>,
  1768. #[serde(default, deserialize_with = "de::as_opt_string")]
  1769. customer_id: Option<String>,
  1770. #[serde(default, deserialize_with = "de::as_opt_string")]
  1771. end_date: Option<String>,
  1772. }
  1773. let item = item.ok_or_else(|| {
  1774. BosError::klt(
  1775. KltCode::M228,
  1776. "附加订阅必须有父订阅:请求未关联合同条目,无从解析父链路(D-2)",
  1777. )
  1778. })?;
  1779. let mode = opt_trim(item.item_mode.as_ref()).unwrap_or("new");
  1780. let rid = if mode == "increment" {
  1781. opt_trim(item.ref_subscription_id.as_ref())
  1782. .ok_or_else(|| {
  1783. BosError::klt(
  1784. KltCode::M228,
  1785. format!("条目 {} 是增量条目,但未填引用订阅号(D-9)", item.item_id),
  1786. )
  1787. })?
  1788. .to_string()
  1789. } else {
  1790. let pid = opt_trim(item.serves_item_id.as_ref()).ok_or_else(|| {
  1791. BosError::klt(
  1792. KltCode::M228,
  1793. format!("附加条目 {} 未选父条目(D-7),无法确定父订阅", item.item_id),
  1794. )
  1795. })?;
  1796. if !items.iter().any(|i| i.item_id == pid) {
  1797. return Err(BosError::klt(
  1798. KltCode::M228,
  1799. format!("附加条目 {} 的父条目 {pid} 不在本合同内", item.item_id),
  1800. ));
  1801. }
  1802. // 父条目落成的 `link` 订阅(可能有多条,取结束日最晚的一条在期行)。
  1803. let sql = "SELECT subscription_id::text AS subscription_id FROM subscription \
  1804. WHERE customer_id = $1::text AND contract_item_id = $2::text \
  1805. AND plan_family = 'link' AND status IN ('pending', 'active') \
  1806. ORDER BY end_date DESC NULLS LAST LIMIT 1";
  1807. let hit = state
  1808. .db
  1809. .query_one::<P>(
  1810. sql,
  1811. &[
  1812. Value::String(customer_id.to_string()),
  1813. Value::String(pid.to_string()),
  1814. ],
  1815. )
  1816. .await?;
  1817. let Some(h) = hit else {
  1818. return Err(BosError::klt(
  1819. KltCode::M228,
  1820. format!("父条目 {pid} 还没有对应的跨境链路订阅:请先建父链路订阅,再建附加订阅(D-2)"),
  1821. ));
  1822. };
  1823. h.subscription_id
  1824. };
  1825. let row = state
  1826. .db
  1827. .query_one::<P>(
  1828. "SELECT subscription_id::text AS subscription_id, coalesce(plan_family, '')::text AS family, \
  1829. coalesce(status, '')::text AS status, coalesce(customer_id, '')::text AS customer_id, \
  1830. coalesce(end_date::text, '')::text AS end_date FROM subscription \
  1831. WHERE subscription_id = $1::text LIMIT 1",
  1832. &[Value::String(rid.clone())],
  1833. )
  1834. .await?
  1835. .ok_or_else(|| BosError::klt(KltCode::M228, format!("父订阅 {rid} 不存在(D-9)")))?;
  1836. if row.customer_id.as_deref() != Some(customer_id) {
  1837. return Err(BosError::klt(
  1838. KltCode::M228,
  1839. format!(
  1840. "父订阅 {rid} 属客户 {},与本客户不同(D-9)",
  1841. row.customer_id.unwrap_or_default()
  1842. ),
  1843. ));
  1844. }
  1845. if row.family.as_deref() != Some("link") {
  1846. return Err(BosError::klt(
  1847. KltCode::M228,
  1848. format!("父订阅 {rid} 的交付形态不是 link:附加订阅只能挂在跨境链路上(D-9)"),
  1849. ));
  1850. }
  1851. let st = row.status.unwrap_or_default();
  1852. if st != "pending" && st != "active" {
  1853. return Err(BosError::klt(
  1854. KltCode::M228,
  1855. format!("父订阅 {rid} 状态为「{st}」,不在期(D-9)"),
  1856. ));
  1857. }
  1858. if row.end_date.as_deref().is_some_and(|d| !d.is_empty() && d < today) {
  1859. return Err(BosError::klt(
  1860. KltCode::M228,
  1861. format!("父订阅 {rid} 已过结束日,不在期(D-9)"),
  1862. ));
  1863. }
  1864. Ok(rid)
  1865. }
  1866. /// `POST /subscription/create@v1`(§5.2 五步前置校验 + 六步事务)。
  1867. pub async fn create(
  1868. State(state): State<AppState>,
  1869. RequireAuth(auth): RequireAuth,
  1870. DataBody(body): DataBody<SubscriptionCreateReq>,
  1871. ) -> Response {
  1872. if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
  1873. return json_err(e);
  1874. }
  1875. if let Err(e) = reject_read_only(&body.rest, &CREATE_READ_ONLY) {
  1876. return json_err(e);
  1877. }
  1878. // ① 客户(必填)
  1879. let cid = match req_field("customer_id", &body.customer_id) {
  1880. Ok(v) => v,
  1881. Err(e) => return json_err(e),
  1882. };
  1883. // ② 可见性 ⇒ KLT-M221
  1884. let customer_name = match require_customer(&state, &auth, &cid).await {
  1885. Ok(v) => v,
  1886. Err(e) => return json_err(e),
  1887. };
  1888. // ③ 合同与条目
  1889. let pid = match req_field("plan_id", &body.plan_id) {
  1890. Ok(v) => v,
  1891. Err(e) => return json_err(e),
  1892. };
  1893. let contract_id = match body
  1894. .contract_id
  1895. .as_deref()
  1896. .map(str::trim)
  1897. .filter(|s| !s.is_empty())
  1898. {
  1899. Some(v) => v.to_string(),
  1900. None => {
  1901. return json_err(BosError::bad_params(
  1902. "请选择合同编号:订单必须引用该客户已登记且未开通的合同",
  1903. ))
  1904. }
  1905. };
  1906. let contract = match contract_row(&state, &contract_id).await {
  1907. Ok(Some(c)) => c,
  1908. Ok(None) => {
  1909. return json_err(BosError::klt(
  1910. KltCode::M222,
  1911. format!("载荷里的合同 {contract_id} 不在册,本客户没有可承接的「未开通」合同"),
  1912. ))
  1913. }
  1914. Err(e) => return json_err(e),
  1915. };
  1916. if contract.customer_id != cid {
  1917. return json_err(BosError::klt(
  1918. KltCode::M221,
  1919. format!(
  1920. "载荷里的合同 {contract_id} 归属客户 {},与本订阅客户 {cid} 不同(I12b)",
  1921. contract.customer_id
  1922. ),
  1923. ));
  1924. }
  1925. if let Err(e) = check_i12b_same_customer(Some(&contract.customer_id), &cid) {
  1926. return json_err(e);
  1927. }
  1928. match opened_map_for(&state, std::slice::from_ref(&contract)).await {
  1929. Ok(m) => match m.get(&contract_id) {
  1930. Some(Opened::Opened) => {
  1931. return json_err(BosError::klt(
  1932. KltCode::M223,
  1933. format!("合同 {contract_id} 已开通,不再新增订阅(补录走合同侧「变更重开」)"),
  1934. ))
  1935. }
  1936. Some(Opened::NotOpened) => {}
  1937. None => {
  1938. return json_err(BosError::klt(
  1939. KltCode::S406,
  1940. format!("合同 {contract_id} 的开通态不可判定(不当成未开通放行)"),
  1941. ))
  1942. }
  1943. },
  1944. Err(e) => return json_err(e),
  1945. }
  1946. let item_id = opt_trim(body.contract_item_id.as_ref()).map(str::to_string);
  1947. let items = match items_of_contracts(&state, &[contract_id.clone()]).await {
  1948. Ok(v) => v,
  1949. Err(e) => return json_err(e),
  1950. };
  1951. let item = match item_id.as_ref() {
  1952. Some(iid) => match items.iter().find(|i| &i.item_id == iid) {
  1953. Some(i) => Some(i),
  1954. None => {
  1955. return json_err(BosError::klt(
  1956. KltCode::M228,
  1957. format!("条目 {iid} 不是合同 {contract_id} 的服务构成条目(档位不可选)"),
  1958. ))
  1959. }
  1960. },
  1961. // 合同内一条匹配条目都没有时合同仍可选,出口由操作人在合同内任选 ⇒ 本轮允许空(§5.2 末段)。
  1962. None => None,
  1963. };
  1964. if let Some(i) = item {
  1965. if let Some(ip) = opt_trim(i.plan_id.as_ref()) {
  1966. if ip != pid {
  1967. return json_err(BosError::klt(
  1968. KltCode::M228,
  1969. format!("条目 {} 关联档位 {ip},与所选档位 {pid} 不匹配", i.item_id),
  1970. ));
  1971. }
  1972. }
  1973. }
  1974. let plan = match plan_row(&state, &pid).await {
  1975. Ok(Some(p)) => p,
  1976. Ok(None) => {
  1977. return json_err(BosError::klt(
  1978. KltCode::M228,
  1979. format!("档位 {pid} 不在册,档位不可选"),
  1980. ))
  1981. }
  1982. Err(e) => return json_err(e),
  1983. };
  1984. let t = today();
  1985. let pr = plan.to_ref();
  1986. let (selectable, unavail) = plan_selectability(&pr, &cid);
  1987. if !selectable {
  1988. return json_err(BosError::klt(
  1989. KltCode::M228,
  1990. format!(
  1991. "档位不可选:{}",
  1992. unavail.unwrap_or_else(|| "未指明原因".to_string())
  1993. ),
  1994. ));
  1995. }
  1996. if let Err(e) = check_plan_available(Some(&pr), &cid) {
  1997. return json_err(e);
  1998. }
  1999. // I12b 已在上方按**合同**判过(合同与客户同属);档位侧只需要「自定义档归属本客户」
  2000. // ——该判据在 [`check_plan_available`] 内(固定档 `owner_customer_id` 为空属正常,
  2001. // ⛔ 拿它当 I12b 的输入:固定档会被误判成「合同不存在」)。
  2002. let exits = match derive_exits(item, &plan) {
  2003. Ok(v) => v,
  2004. Err(e) => return json_err(e),
  2005. };
  2006. let factor_map = match super::line_exit::price_factor_map(state.db.as_ref()).await {
  2007. Ok(v) => v,
  2008. Err(e) => return json_err(e),
  2009. };
  2010. let price_factor_scaled = factor_scaled_for_exits(&factor_map, &exits);
  2011. // ④ 价格与周期(全部服务端派生;年价/月标准先乘出口系数)
  2012. let period = match derive_period(
  2013. &plan,
  2014. body.term.as_ref(),
  2015. body.start_date.as_ref(),
  2016. opt_trim(contract.end_date.as_ref()),
  2017. &t,
  2018. price_factor_scaled,
  2019. ) {
  2020. Ok(v) => v,
  2021. Err(e) => return json_err(e),
  2022. };
  2023. let family = match family_of(body.plan_family.as_ref(), &plan) {
  2024. Ok(v) => v,
  2025. Err(e) => return json_err(e),
  2026. };
  2027. // ⑤ 父订阅(D-2/D-9):附加订阅必挂一条**在期链路**,父可属另一份合同。
  2028. // `increment` 条目直接引用既有链路订阅;普通附加条目走它在本合同里的父条目 →
  2029. // 父条目对应的 `link` 订阅(由台账先建)。`link` 恒无父(库上 `ck_sub_parent` 兜底)。
  2030. let parent_subscription_id = match family {
  2031. PlanFamily::Addon => match resolve_parent_sub(&state, &cid, item, &items, &t).await {
  2032. Ok(v) => Some(v),
  2033. Err(e) => return json_err(e),
  2034. },
  2035. PlanFamily::Link => None,
  2036. };
  2037. if let Err(e) = check_i13_trial_months(body.trial_months, body.discount_monthly_cents) {
  2038. return json_err(e);
  2039. }
  2040. // 份数(D-8 `ck_sub_qty`):`link` 恒 1(一条链路=一份),`addon` 1~9999。
  2041. let quantity = match body.quantity {
  2042. None => 1,
  2043. Some(q) => q,
  2044. };
  2045. if !family.quantity_ok(quantity) {
  2046. return json_err(BosError::bad_params(format!(
  2047. "档位 {} 的交付形态为「{}」,份数必须是{}(收到 {quantity})",
  2048. plan.plan_id,
  2049. family.as_str(),
  2050. if family == PlanFamily::Link { " 1" } else { " 1~9999" }
  2051. )));
  2052. }
  2053. let id = match new_subscription_id(&state).await {
  2054. Ok(v) => v,
  2055. Err(e) => return json_err(e),
  2056. };
  2057. let nv = NewValues {
  2058. subscription_id: id.clone(),
  2059. customer_id: cid.clone(), status: subscription_status_of(&period.start, &period.end, &t).as_str().to_string(),
  2060. plan_id: plan.plan_id.clone(),
  2061. plan_name: plan.plan_name.clone(),
  2062. plan_kind: plan.plan_kind.clone(),
  2063. plan_owner_customer_id: opt_trim(plan.customer_id.as_ref()).map(str::to_string),
  2064. plan_family: family.as_str().to_string(),
  2065. sub_mode: None,
  2066. line_exits: Value::Array(exits.line_exits.iter().cloned().map(Value::String).collect()),
  2067. line_exit_key: exits.line_exit_key.clone(),
  2068. term: period.term.clone(),
  2069. start_date: period.start.clone(),
  2070. end_date: period.end.clone(),
  2071. annual_price_cents: period.annual,
  2072. monthly_settle_cents: period.monthly,
  2073. // 额度贡献=档位额度 × 份数(与合同写口同口径),额度求和仍只读 `quota_slots`。
  2074. quota_slots: pr.sub_account_quota.saturating_mul(quantity),
  2075. quantity,
  2076. contract_id: Some(contract_id.clone()),
  2077. contract_item_id: item_id.clone(),
  2078. trial_months: body.trial_months,
  2079. discount_monthly_cents: body.discount_monthly_cents,
  2080. replaces_subscription_id: None,
  2081. parent_subscription_id: parent_subscription_id.clone(),
  2082. };
  2083. // 额度对齐目标=在册在用行 + 本行
  2084. let mut for_quota = match subs_of_customer(&state, &cid).await {
  2085. Ok(v) => v,
  2086. Err(e) => return json_err(e),
  2087. };
  2088. for_quota.push(SubRowPlaceholder::for_new(&id, &nv));
  2089. let target = match quota_target(&state, &cid, &for_quota).await {
  2090. Ok(v) => v,
  2091. Err(e) => return json_err(e),
  2092. };
  2093. let before = match customer_quota(&state, &cid).await {
  2094. Ok(v) => v,
  2095. Err(e) => return json_err(e),
  2096. };
  2097. // D-08:写库前校验承接团队含即将生成的交付类型,避免订阅成功却静默漏单。
  2098. match ops::handlers::open_gen::predict_delivery_type(state.db.as_ref(), &cid, false).await {
  2099. Ok(tt) => {
  2100. if let Err(e) = ops::handlers::open_gen::assert_team_accepts_type(state.db.as_ref(), &cid, tt).await {
  2101. return json_err(e);
  2102. }
  2103. }
  2104. Err(e) => return json_err(e),
  2105. }
  2106. let mut stmts: Vec<DmlStatement> = Vec::new();
  2107. stmts.push(insert_stmt(&nv));
  2108. stmts.push(first_referred_stmt(&pid));
  2109. if before != target {
  2110. stmts.push(quota_stmt(&cid, target));
  2111. stmts.push(quota_history_stmt(&cid, before, target, &auth.user_id));
  2112. }
  2113. let results = match state.db.dml_batch(&stmts).await {
  2114. Ok(r) => r,
  2115. Err(e) => return json_err(e),
  2116. };
  2117. let mut want: Vec<(&str, u64)> = vec![
  2118. ("新订阅 INSERT", 1),
  2119. ("catalog_plan.first_referred_at 打点", 1),
  2120. ];
  2121. if before != target {
  2122. want.push(("客户额度对齐", 1));
  2123. want.push(("客户额度变更历史", 1));
  2124. }
  2125. if let Err(e) = assert_batch(&results, &want) {
  2126. return json_err(e);
  2127. }
  2128. let mut notes: Vec<String> = vec![
  2129. TICKET_UNCONFIGURED_NOTE.to_string(),
  2130. "order_no/actual_opened_at 由开户工单竣工回传回填,本轮新建留空(§5.2)。".to_string(),
  2131. format!(
  2132. "年订阅价格按订阅时长 {} 折算为 {} 分,月结算标准金额={} 分(monthly_settle_of 唯一折算点)。",
  2133. period.term, period.annual, period.monthly
  2134. ),
  2135. ];
  2136. if item_id.is_none() {
  2137. notes.push(
  2138. "本订阅未关联合同条目(合同内无匹配条目时出口按档位自身出口落库),合同开通态一栏显示「—」。"
  2139. .to_string(),
  2140. );
  2141. }
  2142. // 工单§3.2.3 时点 1/2/3+§7.5(D-35/D-42):订阅保存=开户/服务开通工单的唯一宿主,
  2143. // 建单在保存动作内同步完成(作业册§12.1.6 段 1 ⛔ 异步补偿)。工单侧失败⛔ 回滚
  2144. // 已提交的订阅(工单§3.1 第二条),只把原因如实写回 `notes`+`delivery_ticket`(⛔ 静默)。
  2145. let delivery = match auth.user_id.trim().parse::<i64>() {
  2146. Ok(actor) => {
  2147. ops::handlers::open_gen::run(
  2148. &state.db,
  2149. &ops::handlers::open_gen::SubTicketInput {
  2150. customer_id: cid.clone(),
  2151. subscription_id: id.clone(),
  2152. // 计划执行日=本订阅的服务开始日(合同开始日/台账填的未来日)。
  2153. start_date: nv.start_date.clone(),
  2154. plan_name: nv.plan_name.clone(),
  2155. line_exits: exits.line_exits.clone(),
  2156. quota_slots: pr.sub_account_quota,
  2157. actor_user_id: actor,
  2158. original: None,
  2159. // 附加订阅(D-2/D-9):父订阅随建单下传,决定并入父单还是只出服务开通单。
  2160. parent_subscription_id: parent_subscription_id.clone(),
  2161. // 订阅台账「新增订阅」没有任何续签来源 ⇒ 无从判定「服务内容未变」。
  2162. service_unchanged: false,
  2163. // D-11:运营商订单号一合同一号,取所挂合同的 `external_no`。
  2164. carrier_order_no: contract.external_no.clone(),
  2165. },
  2166. )
  2167. .await
  2168. }
  2169. Err(_) => ops::handlers::open_gen::GenOutcome::delivery_skipped(format!(
  2170. "当前登录账号 ID 非数字({}),不写入工单的提交人(bigint)⇒ 本次未生成交付工单,\
  2171. 请到工单台人工补发(工单§3.2.3 时点 1/2/3)。",
  2172. auth.user_id
  2173. )),
  2174. };
  2175. notes.push(delivery.note.clone());
  2176. // D-41(需求§4.2/客户册§5.2):订阅保存=额度变更落点,分账号由系统按套餐额度**自动补建**
  2177. // (⛔ 手工新增)。与交付工单同一形态:订阅主档先提交,补建在其后同步执行,失败⛔ 回滚
  2178. // 已提交的订阅,只把原因如实写回 `notes`+审计 `detail_json.sub_accounts`(⛔ 静默)。
  2179. let seats = super::sub_provision::align_seats_of(&state, &id, nv.quota_slots).await;
  2180. notes.push(seats.note());
  2181. // 后置审计 `subscription.create`(08 册 §8.1 CU-17/§8.3):此前该动作在 `bos_audit_log` 里
  2182. // 0 行=D-25。`before_json` 新增时为空;额度前后、两个金额与折算来源、order_no 冻结事实照记。
  2183. let after_view = SubAuditView::of_row(&SubRowPlaceholder::for_new(&id, &nv)).to_json();
  2184. let detail = json!({
  2185. "layout": "multi",
  2186. "plan_id": nv.plan_id,
  2187. "plan_name_snapshot": nv.plan_name,
  2188. "plan_family": nv.plan_family,
  2189. "sub_mode": nv.sub_mode,
  2190. "line_exits": nv.line_exits,
  2191. "line_exit_key": nv.line_exit_key,
  2192. "term": nv.term,
  2193. "start_date": nv.start_date,
  2194. "end_date": nv.end_date,
  2195. "annual_price_cents": nv.annual_price_cents,
  2196. "monthly_settle_cents": nv.monthly_settle_cents,
  2197. "amount_source": "annual 取所选口径价,monthly 由 monthly_settle_of 唯一折算点得出",
  2198. "quota_slots_before": before,
  2199. "quota_slots_target": target,
  2200. "quota_change": {
  2201. "field": "quota_cents",
  2202. "before": before,
  2203. "after": target,
  2204. "written": before != target,
  2205. "history_key": if before != target { Some("quota") } else { None },
  2206. },
  2207. "contract_id": nv.contract_id,
  2208. "contract_item_id": nv.contract_item_id,
  2209. "item_matched": item_id.is_some(),
  2210. "delivery_ticket": delivery.to_json(),
  2211. "sub_accounts": seats.to_json(),
  2212. "order_no_note": "order_no 录入即冻结 ⇒ 新建留空,由开户工单竣工回传回填",
  2213. "replaces_subscription_id": nv.replaces_subscription_id,
  2214. });
  2215. let audit_written = write_sub_audit(
  2216. &state,
  2217. &auth,
  2218. "subscription.create",
  2219. &id,
  2220. None,
  2221. Some(after_view),
  2222. detail,
  2223. )
  2224. .await;
  2225. row_out_resp(
  2226. &state,
  2227. &id,
  2228. "created",
  2229. notes,
  2230. json!({
  2231. "audit_written": audit_written,
  2232. "customer_name": customer_name,
  2233. "delivery_ticket": delivery.to_json(),
  2234. "quota_align": { "before": before, "target": target, "written": before != target },
  2235. "derived": {
  2236. "term": period.term,
  2237. "start_date": period.start,
  2238. "end_date": period.end,
  2239. "annual_price_cents": period.annual,
  2240. "monthly_settle_cents": period.monthly,
  2241. "line_exit_key": exits.line_exit_key,
  2242. "plan_family": family.as_str(),
  2243. },
  2244. }),
  2245. )
  2246. .await
  2247. }
  2248. /// 客户在册且在可见范围内 ⇒ 回客户名;越权或不在册=`KLT-M221`。
  2249. pub(crate) async fn require_customer(
  2250. state: &AppState,
  2251. auth: &bos_scope::AuthContext,
  2252. customer_id: &str,
  2253. ) -> Result<String, BosError> {
  2254. customer_visible(state, auth, customer_id)
  2255. .await?
  2256. .ok_or_else(|| {
  2257. BosError::klt(
  2258. KltCode::M221,
  2259. format!("客户不存在或超出当前账号可见范围:{customer_id}"),
  2260. )
  2261. })
  2262. }
  2263. // ───────────────────────── 写侧:升降配 ─────────────────────────
  2264. /// 原订阅已被换过的次数(`replaces_subscription_id` 唯一 ⇒ ≥1 即⛔ 再换)。
  2265. pub(crate) async fn replacement_count(state: &AppState, origin_id: &str) -> Result<i64, BosError> {
  2266. let mut p = Params::default();
  2267. let a = p.push(Value::String(origin_id.to_string()));
  2268. let sql = format!(
  2269. "SELECT COUNT(1) AS c FROM subscription r WHERE r.replaces_subscription_id = {a}::text"
  2270. );
  2271. Ok(state
  2272. .db
  2273. .query_one::<CountRow>(&sql, p.values())
  2274. .await?
  2275. .map(|r| r.c.trim().parse::<i64>().unwrap_or(0))
  2276. .unwrap_or(0))
  2277. }
  2278. /// `POST /subscription/change@v1`(§5.3)。
  2279. ///
  2280. /// 客户/合同/条目/用途分类全部沿用或跟随新档位(载荷出现即 `11103`);
  2281. /// ⛔ 出口一致性校验(分类与出口均随档位变,拦截等于禁止换分类);I6 照常(`KLT-M224`)。
  2282. pub async fn change(
  2283. State(state): State<AppState>,
  2284. RequireAuth(auth): RequireAuth,
  2285. DataBody(body): DataBody<SubscriptionChangeReq>,
  2286. ) -> Response {
  2287. if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
  2288. return json_err(e);
  2289. }
  2290. if let Err(e) = reject_read_only(&body.rest, &CHANGE_READ_ONLY) {
  2291. return json_err(e);
  2292. }
  2293. let rid = match req_field("replaces_subscription_id", &body.replaces_subscription_id) {
  2294. Ok(v) => v,
  2295. Err(e) => return json_err(e),
  2296. };
  2297. let orig = match scoped_sub(&state, &auth, &rid).await {
  2298. Ok(Some(c)) => c,
  2299. Ok(None) => {
  2300. return json_err(BosError::not_found(format!(
  2301. "原订阅不存在或超出当前账号可见范围:{rid}"
  2302. )))
  2303. }
  2304. Err(e) => return json_err(e),
  2305. };
  2306. let t = today();
  2307. let (key, label, _) = status_display(&orig, &t);
  2308. if key != "pending" && key != "active" {
  2309. return json_err(BosError::bad_params(format!(
  2310. "原订阅 {rid} 状态={label}({key}),不升降配(§5.3)"
  2311. )));
  2312. }
  2313. match replacement_count(&state, &rid).await {
  2314. Ok(0) => {}
  2315. Ok(k) => {
  2316. return json_err(BosError::klt(
  2317. KltCode::M226,
  2318. format!("原订阅 {rid} 已被升降配换过 {k} 次:replaces_subscription_id 至多被指向一次"),
  2319. ))
  2320. }
  2321. Err(e) => return json_err(e),
  2322. }
  2323. let cid = orig.customer_id.clone();
  2324. // 契约 `/subscription/change@v1`:`contract_id` 为必填「新合同」(不得沿用原合同),
  2325. // `contract_item_id` 为新合同条目。缺省时回退到原订阅合同(兼容旧调用与「同合同换档」)。
  2326. if let Some(given) = opt_trim(body.customer_id.as_ref()) {
  2327. if given != cid {
  2328. return json_err(BosError::klt(
  2329. KltCode::M221,
  2330. format!("载荷客户 {given} 与原订阅客户 {cid} 不同:升降配不换客户(§5.3)"),
  2331. ));
  2332. }
  2333. }
  2334. let (contract_id, reused_contract) = match opt_trim(body.contract_id.as_ref()) {
  2335. Some(c) => (c.to_string(), false),
  2336. None => match opt_trim(orig.contract_id.as_ref()) {
  2337. Some(c) => (c.to_string(), true),
  2338. None => {
  2339. return json_err(BosError::klt(
  2340. KltCode::M221,
  2341. format!("原订阅 {rid} 未关联合同,且载荷未给 contract_id:升降配须引用新合同"),
  2342. ))
  2343. }
  2344. },
  2345. };
  2346. let contract = match contract_row(&state, &contract_id).await {
  2347. Ok(Some(c)) => c,
  2348. Ok(None) => {
  2349. return json_err(BosError::klt(
  2350. KltCode::M222,
  2351. format!("载荷里的合同 {contract_id} 不在册,升降配不承接"),
  2352. ))
  2353. }
  2354. Err(e) => return json_err(e),
  2355. };
  2356. if contract.customer_id != cid {
  2357. return json_err(BosError::klt(
  2358. KltCode::M221,
  2359. format!(
  2360. "载荷里的合同 {contract_id} 归属客户 {},与原订阅客户 {cid} 不同(I12b)",
  2361. contract.customer_id
  2362. ),
  2363. ));
  2364. }
  2365. if let Err(e) = check_i12b_same_customer(Some(&contract.customer_id), &cid) {
  2366. return json_err(e);
  2367. }
  2368. let pid = match req_field("plan_id", &body.plan_id) {
  2369. Ok(v) => v,
  2370. Err(e) => return json_err(e),
  2371. };
  2372. let plan = match plan_row(&state, &pid).await {
  2373. Ok(Some(p)) => p,
  2374. Ok(None) => {
  2375. return json_err(BosError::klt(KltCode::M228, format!("新档位 {pid} 不在册,档位不可选")))
  2376. }
  2377. Err(e) => return json_err(e),
  2378. };
  2379. let pr = plan.to_ref();
  2380. if let (_, Some(reason)) = plan_selectability(&pr, &cid) {
  2381. return json_err(BosError::klt(KltCode::M228, format!("档位不可选:{reason}")));
  2382. }
  2383. if let Err(e) = check_plan_available(Some(&pr), &cid) {
  2384. return json_err(e);
  2385. }
  2386. // I12b 的判据是「**合同**与客户同属一个客户」,上面已按 `contract.customer_id` 校验过(§5.3)。
  2387. // 此处⛔ 再拿「**档位**归属客户」过一次 I12b:固定档 `catalog_plan.customer_id` 为空是正常
  2388. // 形态(平台通用档),空归属落进 `None` 分支会被报成「合同不存在」(60005),
  2389. // ⇒ 所有固定档的升降配恒失败(缺陷 D-73)。自定义档的归属约束已由
  2390. // [`plan_selectability`]+[`check_plan_available`](I11:自定义档只能被归属它的客户订阅)覆盖。
  2391. // 条目:载荷给了 `contract_item_id` 就按它取(并校验档位匹配),否则按新档位在合同内反查。
  2392. let items = match items_of_contracts(&state, &[contract_id.clone()]).await {
  2393. Ok(v) => v,
  2394. Err(e) => return json_err(e),
  2395. };
  2396. let item = match opt_trim(body.contract_item_id.as_ref()) {
  2397. Some(iid) => match items.iter().find(|i| i.item_id == iid) {
  2398. Some(i) => {
  2399. let bound = opt_trim(i.plan_id.as_ref());
  2400. if let Some(ip) = bound {
  2401. if ip != pid {
  2402. return json_err(BosError::klt(
  2403. KltCode::M228,
  2404. format!("条目 {iid} 关联档位 {ip},与所选档位 {pid} 不匹配"),
  2405. ));
  2406. }
  2407. }
  2408. Some(i)
  2409. }
  2410. None => {
  2411. return json_err(BosError::klt(
  2412. KltCode::M228,
  2413. format!("条目 {iid} 不是合同 {contract_id} 的服务构成条目(档位不可选)"),
  2414. ))
  2415. }
  2416. },
  2417. None => items.iter().find(|i| opt_trim(i.plan_id.as_ref()) == Some(pid.as_str())),
  2418. };
  2419. // 交付形态只读档位(载荷⛔ 带 plan_family)。
  2420. let family = plan.family();
  2421. if let Err(e) = check_i13_trial_months(body.trial_months, body.discount_monthly_cents) {
  2422. return json_err(e);
  2423. }
  2424. let exits = match derive_exits(item, &plan) {
  2425. Ok(v) => v,
  2426. Err(e) => return json_err(e),
  2427. };
  2428. // I6/额度按**最终态**判一次(§5.3):剔除原订阅、加入新订阅后再复检。
  2429. // 候选集必须**排除被替换的原订阅**:升降配正是「用新行顶掉原行」,原行本就还在库里,
  2430. // ⛔ 把它算进「同分类×同出口已有一份」——旧写法让任何一次升降配都被自己的原行拦下
  2431. // (KLT-M224/60217「请在该行点『升降配』」,而用户点的正是升降配;缺陷 D-74)。
  2432. let existing = match subs_of_customer(&state, &cid).await {
  2433. Ok(v) => v,
  2434. Err(e) => return json_err(e),
  2435. };
  2436. let id = match new_subscription_id(&state).await {
  2437. Ok(v) => v,
  2438. Err(e) => return json_err(e),
  2439. };
  2440. let factor_map = match super::line_exit::price_factor_map(state.db.as_ref()).await {
  2441. Ok(v) => v,
  2442. Err(e) => return json_err(e),
  2443. };
  2444. let exits_for_factor = match derive_exits(item, &plan) {
  2445. Ok(v) => v,
  2446. Err(e) => return json_err(e),
  2447. };
  2448. let pin = super::succession::PlanInput {
  2449. plan: &plan,
  2450. item,
  2451. contract_id: &contract_id,
  2452. contract_end: opt_trim(contract.end_date.as_ref()),
  2453. term: body.term.as_ref(),
  2454. start_date: body.start_date.as_ref(),
  2455. trial_months: body.trial_months,
  2456. discount_monthly_cents: body.discount_monthly_cents,
  2457. row_version: body.row_version,
  2458. // 升降配替换只承接 `link` 订阅(叠加服务随父),故无父。
  2459. parent_subscription_id: None,
  2460. mode: super::succession::MatchMode::FollowPlan,
  2461. price_factor_scaled: factor_scaled_for_exits(&factor_map, &exits_for_factor),
  2462. };
  2463. let planned = match super::succession::plan_change(&state, &cid, &orig, &id, &pin, &t, "").await
  2464. {
  2465. Ok(v) => v,
  2466. Err(e) => return json_err(e),
  2467. };
  2468. let planned_once = std::slice::from_ref(&planned);
  2469. let nv = planned.new.clone();
  2470. let period = planned.period.clone();
  2471. let prev_end = planned.prev_end.clone();
  2472. let same_day_cut = planned.same_day_cut;
  2473. let target =
  2474. match super::succession::quota_target_final(&state, &cid, &existing, planned_once, &[])
  2475. .await
  2476. {
  2477. Ok(v) => v,
  2478. Err(e) => return json_err(e),
  2479. };
  2480. let before = match customer_quota(&state, &cid).await {
  2481. Ok(v) => v,
  2482. Err(e) => return json_err(e),
  2483. };
  2484. // D-08:写库前校验承接团队含即将生成的交付类型。
  2485. let original_delivered = orig
  2486. .actual_opened_at
  2487. .as_deref()
  2488. .is_some_and(|s| !s.trim().is_empty());
  2489. match ops::handlers::open_gen::predict_delivery_type(state.db.as_ref(), &cid, original_delivered)
  2490. .await
  2491. {
  2492. Ok(tt) => {
  2493. if let Err(e) =
  2494. ops::handlers::open_gen::assert_team_accepts_type(state.db.as_ref(), &cid, tt).await
  2495. {
  2496. return json_err(e);
  2497. }
  2498. }
  2499. Err(e) => return json_err(e),
  2500. }
  2501. let mut stmts: Vec<DmlStatement> = super::succession::change_dml(&planned);
  2502. let has_quota = before != target;
  2503. if has_quota {
  2504. stmts.push(quota_stmt(&cid, target));
  2505. }
  2506. // M4:席位先改挂到新订阅(0 行=原订阅本就没有席位,属正常)——放在断言语句之后,
  2507. // ⛔ 计入 `assert_batch` 的期望行数。
  2508. stmts.push(super::succession::seat_migration_stmt(
  2509. &planned.orig.subscription_id,
  2510. &planned.new.subscription_id,
  2511. ));
  2512. // D-2「父替换 ⇒ 子改挂」:附加子订阅的父指针改到新订阅(0 行=原订阅无叠加服务)。
  2513. stmts.push(super::succession::reparent_children_stmt(
  2514. &planned.orig.subscription_id,
  2515. &planned.new.subscription_id,
  2516. ));
  2517. let results = match state.db.dml_batch(&stmts).await {
  2518. Ok(r) => r,
  2519. Err(e) => return json_err(e),
  2520. };
  2521. let mut want: Vec<(&str, u64)> = super::succession::CHANGE_DML_LABELS
  2522. .iter()
  2523. .map(|s| (*s, 1))
  2524. .collect();
  2525. if has_quota {
  2526. want.push(("客户额度对齐", 1));
  2527. }
  2528. if let Err(e) = assert_batch(&results, &want) {
  2529. // ⛔ 把任何行数异常都冒充成「乐观锁冲突」:只有**截原**落空才是 §5.3 的前置不符
  2530. let cut_rows = results.first().and_then(|r| r.affected_rows).unwrap_or(0);
  2531. if cut_rows == 0 {
  2532. return json_err(BosError::klt(
  2533. KltCode::M225,
  2534. format!("承接的原订阅 {rid} 状态已变更(原订阅未能截原),请重新加载该行后再试"),
  2535. ));
  2536. }
  2537. return json_err(e);
  2538. }
  2539. let mut notes: Vec<String> = vec![
  2540. TICKET_UNCONFIGURED_NOTE.to_string(),
  2541. "不做出口一致性校验(§5.3:分类与出口均随档位变,拦截等于禁止换分类),本轮未做该校验。"
  2542. .to_string(),
  2543. format!(
  2544. "年订阅价格按订阅时长 {} 折算为 {} 分,月结算标准金额={} 分;原订阅结束日截到 {prev_end}。",
  2545. period.term, period.annual, period.monthly
  2546. ),
  2547. ];
  2548. if reused_contract {
  2549. notes.push(format!(
  2550. "本轮未给 contract_id,沿用原订阅合同 {contract_id}(契约建议另签新合同后再升降配)。"
  2551. ));
  2552. } else if orig.contract_id.as_deref() != Some(contract_id.as_str()) {
  2553. notes.push(format!(
  2554. "承接合同由 {} 换为 {contract_id}(新订单引用新合同,原合同保留为历史)。",
  2555. orig.contract_id.clone().unwrap_or_else(|| "(空)".to_string())
  2556. ));
  2557. }
  2558. if same_day_cut {
  2559. notes.push(format!(
  2560. "原订阅生效日 {} 不早于新生效日前一日,截原结束日钳到 {prev_end}(同日承接,原订阅保留生效当日)。",
  2561. orig.start_date.clone().unwrap_or_else(|| "(空)".to_string())
  2562. ));
  2563. }
  2564. // 工单§3.2.3 时点 3:升降配=「在用客户新增订阅」⇒ 生成服务开通工单(无开停记录),
  2565. // 与新建同宿主、同形态(P5-D3:此前升降配只写「未接线」提示、0 张工单)。
  2566. let delivery = match auth.user_id.trim().parse::<i64>() {
  2567. Ok(actor) => {
  2568. ops::handlers::open_gen::run(
  2569. &state.db,
  2570. &ops::handlers::open_gen::SubTicketInput {
  2571. customer_id: cid.clone(),
  2572. subscription_id: id.clone(),
  2573. // 升降配的执行日=新订阅的服务开始日(新档位生效日)。
  2574. start_date: period.start.clone(),
  2575. plan_name: nv.plan_name.clone(),
  2576. line_exits: exits.line_exits.clone(),
  2577. quota_slots: pr.sub_account_quota,
  2578. actor_user_id: actor,
  2579. original: Some(super::succession::original_sub(&state, &orig).await),
  2580. parent_subscription_id: None,
  2581. // 台账升降配=服务内容变了。
  2582. service_unchanged: false,
  2583. // D-11:升降配承接的新合同号(号随合同,⛔ 沿用原订阅的冻结号)。
  2584. carrier_order_no: contract.external_no.clone(),
  2585. },
  2586. )
  2587. .await
  2588. }
  2589. Err(_) => ops::handlers::open_gen::GenOutcome::delivery_skipped(format!(
  2590. "当前登录账号 ID 非数字({}),不写入工单的提交人(bigint)⇒ 本次未生成交付工单,\
  2591. 请到工单台人工补发(工单§3.2.3 时点 3)。",
  2592. auth.user_id
  2593. )),
  2594. };
  2595. notes.push(delivery.note.clone());
  2596. // D-41(需求§4.2):升降配=额度变更落点。升配侧按新额度补建席位;降配侧**只补不删**,
  2597. // 超出的席位⛔ 删号(随到期停机转停用),差异如实写回 `notes`+审计 `detail_json.sub_accounts`。
  2598. let seats = super::sub_provision::align_seats_of(&state, &id, nv.quota_slots).await;
  2599. notes.push(seats.note());
  2600. // 后置审计 `subscription.replace`(08 册 §8.1 CU-17/§8.3=`pair` 版式:原订阅 `end_date`
  2601. // 与 `status` 记原值→新值,另记原/新合同编号)。此前升降配全程 0 行审计。
  2602. let before_view = SubAuditView::of_row(&orig).to_json();
  2603. let after_view = SubAuditView::of_row(&SubRowPlaceholder::for_new(&id, &nv)).to_json();
  2604. let detail = json!({
  2605. "layout": "pair",
  2606. "replaces_subscription_id": rid.clone(),
  2607. "origin_contract_id": orig.contract_id.clone(),
  2608. "new_contract_id": contract_id.clone(),
  2609. "old_end_date": { "old": orig.end_date.clone(), "new": prev_end.clone() },
  2610. "old_status": { "old": orig.status.clone(), "new": "expired" },
  2611. "new_plan_id": nv.plan_id.clone(),
  2612. "new_plan_name": nv.plan_name.clone(),
  2613. "line_exits": nv.line_exits.clone(),
  2614. "annual_price_cents": nv.annual_price_cents,
  2615. "monthly_settle_cents": nv.monthly_settle_cents,
  2616. "quota_slots_before": before,
  2617. "quota_slots_target": target,
  2618. "sub_accounts": seats.to_json(),
  2619. "exit_check_note": "不做出口一致性校验(§5.3)⇒ 本轮未做,如实记",
  2620. });
  2621. let audit_written = write_sub_audit(
  2622. &state,
  2623. &auth,
  2624. "subscription.replace",
  2625. &id,
  2626. Some(before_view),
  2627. Some(after_view),
  2628. detail,
  2629. )
  2630. .await;
  2631. row_out_resp(
  2632. &state,
  2633. &id,
  2634. "changed",
  2635. notes,
  2636. json!({
  2637. "audit_written": audit_written,
  2638. "replaces_subscription_id": rid,
  2639. "quota_align": { "before": before, "target": target, "written": before != target },
  2640. "derived": {
  2641. "term": period.term,
  2642. "start_date": period.start,
  2643. "end_date": period.end,
  2644. "annual_price_cents": period.annual,
  2645. "monthly_settle_cents": period.monthly,
  2646. "line_exit_key": exits.line_exit_key,
  2647. "plan_family": family.as_str(),
  2648. "contract_id": contract_id,
  2649. "contract_item_id": nv.contract_item_id,
  2650. },
  2651. }),
  2652. )
  2653. .await
  2654. }
  2655. /// 升降配额度对齐用的行占位(把 [`NewValues`] 折算成一行「将来在册」的订阅行)。
  2656. pub(crate) struct SubRowPlaceholder;
  2657. impl SubRowPlaceholder {
  2658. pub(crate) fn for_new(id: &str, v: &NewValues) -> SubRow {
  2659. SubRow {
  2660. subscription_id: id.to_string(),
  2661. customer_id: v.customer_id.clone(),
  2662. contract_id: v.contract_id.clone(),
  2663. contract_item_id: v.contract_item_id.clone(),
  2664. plan_id: Some(v.plan_id.clone()),
  2665. plan_name: Some(v.plan_name.clone()),
  2666. plan_kind: Some(v.plan_kind.clone()),
  2667. plan_owner_customer_id: v.plan_owner_customer_id.clone(),
  2668. status: v.status.clone(),
  2669. plan_family: Some(v.plan_family.clone()),
  2670. sub_mode: v.sub_mode.clone(),
  2671. line_exits: None,
  2672. line_exit_key: Some(v.line_exit_key.clone()),
  2673. start_date: Some(v.start_date.clone()),
  2674. end_date: Some(v.end_date.clone()),
  2675. term: Some(v.term.clone()),
  2676. trial_months: v.trial_months.map(|x| x.to_string()),
  2677. discount_monthly_cents: v.discount_monthly_cents.map(|x| x.to_string()),
  2678. annual_price_cents: Some(v.annual_price_cents.to_string()),
  2679. monthly_settle_cents: Some(v.monthly_settle_cents.to_string()),
  2680. quota_slots: v.quota_slots.to_string(),
  2681. quantity: v.quantity.to_string(),
  2682. parent_subscription_id: v.parent_subscription_id.clone(),
  2683. replaces_subscription_id: v.replaces_subscription_id.clone(),
  2684. order_no: None,
  2685. actual_opened_at: None,
  2686. early_stopped_at: None,
  2687. effective_date: None,
  2688. expire_date: None,
  2689. created_at: String::new(),
  2690. row_version: String::new(),
  2691. }
  2692. }
  2693. }
  2694. // ═══════════════════════════ §5.7 修改(白名单两列) ═══════════════════════════
  2695. /// 修改载荷:白名单只有 `trial_months` + `discount_monthly_cents`(§5.7)。
  2696. ///
  2697. /// 换套餐/换合同 ⇒ `KLT-M229`(改订走升降配承接或先停用再新开);其余键 ⇒ `11103`
  2698. /// 逐一点名(⛔ 静默忽略=把「改了结束日」当成一次成功的修改)。
  2699. fn reject_update_payload(rest: &Map<String, Value>) -> Result<(), BosError> {
  2700. let m229: Vec<&str> = UPDATE_M229_KEYS
  2701. .iter()
  2702. .copied()
  2703. .filter(|k| rest.contains_key(*k))
  2704. .collect();
  2705. if !m229.is_empty() {
  2706. return Err(BosError::klt(
  2707. KltCode::M229,
  2708. format!(
  2709. "修改不换套餐/换合同({}):改订一律走「升降配承接」或「先服务停用再新开」(§5.7)",
  2710. m229.join("、")
  2711. ),
  2712. ));
  2713. }
  2714. let mut keys: Vec<&str> = rest
  2715. .keys()
  2716. .map(String::as_str)
  2717. .filter(|k| !UPDATE_WHITELIST.contains(k))
  2718. .collect();
  2719. if keys.is_empty() {
  2720. return Ok(());
  2721. }
  2722. keys.sort_unstable();
  2723. Err(BosError::bad_params(format!(
  2724. "修改白名单只有 {},以下键不受理:{}",
  2725. UPDATE_WHITELIST.join("/"),
  2726. keys.join("、")
  2727. )))
  2728. }
  2729. /// `POST /subscription/update@v1`(§5.7)。
  2730. pub async fn update(
  2731. State(state): State<AppState>,
  2732. RequireAuth(auth): RequireAuth,
  2733. DataBody(body): DataBody<SubscriptionUpdateReq>,
  2734. ) -> Response {
  2735. if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
  2736. return json_err(e);
  2737. }
  2738. if let Err(e) = reject_update_payload(&body.rest) {
  2739. return json_err(e);
  2740. }
  2741. let sid = match req_field("subscription_id", &body.subscription_id) {
  2742. Ok(v) => v,
  2743. Err(e) => return json_err(e),
  2744. };
  2745. let r = match scoped_sub(&state, &auth, &sid).await {
  2746. Ok(Some(v)) => v,
  2747. Ok(None) => {
  2748. return json_err(BosError::not_found(format!(
  2749. "订阅不存在或超出当前账号可见范围:{sid}"
  2750. )))
  2751. }
  2752. Err(e) => return json_err(e),
  2753. };
  2754. let t = today();
  2755. let (key, label, _) = status_display(&r, &t);
  2756. if key != "pending" && key != "active" {
  2757. return json_err(BosError::bad_params(format!(
  2758. "订阅 {sid} 状态={label},不修改(§5.7:到期/已替换/已退订只读)"
  2759. )));
  2760. }
  2761. // I13 用**改后**的试用/优惠期组合判(本口只改这两列=唯一能碰 I13 的写入口)
  2762. let cur_trial = as_opt_num(r.trial_months.as_deref()).as_i64();
  2763. let cur_disc = as_opt_num(r.discount_monthly_cents.as_deref()).as_i64();
  2764. let trial = body.trial_months.or(cur_trial);
  2765. let disc = body.discount_monthly_cents.or(cur_disc);
  2766. if let Err(e) = check_i13_trial_months(trial, disc) {
  2767. return json_err(e);
  2768. }
  2769. let mut p = Params::default();
  2770. let set: Vec<String> = vec![
  2771. format!(
  2772. "trial_months = {}::int",
  2773. p.push(trial.map(Value::from).unwrap_or(Value::Null))
  2774. ),
  2775. format!(
  2776. "discount_monthly_cents = {}::bigint",
  2777. p.push(disc.map(Value::from).unwrap_or(Value::Null))
  2778. ),
  2779. "row_version = row_version + 1".to_string(),
  2780. "updated_at = NOW()".to_string(),
  2781. ];
  2782. // 乐观锁:`row_version` 进谓词(UDS ⛔ 行锁能力,条件更新是唯一防线)
  2783. let preds: Vec<String> = vec![
  2784. format!("subscription_id = {}::text", p.push(Value::String(sid.clone()))),
  2785. format!("row_version = {}::int", p.push(Value::from(body.row_version))),
  2786. format!("status = {}::text", p.push(Value::String(r.status.clone()))),
  2787. ];
  2788. let sql = format!(
  2789. "UPDATE subscription SET {} {}",
  2790. set.join(", "),
  2791. p.where_clause(&preds)
  2792. );
  2793. let affected = match state.db.dml(&sql, p.values()).await {
  2794. Ok(v) => v,
  2795. Err(e) => return json_err(e),
  2796. };
  2797. if affected == 0 {
  2798. return json_err(BosError::klt(
  2799. KltCode::S407,
  2800. format!("订阅 {sid} 已被他人改动(row_version 不符),请重新加载后重试(§5.7)"),
  2801. ));
  2802. }
  2803. let notes: Vec<String> = vec![
  2804. format!(
  2805. "本轮修改列={};订阅时长/结束日/两个金额不可改(§5.7)。",
  2806. UPDATE_WHITELIST.join("/")
  2807. ),
  2808. TICKET_UNCONFIGURED_NOTE.to_string(),
  2809. ];
  2810. // 后置审计 `subscription.update`(08 册 §8.1 CU-18/§8.3=`diff` 版式):只记改了哪些列+
  2811. // 原值→新值,并如实记「结束日/两个金额⛔ 经本口改动」。此前编辑订阅 0 行审计=D-25。
  2812. let before_view = SubAuditView::of_row(&r);
  2813. let mut after_view = before_view.clone();
  2814. after_view.trial_months = trial;
  2815. after_view.discount_monthly_cents = disc;
  2816. let detail = json!({
  2817. "layout": "diff",
  2818. "fields": after_view.diff(&before_view),
  2819. "whitelist": UPDATE_WHITELIST,
  2820. "end_date_untouched": true,
  2821. "annual_price_untouched": true,
  2822. "monthly_settle_untouched": true,
  2823. "i13_checked": true,
  2824. });
  2825. let audit_written = write_sub_audit(
  2826. &state,
  2827. &auth,
  2828. "subscription.update",
  2829. &sid,
  2830. Some(before_view.to_json()),
  2831. Some(after_view.to_json()),
  2832. detail,
  2833. )
  2834. .await;
  2835. row_out_resp(
  2836. &state,
  2837. &sid,
  2838. "updated",
  2839. notes,
  2840. json!({
  2841. "audit_written": audit_written,
  2842. "updated_fields": UPDATE_WHITELIST,
  2843. "row_version": body.row_version + 1,
  2844. "trial_months": trial,
  2845. "discount_monthly_cents": disc,
  2846. }),
  2847. )
  2848. .await
  2849. }
  2850. // ═══════════════════════════ §5.5 删除前检查与删除 ═══════════════════════════
  2851. /// 删除阻塞(§5.5 两栏)=账单明细 + 变更链。
  2852. ///
  2853. /// 账单明细只读口本轮未接线 ⇒ [`CrossRead::Unconfigured`](按登记回落值=「无账单」),
  2854. /// 出参**必须**说明该回落⛔ 构成「无阻塞结论」;变更链=本订阅作为**原订阅**被指向的行。
  2855. async fn delete_blocks(state: &AppState, r: &SubRow) -> Result<SubscriptionBlocks, BosError> {
  2856. let mut p = Params::default();
  2857. let a = p.push(Value::String(r.subscription_id.clone()));
  2858. let sql = format!(
  2859. "SELECT s.subscription_id AS v FROM subscription s \
  2860. WHERE s.replaces_subscription_id = {a}::text ORDER BY s.subscription_id"
  2861. );
  2862. let rows = state.db.query_all::<IdRow>(&sql, p.values()).await?;
  2863. let chain: Vec<String> = rows.into_iter().map(|x| x.v).collect();
  2864. check_subscription_deletable(&CrossRead::<bool>::Unconfigured, &[], &chain)
  2865. }
  2866. /// 在期附加子订阅(D-2 生命周期:**父删 ⇒ 有在期子的父不可删**)。
  2867. ///
  2868. /// 「在期」按库里的 `status` 取 `pending`/`active`:删除闸门不推导日期态(到期行可删是
  2869. /// 既有口径),子订阅只要没进真终态就还在履约,父一删它就会变成没有父的 `addon`
  2870. /// (`parent_subscription_id` 悬空,`ck_sub_parent` 只保证非空、不保证父还在)。
  2871. async fn live_children(state: &AppState, parent_id: &str) -> Result<Vec<String>, BosError> {
  2872. let mut p = Params::default();
  2873. let a = p.push(Value::String(parent_id.to_string()));
  2874. let sql = format!(
  2875. "SELECT s.subscription_id AS v FROM subscription s \
  2876. WHERE s.parent_subscription_id = {a}::text \
  2877. AND s.status IN ('pending', 'active') ORDER BY s.subscription_id"
  2878. );
  2879. let rows = state.db.query_all::<IdRow>(&sql, p.values()).await?;
  2880. Ok(rows.into_iter().map(|x| x.v).collect())
  2881. }
  2882. /// 真终态(已退订/被承接)⛔ 任何写操作。
  2883. ///
  2884. /// ⚠️「到期」**⛔** 算这里的闸门:删除的阻塞按 05 册 §5.6 只有两类(已产生账单明细
  2885. /// ⇒`KLT-M227`/被 `replaces_subscription_id` 指为变更链原订阅⇒`KLT-M230`),
  2886. /// 03 册 §5.2「当前可否编辑」=权限 ∧ 未被替代 ∧ 删除预检——到期本身⛔ 是判据
  2887. /// (13 册回滚场景「订阅建错且未出账 ⇒ `delete_check` → 删除」正是到期行可删的正例)。
  2888. fn terminal_guard(r: &SubRow, today: &str, op: &str) -> Result<(String, String), BosError> {
  2889. let (key, label, _) = status_display(r, today);
  2890. if key == "cancelled" || key == "replaced" || key == "early_stopped" {
  2891. return Err(BosError::bad_params(format!(
  2892. "订阅 {} 状态={label},不允许{op}(已退订/被承接/提前停机=真终态,只读)",
  2893. r.subscription_id
  2894. )));
  2895. }
  2896. Ok((key, label))
  2897. }
  2898. /// `POST /subscription/delete_check@v1`:删除弹窗的两栏阻塞(账单明细 + 变更链)。
  2899. pub async fn delete_check(
  2900. State(state): State<AppState>,
  2901. RequireAuth(auth): RequireAuth,
  2902. DataBody(body): DataBody<SubscriptionIdReq>,
  2903. ) -> Response {
  2904. if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
  2905. return json_err(e);
  2906. }
  2907. let sid = match req_field("subscription_id", &body.subscription_id) {
  2908. Ok(v) => v,
  2909. Err(e) => return json_err(e),
  2910. };
  2911. let r = match scoped_sub(&state, &auth, &sid).await {
  2912. Ok(Some(v)) => v,
  2913. Ok(None) => {
  2914. return json_err(BosError::not_found(format!(
  2915. "订阅不存在或超出当前账号可见范围:{sid}"
  2916. )))
  2917. }
  2918. Err(e) => return json_err(e),
  2919. };
  2920. let blocks = match delete_blocks(&state, &r).await {
  2921. Ok(v) => v,
  2922. Err(e) => return json_err(e),
  2923. };
  2924. let children = match live_children(&state, &sid).await {
  2925. Ok(v) => v,
  2926. Err(e) => return json_err(e),
  2927. };
  2928. let t = today();
  2929. let (key, label, _) = status_display(&r, &t);
  2930. let mut status_blocks: Vec<String> = if key == "pending" || key == "active" {
  2931. Vec::new()
  2932. } else {
  2933. vec![format!("状态={label},不删除(§5.7)")]
  2934. };
  2935. // D-2 生命周期:有在期附加子订阅的父不可删(先停子或整链路停用)。
  2936. if !children.is_empty() {
  2937. status_blocks.push(format!(
  2938. "该订阅下还有 {} 条在期附加子订阅({}),父删会让子订阅失去归属(D-2);\
  2939. 请先停用子订阅或整链路做服务停用",
  2940. children.len(),
  2941. children.join("、")
  2942. ));
  2943. }
  2944. let mut notes: Vec<String> = vec![format!(
  2945. "{BILLING_UNCONFIGURED_NOTE}本次检查**未取得**「无账单阻塞」结论。"
  2946. )];
  2947. notes.extend(blocks.note.clone());
  2948. json_ok(json!({
  2949. "subscription_id": r.subscription_id,
  2950. "can_delete": status_blocks.is_empty(),
  2951. "status": key,
  2952. "status_label": label,
  2953. "blocks": {
  2954. "billing_details": blocks.billing_details,
  2955. "change_chain": blocks.change_chain,
  2956. "live_children": children,
  2957. },
  2958. "status_blocks": status_blocks,
  2959. "billing_state": "unconfigured",
  2960. "notes": notes,
  2961. }))
  2962. }
  2963. /// `POST /subscription/delete@v1`:删除 + 第 6 步额度回退(同一批语句)。
  2964. pub async fn delete(
  2965. State(state): State<AppState>,
  2966. RequireAuth(auth): RequireAuth,
  2967. DataBody(body): DataBody<SubscriptionIdReq>,
  2968. ) -> Response {
  2969. if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
  2970. return json_err(e);
  2971. }
  2972. let sid = match req_field("subscription_id", &body.subscription_id) {
  2973. Ok(v) => v,
  2974. Err(e) => return json_err(e),
  2975. };
  2976. let r = match scoped_sub(&state, &auth, &sid).await {
  2977. Ok(Some(v)) => v,
  2978. Ok(None) => {
  2979. return json_err(BosError::not_found(format!(
  2980. "订阅不存在或超出当前账号可见范围:{sid}"
  2981. )))
  2982. }
  2983. Err(e) => return json_err(e),
  2984. };
  2985. let t = today();
  2986. if let Err(e) = terminal_guard(&r, &t, "删除") {
  2987. return json_err(e);
  2988. }
  2989. // 阻塞复算(⛔ 让前端只靠 delete_check 的结论下单:两次调用之间状态可能已变)
  2990. if let Err(e) = delete_blocks(&state, &r).await {
  2991. return json_err(e);
  2992. }
  2993. // D-2 生命周期:有在期子的父不可删(与 delete_check 同源复算)。
  2994. match live_children(&state, &sid).await {
  2995. Ok(v) if !v.is_empty() => {
  2996. return json_err(BosError::klt(
  2997. KltCode::M230,
  2998. format!(
  2999. "订阅 {sid} 下还有 {} 条在期附加子订阅({}),父删会让子订阅失去归属(D-2):\
  3000. 请先停用子订阅或整链路做服务停用",
  3001. v.len(),
  3002. v.join("、")
  3003. ),
  3004. ));
  3005. }
  3006. Ok(_) => {}
  3007. Err(e) => return json_err(e),
  3008. }
  3009. // §5.7 第 6 步:额度回退=剔除本行后重算应占额度(升降配不重复计入由求和口径自然保证)
  3010. let rest_rows: Vec<SubRow> = match subs_of_customer(&state, &r.customer_id).await {
  3011. Ok(v) => v.into_iter().filter(|x| x.subscription_id != sid).collect(),
  3012. Err(e) => return json_err(e),
  3013. };
  3014. let target = match quota_target(&state, &r.customer_id, &rest_rows).await {
  3015. Ok(v) => v,
  3016. Err(e) => return json_err(e),
  3017. };
  3018. let before = match customer_quota(&state, &r.customer_id).await {
  3019. Ok(v) => v,
  3020. Err(e) => return json_err(e),
  3021. };
  3022. let mut p = Params::default();
  3023. let preds: Vec<String> = vec![
  3024. format!("subscription_id = {}::text", p.push(Value::String(sid.clone()))),
  3025. format!("status = {}::text", p.push(Value::String(r.status.clone()))),
  3026. ];
  3027. let mut stmts: Vec<DmlStatement> = vec![DmlStatement::new(
  3028. format!("DELETE FROM subscription {}", p.where_clause(&preds)),
  3029. p.values().to_vec(),
  3030. )];
  3031. if before != target {
  3032. stmts.push(quota_stmt(&r.customer_id, target));
  3033. }
  3034. let results = match state.db.dml_batch(&stmts).await {
  3035. Ok(v) => v,
  3036. Err(e) => return json_err(e),
  3037. };
  3038. let mut want: Vec<(&str, u64)> = vec![("订阅行 DELETE", 1)];
  3039. if stmts.len() > 1 {
  3040. want.push(("客户额度回退", 1));
  3041. }
  3042. if let Err(e) = assert_batch(&results, &want) {
  3043. return json_err(e);
  3044. }
  3045. let mut notes: Vec<String> = vec![
  3046. format!(
  3047. "{BILLING_UNCONFIGURED_NOTE}本次删除**未取得**「无账单阻塞」结论,需在只读口接线后复核。"
  3048. ),
  3049. "档位 `catalog_plan.first_referred_at` 打点不回滚(§5.7:引用事实不可逆,档位不回到可下架)。"
  3050. .to_string(),
  3051. format!(
  3052. "额度按「应占额度」对齐:删除前 {before} 分,应占 {target} 分,释放 {} 分。",
  3053. before - target
  3054. ),
  3055. ];
  3056. // D-41(需求§4.2):删除订阅=额度缩减侧 ⇒ 分账号**只补不删**,超出的席位一行不删(随到期
  3057. // 停机转停用),只把「为什么不删」如实写回 `notes`+审计 `detail_json.sub_accounts`。
  3058. let seats = super::sub_provision::align_seats_of(&state, &r.subscription_id, 0).await;
  3059. notes.push(seats.note());
  3060. // 后置审计 `subscription.delete`(08 册 §8.1 CU-19/§8.3):真删 ⇒ `before_json` 记完整关键字段
  3061. // 快照、`after_json` 为空;额度前后/释放值、账单口径未接线声明、打点不回滚声明照记。
  3062. let detail = json!({
  3063. "layout": "multi",
  3064. "quota_before": before,
  3065. "quota_target": target,
  3066. "quota_released": before - target,
  3067. "sub_accounts": seats.to_json(),
  3068. "plan_id": r.plan_id,
  3069. "plan_name_snapshot": r.plan_name,
  3070. "contract_id": r.contract_id,
  3071. "order_no": r.order_no,
  3072. "billing_note": BILLING_UNCONFIGURED_NOTE.to_string(),
  3073. "first_referred_at_note": "catalog_plan.first_referred_at 打点不回滚(引用事实不可逆)",
  3074. });
  3075. let audit_written = write_sub_audit(
  3076. &state,
  3077. &auth,
  3078. "subscription.delete",
  3079. &sid,
  3080. Some(SubAuditView::of_row(&r).to_json()),
  3081. None,
  3082. detail,
  3083. )
  3084. .await;
  3085. json_ok(json!({
  3086. "deleted": true,
  3087. "audit_written": audit_written,
  3088. "subscription_id": sid,
  3089. "quota_released": before - target,
  3090. "quota_align": { "before": before, "target": target, "written": before != target },
  3091. "notes": notes,
  3092. }))
  3093. }
  3094. // ═══════════════════════ §5.6/§5.7 列表:get_list 与 list_all 共用一份实现 ═══════════════════════
  3095. /// 列表的**唯一**查询实现(§5.1「不为两个页面写两套查询——一旦分叉,计数同源迟早破」)。
  3096. ///
  3097. /// 两个入口只差入参:订阅管理页 `customer_id` 必填;全部订阅页客户可选、可跨客户、
  3098. /// 可带区域筛选(区域经 `dim_node_ancestor` 展开成客户集合,⛔ 本册表带区域列)。
  3099. /// 订阅的出账聚合(详情页四卡:应收合计/已出账/未出账/累计成本)。
  3100. ///
  3101. /// 取数真源(第 6 册):
  3102. /// * 应收合计/累计成本/期次数=`billing_receivable` 按 `subscription_id` 求和
  3103. /// (`receivable_cents`/`cost_deduct_cents`);
  3104. /// * 已出账金额=`bill_detail.share_base_cents` 中**已执行批次**且明细未作废(`status='active'`)
  3105. /// 的合计(与账单明细页同一谓词);
  3106. /// * 未出账=应收合计 − 已出账(不足 0 按 0,异常差额由明细页核对)。
  3107. ///
  3108. /// 无应收行 ⇒ 四值回 `null` + `state="no_receivable"`(⛔ 回 0 冒充「没有钱」);有行 ⇒
  3109. /// `state="ok"`。⛔ 回连 `catalog_plan`/`contract` 现价推算。
  3110. async fn billing_summary(
  3111. state: &AppState,
  3112. ids: &[String],
  3113. ) -> Result<HashMap<String, Value>, BosError> {
  3114. let mut out: HashMap<String, Value> = HashMap::new();
  3115. if ids.is_empty() {
  3116. return Ok(out);
  3117. }
  3118. let mut recv: HashMap<String, (i64, i64, i64)> = HashMap::new();
  3119. let mut billed: HashMap<String, i64> = HashMap::new();
  3120. let mut p = Params::default();
  3121. let in_pred = push_in(&mut p, "subscription_id", ids, "text");
  3122. let q_in = push_in(&mut p, "d.subscription_id", ids, "text");
  3123. // UDS 收拢:应收聚合 + 已出账 原 2 跳 → 1 条 UNION ALL。
  3124. // ⚠️ 聚合函数与左括号之间留空格(额度求和断言不误触)。
  3125. let sql = format!(
  3126. "SELECT 'recv' AS kind, subscription_id AS k, \
  3127. COALESCE(SUM (receivable_cents), 0)::text AS a, \
  3128. COALESCE(SUM (cost_deduct_cents), 0)::text AS b, COUNT(1)::text AS c \
  3129. FROM billing_receivable WHERE {in_pred} GROUP BY subscription_id \
  3130. UNION ALL \
  3131. SELECT 'billed' AS kind, d.subscription_id AS k, \
  3132. COALESCE(SUM (d.share_base_cents), 0)::text AS a, '' AS b, '' AS c \
  3133. FROM bill_detail d JOIN reconcile_batch b ON b.batch_no = d.batch_no \
  3134. WHERE {q_in} AND d.status = 'active' AND b.status = 'executed' \
  3135. GROUP BY d.subscription_id"
  3136. );
  3137. for r in state.db.query_all::<Value>(&sql, p.values()).await? {
  3138. let kind = r.get("kind").and_then(Value::as_str).unwrap_or_default();
  3139. let k = r.get("k").and_then(Value::as_str).unwrap_or_default().to_string();
  3140. if k.is_empty() {
  3141. continue;
  3142. }
  3143. let parse = |key: &str| {
  3144. r.get(key).and_then(|v| match v {
  3145. Value::String(s) => s.trim().parse::<i64>().ok(),
  3146. other => other.as_i64(),
  3147. }).unwrap_or(0)
  3148. };
  3149. match kind {
  3150. "recv" => {
  3151. recv.insert(k, (parse("a"), parse("b"), parse("c")));
  3152. }
  3153. "billed" => {
  3154. billed.insert(k, parse("a"));
  3155. }
  3156. _ => {}
  3157. }
  3158. }
  3159. for id in ids {
  3160. let v = match recv.get(id) {
  3161. None => json!({
  3162. "state": "no_receivable",
  3163. "receivable_cents": Value::Null,
  3164. "billed_cents": Value::Null,
  3165. "unbilled_cents": Value::Null,
  3166. "cost_cents": Value::Null,
  3167. "periods": 0,
  3168. }),
  3169. Some((receivable, cost, periods)) => {
  3170. let b = billed.get(id).copied().unwrap_or(0);
  3171. json!({
  3172. "state": "ok",
  3173. "receivable_cents": receivable,
  3174. "billed_cents": b,
  3175. "unbilled_cents": (*receivable - b).max(0),
  3176. "cost_cents": cost,
  3177. "periods": periods,
  3178. })
  3179. }
  3180. };
  3181. out.insert(id.clone(), v);
  3182. }
  3183. Ok(out)
  3184. }
  3185. /// 订阅列表展示名回填(客户名 + 合同编号)单 UDS。
  3186. async fn sub_list_names(
  3187. db: &bos_platform::clients::uds::UdsClient,
  3188. customer_ids: &[String],
  3189. contract_ids: &[String],
  3190. ) -> Result<(HashMap<String, Vec<String>>, HashMap<String, Vec<String>>), BosError> {
  3191. let mut names: HashMap<String, Vec<String>> = HashMap::new();
  3192. let mut contract_nos: HashMap<String, Vec<String>> = HashMap::new();
  3193. if customer_ids.is_empty() && contract_ids.is_empty() {
  3194. return Ok((names, contract_nos));
  3195. }
  3196. let mut p = Params::default();
  3197. let mut parts = Vec::new();
  3198. if !customer_ids.is_empty() {
  3199. let in_pred = push_in(&mut p, "customer_id", customer_ids, "text");
  3200. parts.push(format!(
  3201. "SELECT 'c' AS kind, customer_id AS k, customer_name AS v FROM customer WHERE {in_pred}"
  3202. ));
  3203. }
  3204. if !contract_ids.is_empty() {
  3205. let in_pred = push_in(&mut p, "k.contract_id", contract_ids, "text");
  3206. parts.push(format!(
  3207. "SELECT 'k' AS kind, k.contract_id AS k, \
  3208. COALESCE(NULLIF(k.external_no, ''), k.contract_no) AS v \
  3209. FROM contract k WHERE {in_pred}"
  3210. ));
  3211. }
  3212. #[derive(Deserialize)]
  3213. struct Row {
  3214. #[serde(deserialize_with = "de::as_string")]
  3215. kind: String,
  3216. #[serde(deserialize_with = "de::as_string")]
  3217. k: String,
  3218. #[serde(deserialize_with = "de::as_string")]
  3219. v: String,
  3220. }
  3221. for r in db.query_all::<Row>(&parts.join(" UNION ALL "), p.values()).await? {
  3222. match r.kind.as_str() {
  3223. "c" => names.entry(r.k).or_default().push(r.v),
  3224. "k" => {
  3225. if !r.v.trim().is_empty() {
  3226. contract_nos.entry(r.k).or_default().push(r.v);
  3227. }
  3228. }
  3229. _ => {}
  3230. }
  3231. }
  3232. Ok((names, contract_nos))
  3233. }
  3234. async fn list_records(
  3235. state: &AppState,
  3236. auth: &bos_scope::AuthContext,
  3237. body: &SubscriptionListReq,
  3238. customer_required: bool,
  3239. // `list_all` 台账页不展示出账四卡 ⇒ 跳过 `billing_summary`(Wave B:业务跳 4→3);
  3240. // `get_list`/详情仍要随行下发。
  3241. include_billing: bool,
  3242. ) -> Result<Value, BosError> {
  3243. let mut unknown: Vec<&str> = body.rest.keys().map(String::as_str).collect();
  3244. if !unknown.is_empty() {
  3245. unknown.sort_unstable();
  3246. return Err(BosError::bad_params(format!(
  3247. "不支持的检索条件:{}(可用 keyword/status/plan_kind/line_exit/expiring_within_days/\
  3248. customer_id/contract_id/region_ids/page/page_size)",
  3249. unknown.join("、")
  3250. )));
  3251. }
  3252. let cid = opt_trim(body.customer_id.as_ref());
  3253. if customer_required && cid.is_none() {
  3254. return Err(BosError::bad_params(
  3255. "customer_id 必填:订阅管理页按客户列出该客户的全部订阅(§5.1)",
  3256. ));
  3257. }
  3258. let t = today();
  3259. let mut p = Params::default();
  3260. let mut w: Vec<String> = vec![customer_scope_pred(state, auth, &mut p, "s.customer_id").await?];
  3261. if let Some(c) = cid {
  3262. w.push(format!("s.customer_id = {}::text", p.push(Value::String(c.to_string()))));
  3263. }
  3264. if let Some(regions) = opt_region_ids(body.region_ids.as_ref()) {
  3265. let ids = customers_under_regions(state, regions).await?;
  3266. w.push(push_in(&mut p, "s.customer_id", &ids, "text"));
  3267. }
  3268. // 关键字需 JOIN 客户名/合同号 ⇒ FROM 带 LEFT JOIN(仅筛选时也 JOIN,口径单一)。
  3269. let need_kw_join = opt_trim(body.keyword.as_ref()).is_some();
  3270. if let Some(k) = p.push_like(opt_trim(body.keyword.as_ref())) {
  3271. w.push(format!(
  3272. "(s.plan_name LIKE {k} OR s.subscription_id LIKE {k} \
  3273. OR COALESCE(s.order_no, '') LIKE {k} \
  3274. OR COALESCE(cu.customer_name, '') LIKE {k} \
  3275. OR COALESCE(ct.contract_no, '') LIKE {k} \
  3276. OR COALESCE(ct.external_no, '') LIKE {k})"
  3277. ));
  3278. }
  3279. if let Some(ct) = opt_trim(body.contract_id.as_ref()) {
  3280. w.push(format!("s.contract_id = {}::text", p.push(Value::String(ct.to_string()))));
  3281. }
  3282. if let Some(pk) = opt_trim(body.plan_kind.as_ref()) {
  3283. match pk {
  3284. "fixed" | "custom" => {
  3285. w.push(format!(
  3286. "s.plan_kind = {}::text",
  3287. p.push(Value::String(pk.to_string()))
  3288. ));
  3289. }
  3290. other => {
  3291. return Err(BosError::bad_params(format!(
  3292. "plan_kind 只接受 fixed/custom,收到「{other}」"
  3293. )));
  3294. }
  3295. }
  3296. }
  3297. if let Some(exit) = p.push_like(opt_trim(body.line_exit.as_ref())) {
  3298. // 快照 jsonb 以文本 LIKE 命中出口名(与台账下拉同源;⛔ 相关 EXISTS)。
  3299. w.push(format!("COALESCE(s.line_exits::text, '') LIKE {exit}"));
  3300. }
  3301. if let Some(days) = body.expiring_within_days {
  3302. if days < 0 {
  3303. return Err(BosError::bad_params(format!(
  3304. "expiring_within_days 须 ≥ 0,收到 {days}"
  3305. )));
  3306. }
  3307. let until = NaiveDate::parse_from_str(&t, "%Y-%m-%d")
  3308. .unwrap_or_else(|_| chrono::Local::now().date_naive())
  3309. + chrono::Duration::days(days);
  3310. let td = p.push(Value::String(t.clone()));
  3311. let until_p = p.push(Value::String(date_text(until)));
  3312. // 快到期=止期 ∈ [today, today+N];已到期(止期 < today)不算。日期上限在 Rust 算好,
  3313. // ⛔ SQL `date + int`(UDS/DataFusion 对日期算术支持不稳定)。
  3314. w.push("COALESCE(s.end_date, s.expire_date) IS NOT NULL".to_string());
  3315. w.push(format!("COALESCE(s.end_date, s.expire_date)::date >= {td}::date"));
  3316. w.push(format!("COALESCE(s.end_date, s.expire_date)::date <= {until_p}::date"));
  3317. }
  3318. if let Some(st) = opt_trim(body.status.as_ref()) {
  3319. // 状态三态是**读侧推导**(本轮⛔ 日终翻转任务)⇒ 筛选谓词与 `status_display` 同源
  3320. match st {
  3321. "cancelled" | "replaced" | "early_stopped" => {
  3322. w.push(format!("s.status = {}::text", p.push(Value::String(st.to_string()))));
  3323. }
  3324. "pending" => {
  3325. let td = p.push(Value::String(t.clone()));
  3326. w.push("s.status NOT IN ('cancelled','replaced','early_stopped')".to_string());
  3327. w.push(format!("COALESCE(s.start_date, s.effective_date) > {td}::date"));
  3328. }
  3329. "active" => {
  3330. let td = p.push(Value::String(t.clone()));
  3331. w.push("s.status NOT IN ('cancelled','replaced','early_stopped')".to_string());
  3332. w.push(format!("COALESCE(s.start_date, s.effective_date) <= {td}::date"));
  3333. w.push(format!("COALESCE(s.end_date, s.expire_date) >= {td}::date"));
  3334. }
  3335. "expired" => {
  3336. let td = p.push(Value::String(t.clone()));
  3337. w.push("s.status NOT IN ('cancelled','replaced','early_stopped')".to_string());
  3338. w.push(format!("COALESCE(s.end_date, s.expire_date) < {td}::date"));
  3339. }
  3340. other => {
  3341. return Err(BosError::bad_params(format!(
  3342. "未知订阅状态筛选值:{other}(可选 pending/active/expired/cancelled/replaced/early_stopped)"
  3343. )))
  3344. }
  3345. }
  3346. }
  3347. // ⚠️ `total()` 只接受 `FROM … WHERE …` 片段(它自己前缀 `SELECT COUNT(1) AS c`),
  3348. // 把 `SELECT_COLS` 拼进来会成 `SELECT COUNT(1) AS c SELECT …` ⇒ UDS 侧解析报错。
  3349. let from_clause = if need_kw_join {
  3350. "FROM subscription s \
  3351. LEFT JOIN customer cu ON cu.customer_id = s.customer_id \
  3352. LEFT JOIN contract ct ON ct.contract_id = s.contract_id"
  3353. } else {
  3354. "FROM subscription s"
  3355. };
  3356. let from_where = format!("{from_clause} {}", p.where_clause(&w));
  3357. let total = total(state.db.as_ref(), &from_where, p.values()).await?;
  3358. let (lim, off) = p.push_page(&body.pg);
  3359. let sql =
  3360. format!("{SELECT_COLS} {from_where} ORDER BY s.customer_id, s.subscription_id DESC LIMIT {lim} OFFSET {off}");
  3361. let rows = state.db.query_all::<SubRow>(&sql, p.values()).await?;
  3362. let ids: Vec<String> = rows.iter().map(|r| r.customer_id.clone()).collect();
  3363. let contract_ids: Vec<String> = rows
  3364. .iter()
  3365. .filter_map(|r| opt_trim(r.contract_id.as_ref()).map(str::to_string))
  3366. .collect();
  3367. // UDS 收拢:客户名 + 合同编号 原 2 跳 → 1 条 UNION。
  3368. let (names, contract_nos) = sub_list_names(state.db.as_ref(), &ids, &contract_ids).await?;
  3369. let items: Vec<Value> = rows
  3370. .iter()
  3371. .map(|r| {
  3372. let contract_no = r
  3373. .contract_id
  3374. .as_deref()
  3375. .and_then(|id| contract_nos.get(id))
  3376. .and_then(|v| v.first())
  3377. .map(String::as_str);
  3378. to_json(
  3379. r,
  3380. names.get(&r.customer_id).and_then(|v| v.first()).map(String::as_str),
  3381. contract_no,
  3382. &t,
  3383. )
  3384. })
  3385. .collect();
  3386. // 出账聚合(详情页四卡):一次批量算本页全部订阅,⛔ 逐行 N+1。
  3387. // Wave B:`list_all` 台账不展示四卡 ⇒ `include_billing=false` 跳过本跳(业务约 3);
  3388. // 详情改走 `subscription/get`;`get_list`(客户订阅管理)仍随行下发。
  3389. let mut items = items;
  3390. if include_billing {
  3391. let sub_ids: Vec<String> = rows.iter().map(|r| r.subscription_id.clone()).collect();
  3392. let mut billing = billing_summary(state, &sub_ids).await?;
  3393. for (i, r) in rows.iter().enumerate() {
  3394. if let Some(v) = items.get_mut(i) {
  3395. v["billing"] = billing.remove(&r.subscription_id).unwrap_or_else(|| json!({
  3396. "state": "no_receivable",
  3397. "receivable_cents": Value::Null,
  3398. "billed_cents": Value::Null,
  3399. "unbilled_cents": Value::Null,
  3400. "cost_cents": Value::Null,
  3401. "periods": 0,
  3402. }));
  3403. }
  3404. }
  3405. }
  3406. Ok(json!({
  3407. "items": items,
  3408. "total": total,
  3409. "page": body.pg.page,
  3410. "page_size": body.pg.page_size,
  3411. "notes": [
  3412. "关键字命中 plan_name/subscription_id/order_no/客户名/合同号(LEFT JOIN)。",
  3413. "状态三态为读侧推导(本轮无日终状态任务);`editable`/`reason` 与状态同源。",
  3414. if include_billing {
  3415. "本应答随行下发出账四卡(billing_summary)。"
  3416. } else {
  3417. "list_all 跳过 billing_summary;出账四卡请走 subscription/get。"
  3418. },
  3419. ],
  3420. }))
  3421. }
  3422. fn opt_region_ids(v: Option<&Vec<String>>) -> Option<&[String]> {
  3423. v.map(Vec::as_slice).filter(|s| !s.is_empty())
  3424. }
  3425. /// 订阅**读口**放行的角色(`get_list`/`list_all` 共用)。
  3426. ///
  3427. /// 2026-11-14 加 `Enterprise`:客户门户「订阅记录」页此前恒 `60058`。放行的前提是
  3428. /// [`list_records`] 的行集**恒以** [`customer_scope_pred`] 打头(客户主体 ⇒ 等值收窄到本公司,
  3429. /// 越权的 `customer_id` 入参只会命中空集),⛔ 在没有该谓词的读口上照抄这份清单。
  3430. /// 平台侧另需给 `enterprise` 角色绑 `bos.subscription.list`(否则先被网关 AC 拒成 `11001`)。
  3431. ///
  3432. /// 2026-11-16 加 `TeamLead`(P3-D9):团队长在「团队客户 → 客户档案 → 全部订单」里点「查看」会进
  3433. /// `/orders/{id}`,该页取 [`get`] ⇒ 此前恒 `60058`。行集同样由 [`customer_scope_pred`] 收窄到
  3434. /// 本团队在册客户,越权 `customer_id` 只命中空集。
  3435. const SUB_READ_ROLES: [RoleCode; 6] = [
  3436. RoleCode::Admin,
  3437. RoleCode::OpsMain,
  3438. RoleCode::Ops,
  3439. RoleCode::OpsSub,
  3440. RoleCode::Enterprise,
  3441. RoleCode::TeamLead,
  3442. ];
  3443. /// 订阅**详情**读口放行的角色([`get`])。
  3444. ///
  3445. /// 与 [`SUB_READ_ROLES`] 分开列:`Enterprise`(客户主账号)的套餐页走
  3446. /// `subscription/get_list`+门户自读,详情口未接线,⛔ 顺手放开;`TeamLead` 必须放行(P3-D9)。
  3447. const SUB_DETAIL_ROLES: [RoleCode; 5] = [
  3448. RoleCode::Admin,
  3449. RoleCode::OpsMain,
  3450. RoleCode::Ops,
  3451. RoleCode::OpsSub,
  3452. RoleCode::TeamLead,
  3453. ];
  3454. /// `POST /subscription/get_list@v1`:客户管理 → 套餐订阅管理页(唯一写入口的列表)。
  3455. pub async fn get_list(
  3456. State(state): State<AppState>,
  3457. RequireAuth(auth): RequireAuth,
  3458. DataBody(body): DataBody<SubscriptionListReq>,
  3459. ) -> Response {
  3460. if let Err(e) = auth.require_roles(&SUB_READ_ROLES) {
  3461. return json_err(e);
  3462. }
  3463. match list_records(&state, &auth, &body, true, true).await {
  3464. Ok(v) => json_ok(v),
  3465. Err(e) => json_err(e),
  3466. }
  3467. }
  3468. /// `POST /subscription/list_all@v1`:全部订阅页(⛔ 新增/编辑/删除入口,只查询)。
  3469. pub async fn list_all(
  3470. State(state): State<AppState>,
  3471. RequireAuth(auth): RequireAuth,
  3472. DataBody(body): DataBody<SubscriptionListReq>,
  3473. ) -> Response {
  3474. if let Err(e) = auth.require_roles(&SUB_READ_ROLES) {
  3475. return json_err(e);
  3476. }
  3477. // Wave B:台账不展示出账四卡 ⇒ 跳过 billing_summary(uds 业务跳约 3)。
  3478. match list_records(&state, &auth, &body, false, false).await {
  3479. Ok(v) => json_ok(v),
  3480. Err(e) => json_err(e),
  3481. }
  3482. }
  3483. // ═══════════════════════════ §5.4 详情:五分区 ═══════════════════════════
  3484. /// `POST /subscription/get@v1`:基本/周期/金额/出口/额度五分区 + 条件 `related`。
  3485. pub async fn get(
  3486. State(state): State<AppState>,
  3487. RequireAuth(auth): RequireAuth,
  3488. DataBody(body): DataBody<SubscriptionGetReq>,
  3489. ) -> Response {
  3490. if let Err(e) = auth.require_roles(&SUB_DETAIL_ROLES) {
  3491. return json_err(e);
  3492. }
  3493. let sid = match req_field("subscription_id", &body.subscription_id) {
  3494. Ok(v) => v,
  3495. Err(e) => return json_err(e),
  3496. };
  3497. let r = match scoped_sub(&state, &auth, &sid).await {
  3498. Ok(Some(v)) => v,
  3499. Ok(None) => {
  3500. return json_err(BosError::not_found(format!(
  3501. "订阅不存在或超出当前账号可见范围:{sid}"
  3502. )))
  3503. }
  3504. Err(e) => return json_err(e),
  3505. };
  3506. let t = today();
  3507. let names = match pairs_by(
  3508. state.db.as_ref(),
  3509. "customer",
  3510. "customer_id",
  3511. "customer_name",
  3512. &[r.customer_id.clone()],
  3513. )
  3514. .await
  3515. {
  3516. Ok(v) => v,
  3517. Err(e) => return json_err(e),
  3518. };
  3519. let customer_name = names
  3520. .get(&r.customer_id)
  3521. .and_then(|v| v.first())
  3522. .cloned()
  3523. .unwrap_or_default();
  3524. // 合同一栏:未关联合同显示「—」且⛔ 显示「未开通」(§5.4:⛔ 把「无合同」说成一种开通态)
  3525. let mut opened_state: Option<&str> = None;
  3526. let mut contract_no: Option<String> = None;
  3527. if let Some(ct) = opt_trim(r.contract_id.as_ref()) {
  3528. let all = match contracts_of_customer(&state, &r.customer_id).await {
  3529. Ok(v) => v,
  3530. Err(e) => return json_err(e),
  3531. };
  3532. if let Some(c) = all.into_iter().find(|c| c.contract_id == ct) {
  3533. contract_no =
  3534. Some(opt_trim(c.external_no.as_ref()).unwrap_or(c.contract_no.as_str()).to_string());
  3535. match opened_map_for(&state, &[c]).await {
  3536. Ok(m) => {
  3537. opened_state = match m.get(ct) {
  3538. Some(Opened::Opened) => Some("opened"),
  3539. Some(Opened::NotOpened) => Some("not_opened"),
  3540. None => None,
  3541. }
  3542. }
  3543. Err(e) => return json_err(e),
  3544. }
  3545. }
  3546. }
  3547. // 变更链(§5.4「关联订阅」):被谁替代 + 替代了谁
  3548. let replaced_by: Vec<Value> = {
  3549. let mut p = Params::default();
  3550. let a = p.push(Value::String(sid.clone()));
  3551. let sql = format!(
  3552. "{SELECT_COLS} FROM subscription s WHERE s.replaces_subscription_id = {a}::text \
  3553. ORDER BY s.subscription_id"
  3554. );
  3555. match state.db.query_all::<SubRow>(&sql, p.values()).await {
  3556. Ok(v) => v.iter().map(|x| brief(x, &t)).collect(),
  3557. Err(e) => return json_err(e),
  3558. }
  3559. };
  3560. let original: Option<Value> = match opt_trim(r.replaces_subscription_id.as_ref()) {
  3561. Some(o) => {
  3562. match scoped_sub(&state, &auth, o).await {
  3563. Ok(Some(row)) => Some(brief(&row, &t)),
  3564. Ok(None) => None,
  3565. Err(e) => return json_err(e),
  3566. }
  3567. }
  3568. None => None,
  3569. };
  3570. let quota_slots = as_opt_num(Some(r.quota_slots.as_str()));
  3571. let customer_quota_cents = match customer_quota(&state, &r.customer_id).await {
  3572. Ok(v) => v,
  3573. Err(e) => return json_err(e),
  3574. };
  3575. let mut v = to_json(&r, Some(customer_name.as_str()), contract_no.as_deref(), &t);
  3576. v["panels"] = json!({
  3577. "basic": {
  3578. "customer_id": r.customer_id,
  3579. "customer_name": customer_name,
  3580. "contract_id": r.contract_id,
  3581. "contract_no": contract_no.clone().unwrap_or_else(|| "—".to_string()),
  3582. "contract_opened_state": opened_state,
  3583. "contract_item_id": r.contract_item_id,
  3584. "order_no": opt_trim(r.order_no.as_ref()).unwrap_or("—"),
  3585. "actual_opened_at": opt_trim(r.actual_opened_at.as_ref()).unwrap_or("—"),
  3586. "early_stopped_at": opt_trim(r.early_stopped_at.as_ref()).unwrap_or("—"),
  3587. "plan_id": r.plan_id,
  3588. "plan_name": r.plan_name,
  3589. "plan_kind": r.plan_kind,
  3590. "created_at": r.created_at,
  3591. "row_version": as_opt_num(Some(r.row_version.as_str())),
  3592. },
  3593. "period": {
  3594. "term": r.term,
  3595. "start_date": start_text(&r),
  3596. "end_date": end_text(&r),
  3597. "effective_date": r.effective_date,
  3598. "expire_date": r.expire_date,
  3599. },
  3600. "amount": money_json(&r),
  3601. "exits": {
  3602. "plan_family": r.plan_family,
  3603. "sub_mode": r.sub_mode,
  3604. "line_exits": exits_json(r.line_exits.as_ref()),
  3605. "line_exit_key": r.line_exit_key,
  3606. },
  3607. "quota": {
  3608. "quota_slots": quota_slots,
  3609. "customer_quota_cents": customer_quota_cents,
  3610. },
  3611. });
  3612. v["related"] = json!({
  3613. "replaced_by": replaced_by,
  3614. "original": original,
  3615. });
  3616. // 套餐月成本只读口未接线 ⇒ 三态里的 `unconfigured`(⛔ 显示 0 元、⛔ 显示「无成本」)
  3617. v["plan_cost_cents"] = json!(null);
  3618. v["plan_cost_state"] = json!("unconfigured");
  3619. // 出账四卡(第 6 册):应收/已出账/未出账/累计成本来自 `billing_receivable` +
  3620. // 已执行批次 `bill_detail`;无应收行 ⇒ 四值 null + `no_receivable`,
  3621. // ⛔ 用 0 元冒充「未出账」。
  3622. let billing = match billing_summary(&state, &[r.subscription_id.clone()]).await {
  3623. Ok(mut m) => m.remove(&r.subscription_id).unwrap_or(Value::Null),
  3624. Err(e) => return json_err(e),
  3625. };
  3626. let billing_state = billing
  3627. .get("state")
  3628. .and_then(Value::as_str)
  3629. .unwrap_or("no_receivable")
  3630. .to_string();
  3631. v["billing"] = billing;
  3632. v["billing_state"] = json!(billing_state);
  3633. let mut notes: Vec<String> = vec![
  3634. COST_UNCONFIGURED_NOTE.to_string(),
  3635. if billing_state == "ok" {
  3636. "出账四卡=应收期次合计(billing_receivable)/已执行批次明细合计(bill_detail),\
  3637. 未出账=应收−已出账;逐期清单与对账批次状态请到对账页核对。"
  3638. .to_string()
  3639. } else {
  3640. "本条订阅尚无应收期次(billing_receivable 无行):四卡按「未配置」呈现,\
  3641. 不以 0 元或「未出账」冒充结论。"
  3642. .to_string()
  3643. },
  3644. ];
  3645. if contract_no.is_none() {
  3646. notes.push("本订阅未关联合同:合同一栏显示「—」,不显示「未开通」(§5.4)。".to_string());
  3647. }
  3648. v["notes"] = json!(notes);
  3649. json_ok(v)
  3650. }
  3651. /// 变更链节点的精简出参(⛔ 详情里递归展开整行)。
  3652. fn brief(r: &SubRow, today: &str) -> Value {
  3653. let (key, label, _) = status_display(r, today);
  3654. json!({
  3655. "subscription_id": r.subscription_id,
  3656. "plan_name": r.plan_name,
  3657. "status": key,
  3658. "status_label": label,
  3659. "start_date": start_text(r),
  3660. "end_date": end_text(r),
  3661. })
  3662. }
  3663. // ═══════════════════════════ stack(D-03:就地续期口已停用) ═══════════════════════════
  3664. /// `POST /subscription/stack@v1`:**D-03 起拒写**。
  3665. ///
  3666. /// 权威「叠加」=新建并存订阅(原订阅不动)+客户在用时经 `create@v1` 触发服务开通工单;
  3667. /// 本口原先「就地改 `end_date`」与 §5.2「结束日不可人工改」/数据模型「叠加=新增行」冲突。
  3668. /// 路由保留、契约入参形态不动,一律指向 `/subscription/create@v1`。
  3669. pub async fn stack(
  3670. State(_state): State<AppState>,
  3671. RequireAuth(auth): RequireAuth,
  3672. DataBody(_body): DataBody<SubscriptionStackReq>,
  3673. ) -> Response {
  3674. if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
  3675. return json_err(e);
  3676. }
  3677. json_err(BosError::bad_params(
  3678. "subscription/stack@v1 已停用就地改结束日(D-03):叠加=新建并存订阅,请走 \
  3679. /subscription/create@v1(§5.2 五步校验+六步事务;客户在用时自动生成服务开通工单)"
  3680. .to_string(),
  3681. ))
  3682. }
  3683. // ═══════════════════════════ 单元测试(纯函数+静态断言) ═══════════════════════════
  3684. #[cfg(test)]
  3685. mod tests {
  3686. use super::*;
  3687. #[test]
  3688. fn 额度变更写客户字段历史且带前后额度() {
  3689. // TC-CU-53 步骤 5:额度调整必须落 `customer_field_history(field_key='quota')`,
  3690. // 且旧值/新值分别是调整前后的席位数字符串(客户「归属变更」页直接展示这两列)。
  3691. let stmt = quota_history_stmt("KL-2026-000058", 0, 5, "377168271910113280");
  3692. assert!(stmt.sql.contains("INSERT INTO customer_field_history"), "{}", stmt.sql);
  3693. assert!(stmt.sql.contains("'quota'::text"), "{}", stmt.sql);
  3694. assert!(stmt.sql.contains("old_display"), "{}", stmt.sql);
  3695. assert!(stmt.sql.contains("new_display"), "{}", stmt.sql);
  3696. let vals: Vec<String> = stmt
  3697. .params
  3698. .iter()
  3699. .map(|v| match v {
  3700. Value::String(s) => s.clone(),
  3701. other => other.to_string(),
  3702. })
  3703. .collect();
  3704. assert!(vals.contains(&"0".to_string()), "{vals:?}");
  3705. assert!(vals.contains(&"5".to_string()), "{vals:?}");
  3706. assert!(vals.contains(&"377168271910113280".to_string()), "{vals:?}");
  3707. }
  3708. fn map(raw: &str) -> Map<String, Value> {
  3709. serde_json::from_str::<Value>(raw).unwrap().as_object().unwrap().clone()
  3710. }
  3711. #[test]
  3712. fn 时长折算先折下一周期生效日再减一天() {
  3713. // §5.2:2026-01-31 按月 ⇒ 下一周期 2026-02-28 ⇒ 结束日 2026-02-27
  3714. let d = NaiveDate::from_ymd_opt(2026, 1, 31).unwrap();
  3715. let next = add_months_clamped(d, 1);
  3716. assert_eq!(date_text(next), "2026-02-28");
  3717. let prev = next - chrono::Duration::days(1);
  3718. assert_eq!(date_text(prev), "2026-02-27");
  3719. // 按年=加 12 个月;按季度=加 3 个月
  3720. assert_eq!(term_months("yearly").unwrap(), 12);
  3721. assert_eq!(term_months("quarterly").unwrap(), 3);
  3722. assert_eq!(term_months("monthly").unwrap(), 1);
  3723. assert!(term_months("weekly").is_err());
  3724. let d2 = NaiveDate::from_ymd_opt(2028, 2, 29).unwrap();
  3725. assert_eq!(date_text(add_months_clamped(d2, 12)), "2029-02-28");
  3726. }
  3727. #[test]
  3728. fn 年价按订阅时长折算且月结算不受时长影响() {
  3729. assert_eq!(annual_by_term(120_000, 10_000, "yearly"), 120_000);
  3730. assert_eq!(annual_by_term(120_000, 10_000, "quarterly"), 30_000);
  3731. assert_eq!(annual_by_term(120_000, 10_000, "monthly"), 10_000);
  3732. }
  3733. #[test]
  3734. fn 新建载荷的只读派生列逐列点名拒收() {
  3735. let m = map(r#"{"annual_price_cents":1,"line_exits":["美国"],"sub_mode":"upgrade","end_date":"2027-01-01","order_no":"X","actual_opened_at":"2026-01-01","monthly_settle_cents":2,"term":"monthly","item_family":"addon"}"#);
  3736. let e = reject_read_only(&m, &CREATE_READ_ONLY).unwrap_err();
  3737. let s = format!("{e}");
  3738. for k in [
  3739. "annual_price_cents",
  3740. "monthly_settle_cents",
  3741. "end_date",
  3742. "line_exits",
  3743. "sub_mode",
  3744. "order_no",
  3745. "actual_opened_at",
  3746. // D-15:条目形态随条目带入,订阅载荷⛔ 再收
  3747. "item_family",
  3748. ] {
  3749. assert!(s.contains(k), "未点名 {k}:{s}");
  3750. }
  3751. assert!(!s.contains("term"), "term 是新增态唯一入参,不拒收:{s}");
  3752. let ok = map(r#"{"customer_id":"C1","plan_id":"P1","term":"monthly"}"#);
  3753. assert!(reject_read_only(&ok, &CREATE_READ_ONLY).is_ok());
  3754. }
  3755. #[test]
  3756. #[allow(non_snake_case)] // 测试名用中文直述判据口径(错误码后缀保持大写更易检索)
  3757. fn 修改白名单两列其余键点名且换套餐走M229() {
  3758. let swap = map(r#"{"plan_id":"P2"}"#);
  3759. assert!(matches!(
  3760. reject_update_payload(&swap),
  3761. Err(e) if format!("{e}").contains("KLT-M229") || format!("{e:?}").contains("M229")
  3762. ));
  3763. let bad = map(r#"{"end_date":"2027-01-01","term":"monthly","status":"active"}"#);
  3764. let s = format!("{}", reject_update_payload(&bad).unwrap_err());
  3765. for k in ["end_date", "term", "status"] {
  3766. assert!(s.contains(k), "未点名 {k}:{s}");
  3767. }
  3768. assert!(reject_update_payload(&map(r#"{"trial_months":3}"#)).is_ok());
  3769. assert!(reject_update_payload(&Map::new()).is_ok());
  3770. }
  3771. fn row(status: &str, start: Option<&str>, end: Option<&str>) -> SubRow {
  3772. SubRow {
  3773. subscription_id: "SUB-1".to_string(),
  3774. customer_id: "C1".to_string(),
  3775. contract_id: None,
  3776. contract_item_id: None,
  3777. plan_id: Some("P1".to_string()),
  3778. plan_name: Some("标准档".to_string()),
  3779. plan_kind: Some("fixed".to_string()),
  3780. plan_owner_customer_id: None,
  3781. status: status.to_string(),
  3782. plan_family: Some("link".to_string()),
  3783. sub_mode: None,
  3784. line_exits: None,
  3785. line_exit_key: Some("中国香港".to_string()),
  3786. start_date: start.map(str::to_string),
  3787. end_date: end.map(str::to_string),
  3788. term: Some("yearly".to_string()),
  3789. trial_months: None,
  3790. discount_monthly_cents: None,
  3791. annual_price_cents: Some("2000000".to_string()),
  3792. monthly_settle_cents: Some("166666".to_string()),
  3793. quota_slots: "10".to_string(),
  3794. quantity: "1".to_string(),
  3795. parent_subscription_id: None,
  3796. replaces_subscription_id: None,
  3797. order_no: None,
  3798. actual_opened_at: None,
  3799. early_stopped_at: None,
  3800. effective_date: None,
  3801. expire_date: None,
  3802. created_at: "2026-01-01".to_string(),
  3803. row_version: "1".to_string(),
  3804. }
  3805. }
  3806. #[test]
  3807. fn 终态状态不被读侧推导覆盖() {
  3808. let t = "2026-11-09";
  3809. // 库值=生效中,日期已过 ⇒ 推导成已到期(本轮⛔ 日终翻转任务)
  3810. let (k, l, n) = status_display(&row("active", Some("2025-01-01"), Some("2025-12-31")), t);
  3811. assert_eq!(k, "expired");
  3812. assert_eq!(l, "已到期");
  3813. assert!(n.is_none());
  3814. // 终态(已退订/已替换/提前停机)原样保留,⛔ 被日期改写
  3815. let (k2, _, _) = status_display(&row("cancelled", Some("2025-01-01"), Some("2026-12-31")), t);
  3816. assert_eq!(k2, "cancelled");
  3817. let (k3, _, _) = status_display(&row("replaced", Some("2025-01-01"), Some("2026-12-31")), t);
  3818. assert_eq!(k3, "replaced");
  3819. let (k6, l6, _) =
  3820. status_display(&row("early_stopped", Some("2025-01-01"), Some("2026-12-31")), t);
  3821. assert_eq!(k6, "early_stopped");
  3822. assert_eq!(l6, "提前停机");
  3823. // 待生效
  3824. let (k4, _, _) = status_display(&row("pending", Some("2027-01-01"), Some("2027-12-31")), t);
  3825. assert_eq!(k4, "pending");
  3826. // 日期缺失 ⇒ 回库值+说明(⛔ 凭空造一个状态)
  3827. let (k5, _, n5) = status_display(&row("active", None, None), t);
  3828. assert_eq!(k5, "active");
  3829. assert!(n5.is_some());
  3830. }
  3831. #[test]
  3832. fn 终态订阅不可修改不可删除() {
  3833. let t = "2026-11-09";
  3834. assert!(terminal_guard(&row("expired", Some("2025-01-01"), Some("2025-12-31")), t, "删除").is_ok());
  3835. assert!(terminal_guard(&row("cancelled", Some("2025-01-01"), Some("2026-12-31")), t, "删除").is_err());
  3836. assert!(terminal_guard(&row("replaced", Some("2025-01-01"), Some("2026-12-31")), t, "修改").is_err());
  3837. }
  3838. #[test]
  3839. fn 金额出参一处折算点() {
  3840. let v = money_json(&row("active", Some("2026-01-01"), Some("2026-12-31")));
  3841. assert_eq!(v["annual_price_cents"], json!(2000000));
  3842. assert_eq!(v["monthly_settle_cents"], json!(166666));
  3843. assert_eq!(
  3844. v["monthly_settle_display"].as_str().unwrap(),
  3845. "2000000(折算 166666/月)"
  3846. );
  3847. }
  3848. #[test]
  3849. fn 源码静态断言_除月数与冲突改写只有一处实现() {
  3850. let src = include_str!("subscription.rs");
  3851. let lower = src.to_lowercase();
  3852. let conflict = concat!("ON CON", "FLICT");
  3853. assert!(!src.contains(conflict), "UDS 不支持冲突改写");
  3854. assert!(
  3855. !lower.contains(concat!(" cur", "rent_date")),
  3856. "不在 SQL 里取当前日期(时区口径须与 today() 一致)"
  3857. );
  3858. // 月结算与额度求和的唯一实现落在 bos-invariant,本模块⛔ 自行「金额 ÷12」/自行 SUM。
  3859. // ⚠️ 只锁**金额侧**写法:`add_months_clamped` 里的 `total / 12` 是日期取模,
  3860. // 与月结算算式无关,按裸 `/ 12` 断言会把正确的日期数学一起判死。
  3861. for pat in [concat!("cents / 1", "2"), concat!("cents/1", "2")] {
  3862. assert!(
  3863. !src.contains(pat),
  3864. "月结算标准金额只能经 monthly_settle_of 折算(05 册 §3.3 唯一算式)"
  3865. );
  3866. }
  3867. assert!(
  3868. !src.to_uppercase().contains(concat!("SU", "M(")),
  3869. "在用额度求和只能经 in_use_quota_sum_batch(§5.6 唯一实现)"
  3870. );
  3871. assert!(
  3872. !src.contains(concat!(".me", "ssage()")),
  3873. "BosError 不提供该访问器"
  3874. );
  3875. assert!(src.contains("check_subscription_deletable"), "删除阻塞必须走不变量库(M227/M230 同源)");
  3876. }
  3877. }