| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027 |
- //! 订阅维护与升降配承接(第 3 册 §5)。
- //!
- //! ## 本轮口径(设计列已在册 ⇒ 只读派生列一律⛔ 接受入参)
- //!
- //! * **六项只读派生**(`annual_price_cents`/`monthly_settle_cents`/`end_date`/`line_exits`/
- //! `sub_mode`/`order_no`+`actual_opened_at`)+变更链指针 `replaces_subscription_id` 只属于
- //! `/change`:载荷出现即 `11103` 点名(§5.2「手工填价与手工改到期日=数据污染的入口」)。
- //! 唯一可录的周期入参=`term`(`yearly`/`quarterly`/`monthly`,缺省按年)。
- //! * **快照六列**(`plan_name`/`plan_kind`/`plan_owner_customer_id`/`line_exits`+`line_exit_key`/
- //! `term`/`sub_mode`)由档位与条目折算后落库=当时值(§2.3「改档⛔ 追溯改历史订阅」),
- //! 读侧⛔ 现取 `catalog_plan`(`to_json` 的 `plan_name` 走快照列)。
- //! * 金额与状态一律走 [`bos_invariant`]:`monthly_settle_of`=月结算唯一折算点、
- //! `subscription_status_of`=状态唯一判据、`in_use_quota_sum_batch`=额度求和唯一实现、
- //! I6 已于 2026-11-19 停用(D-15:`sub_mode` 不再派生),码位 `KLT-M224` 保留不复用。
- //!
- //! ## 写侧事务落点(§5.2 六步)
- //!
- //! UDS 只暴露 `/dml/batch@v1`(整批原子提交、⛔ 批内条件中止、⛔ 行锁、⛔ 回读行集),故六步
- //! 落成**一次 `dml_batch`**:截原 → 新行 INSERT → `catalog_plan.first_referred_at` 打点 →
- //! 客户额度对齐;每步的前置条件写进 `WHERE` 谓词,影响行数**事后自检**,异常即
- //! `BosError::internal` 点名已提交的形态(⛔ 静默)。`SELECT … FOR UPDATE` 无能力 ⇒ 「锁条目行」
- //! 落成带谓词的守卫更新,差异登 18 册。
- //!
- //! ⚠️ 工单事实、账单明细、套餐月成本三枚跨册只读口本轮⛔ 未接线 ⇒ 一律 `CrossRead::Unconfigured`
- //! +响应点名(⛔ 塌成「无阻塞」「未配置=零成本」)。
- //!
- //! ⛔ 日终到期翻转任务(`SUB-EFF`)本轮不做:状态在读侧按三要素推导(`status_display`)。
- use axum::extract::State;
- use axum::response::Response;
- use bos_api::extract::{json_err, json_ok, DataBody, RequireAuth};
- use bos_api::AppState;
- use bos_core::page::PageQuery;
- use bos_core::{BosError, KltCode, RoleCode};
- use bos_invariant::{
- check_i12b_same_customer, check_i13_trial_months, check_plan_available,
- check_subscription_deletable, contracts_opened, in_use_quota_sum_batch, monthly_settle_of,
- normalize_line_exits, subscription_status_of, CrossRead,
- NormalizedExits, Opened, OpenedProbe, PlanFamily, PlanRef, SubscriptionBlocks,
- };
- use bos_platform::clients::uds::{de, DmlStatement};
- use chrono::{Datelike, NaiveDate};
- use serde::Deserialize;
- use serde_json::{json, Map, Value};
- use std::collections::{HashMap, HashSet};
- use super::listq::{
- as_num, as_opt_num, count_by, next_seq, pairs_by, push_in, total, Params,
- };
- use super::partner::customer_scope_pred;
- /// 补列后已无缺列(⛔ 删键=前端类型会缺字段)。
- const COLUMNS_PENDING: &[&str] = &[];
- /// 订阅时长值域(§2.3 `term`;⛔ 落库成月数,月数只是折算中间量)。
- const TERMS: [&str; 3] = ["yearly", "quarterly", "monthly"];
- /// 在用状态(§4 额度口径:仅待生效与生效中占额度)。
- pub(crate) const IN_USE_STATUS: [&str; 2] = ["pending", "active"];
- /// 六项只读派生列+变更链指针:新建载荷出现即 `11103`(§5.2 段 3/4、§2.3)。
- const CREATE_READ_ONLY: [&str; 10] = [
- "annual_price_cents",
- "monthly_settle_cents",
- "end_date",
- "line_exits",
- "sub_mode",
- "order_no",
- "actual_opened_at",
- "early_stopped_at",
- "replaces_subscription_id",
- // D-15:`item_family` 随所引合同条目带入并冻结(合同侧载荷已拒传),订阅侧⛔ 再收一份。
- "item_family",
- ];
- /// 升降配额外只读项:⛔ 换客户(`customer_id` 只做一致性校验),用途分类跟着新档位走
- /// (需求明文「不换分类另建」)。⚠️ 2026-11-16 修正:`contract_id`/`contract_item_id` 由
- /// 契约(`openapi.yaml` `/subscription/change@v1`)列为必填「新合同/新条目」,此前误入拒收表
- /// ⇒ 前端按契约提交必吃 `KLT-S20004`,升降配在界面与接口两侧都不可用(P5-D1)。
- const CHANGE_READ_ONLY: [&str; 9] = [
- "plan_family",
- "annual_price_cents",
- "monthly_settle_cents",
- "end_date",
- "line_exits",
- "sub_mode",
- "order_no",
- "actual_opened_at",
- "early_stopped_at",
- ];
- /// 修改白名单:只有这两列可改(§5.7)。
- const UPDATE_WHITELIST: [&str; 2] = ["trial_months", "discount_monthly_cents"];
- /// 修改里点名 `KLT-M229` 的越权列(换套餐/换合同=改订语义)。
- const UPDATE_M229_KEYS: [&str; 3] = ["plan_id", "contract_id", "contract_item_id"];
- /// 账单明细只读口未接线的原文说明(§5.5「未配置=不可判定,⛔ 当成无阻塞」)。
- const BILLING_UNCONFIGURED_NOTE: &str = "账单明细只读口本轮未接线(`billing_state=unconfigured`):\
- 「账单阻塞=无」是取数未配置的回落值,不构成无阻塞结论,删除须由人工复核账单。";
- /// 套餐月成本只读口未接线的原文说明(§5.4 段 2)。
- const COST_UNCONFIGURED_NOTE: &str = "套餐月成本只读口本轮未接线(`plan_cost_state=unconfigured`):\
- `plan_cost_item` 在册但成本折算属第 4 册口径,不以 0 冒充无成本。";
- /// 开户工单只读口未接线的原文说明(§2.1/§5.2 第 6 步)。
- pub(crate) const TICKET_UNCONFIGURED_NOTE: &str = "开户工单只读口本轮未接线(`open_tickets=unconfigured`):\
- 开通态判定只用了本域自读的 `actual_opened_at` 一维,不据此认定合同未开通;\
- 新订第 6 步「回写开户工单号与订单号」同样未接线,本轮未回写。";
- /// 统一取列(写侧回读、列表、详情、I6 取数共用一份列集=⛔ 三处漂移)。
- const SELECT_COLS: &str = "SELECT s.subscription_id, s.customer_id, s.contract_id, s.contract_item_id, \
- s.plan_id, s.plan_name, s.plan_kind, s.plan_owner_customer_id, s.status, s.plan_family, s.sub_mode, \
- s.line_exits, s.line_exit_key, s.start_date, s.end_date, s.term, s.trial_months, \
- s.discount_monthly_cents, s.annual_price_cents, s.monthly_settle_cents, s.quota_slots, \
- s.quantity, s.parent_subscription_id, s.replaces_subscription_id, s.order_no, s.actual_opened_at, \
- s.early_stopped_at, s.effective_date, s.expire_date, s.created_at, s.row_version";
- /// 档位取列(`p`=`catalog_plan`)。`plan_family` 是条目/订阅形态的**唯一来源**;
- /// 派生档整链已删(D-15)⇒ 不再有 `derived_from_contract_item_id`。
- const PLAN_COLS: &str = "SELECT p.plan_id, p.plan_name, p.plan_kind, p.customer_id, p.status, \
- p.plan_family, p.sub_account_quota, p.annual_price_cents, \
- p.monthly_settle_cents, p.line_exits, p.first_referred_at";
- // ───────────────────────── 入参 ─────────────────────────
- /// 新建载荷:`rest` 捕获未建模的键,用于把只读派生列点名拒收(⛔ 静默忽略)。
- #[derive(Deserialize)]
- pub struct SubscriptionCreateReq {
- pub customer_id: String,
- pub plan_id: String,
- /// 可空**只是为了给出业务文案**(TC-CU-51 步骤 2):缺键时 `serde` 原本直接回
- /// `missing field contract_id`,页面无法把它渲染成「请选择合同编号」这一句。
- /// 语义仍是必填(见 [`create`] 的首段校验)。
- pub contract_id: Option<String>,
- /// 与 `contract_id` 同现同空(§2.3);合同内一条匹配条目都没有时可空(§5.2 末段)。
- pub contract_item_id: Option<String>,
- /// 缺省=当天(§5.2「开始日(默当天)」)。
- pub start_date: Option<String>,
- /// 唯一可录的周期入参;缺省按年(§5.2)。
- pub term: Option<String>,
- /// 交付形态(只读确认位):只能与所选档位的 `plan_family` 相同,不同即 `11103`。
- pub plan_family: Option<String>,
- pub trial_months: Option<i64>,
- pub discount_monthly_cents: Option<i64>,
- /// 档位份数(2026-11-17):缺省 1;仅可叠加档(叠加增值)允许 > 1,其余档给 > 1 即拒。
- /// 一份合同条目仍只生一份订阅——数量是订阅自身的份数,不是条目数。
- pub quantity: Option<i64>,
- #[serde(flatten)]
- pub rest: Map<String, Value>,
- }
- /// 升降配载荷:⛔ 换客户(`customer_id` 仅用于一致性校验);合同与条目按契约可另选新合同
- /// (`contract_id` 缺省时沿用原订阅合同,兼容旧调用)。
- #[derive(Deserialize)]
- pub struct SubscriptionChangeReq {
- /// 被替换的原订阅,至多被指向一次(§5.3)。
- pub replaces_subscription_id: String,
- pub plan_id: String,
- /// 新合同(契约明写「不得沿用原合同」;缺省=沿用原订阅合同)。
- pub contract_id: Option<String>,
- /// 新合同服务条目(缺省=按新档位在合同内反查)。
- pub contract_item_id: Option<String>,
- /// 仅做一致性校验:与原订阅客户不同即拒。
- pub customer_id: Option<String>,
- /// 缺省=当天(截原基线)。
- pub start_date: Option<String>,
- pub term: Option<String>,
- pub trial_months: Option<i64>,
- pub discount_monthly_cents: Option<i64>,
- /// 乐观锁作用于**原订阅行**。
- pub row_version: Option<i64>,
- #[serde(flatten)]
- pub rest: Map<String, Value>,
- }
- /// 修改载荷:白名单两列+乐观锁,其余键一律拒收(§5.7)。
- #[derive(Deserialize)]
- pub struct SubscriptionUpdateReq {
- pub subscription_id: String,
- pub row_version: i64,
- pub trial_months: Option<i64>,
- pub discount_monthly_cents: Option<i64>,
- #[serde(flatten)]
- pub rest: Map<String, Value>,
- }
- #[derive(Deserialize)]
- pub struct SubscriptionIdReq {
- pub subscription_id: String,
- }
- #[derive(Deserialize)]
- pub struct SubscriptionOptionsReq {
- pub customer_id: String,
- /// 只读列表用关键字(⛔ 客户名称/合同编号检索)。
- pub keyword: Option<String>,
- }
- /// 列表入参(`get_list` 与 `list_all` 共用=同一实现只差入参)。
- #[derive(Deserialize)]
- pub struct SubscriptionListReq {
- #[serde(flatten)]
- pub pg: PageQuery,
- /// 命中套餐名快照/订阅号/订单号/客户名/合同号(LEFT JOIN customer/contract)。
- pub keyword: Option<String>,
- pub customer_id: Option<String>,
- pub contract_id: Option<String>,
- pub status: Option<String>,
- /// 套餐类型:`fixed`/`custom`(快照列 `subscription.plan_kind`)。
- pub plan_kind: Option<String>,
- /// 线路出口名称(命中 `line_exits` 快照 JSON 文本)。
- pub line_exit: Option<String>,
- /// 快到期:止期落在 `[today, today+N]`(含边界;已到期不算)。
- pub expiring_within_days: Option<i64>,
- /// 区域筛选=按客户挂载区域展开成客户集合(§5.7)。
- pub region_ids: Option<Vec<String>>,
- #[serde(flatten)]
- pub rest: Map<String, Value>,
- }
- #[derive(Deserialize)]
- pub struct SubscriptionGetReq {
- pub subscription_id: String,
- }
- #[derive(Deserialize)]
- pub struct SubscriptionStackReq {
- pub subscription_id: Option<String>,
- pub end_date: Option<String>,
- pub annual_price_cents: Option<i64>,
- pub monthly_settle_cents: Option<i64>,
- /// 以下五列只属于 openapi 的「叠加新建」分支,本轮⛔ 新建行 ⇒ 带上就点名未落库。
- pub customer_id: Option<String>,
- pub plan_id: Option<String>,
- pub contract_id: Option<String>,
- pub contract_item_id: Option<String>,
- pub start_date: Option<String>,
- pub row_version: Option<i64>,
- }
- // ───────────────────────── 共用小件 ─────────────────────────
- fn trimmed(raw: &str) -> String {
- raw.trim().to_string()
- }
- /// 必填串;空白=显式失败(⛔ 落成空串)。
- pub(crate) fn req_field(field: &str, raw: &str) -> Result<String, BosError> {
- let s = trimmed(raw);
- if s.is_empty() {
- return Err(BosError::bad_params(format!("{field} 必填")));
- }
- Ok(s)
- }
- /// `YYYY-MM-DD` 解析(同时兜住「日期不可比」与「非法值传给 `::date` 后 UDS 报错」两种失效形态)。
- pub(crate) fn parse_date(field: &str, raw: &str) -> Result<NaiveDate, BosError> {
- NaiveDate::parse_from_str(raw.trim(), "%Y-%m-%d")
- .map_err(|_| BosError::bad_params(format!("{field} 须为 YYYY-MM-DD,实得 {raw}")))
- }
- pub(crate) fn date_text(d: NaiveDate) -> String {
- d.format("%Y-%m-%d").to_string()
- }
- pub(crate) fn today() -> String {
- chrono::Local::now().format("%Y-%m-%d").to_string()
- }
- pub(crate) fn opt_trim(v: Option<&String>) -> Option<&str> {
- v.map(String::as_str).map(str::trim).filter(|s| !s.is_empty())
- }
- /// 只读派生列出现在载荷里 ⇒ `11103` 逐列点名(⛔ 忽略、⛔ 只取服务端值而不告知)。
- fn reject_read_only(rest: &Map<String, Value>, keys: &[&str]) -> Result<(), BosError> {
- let hit: Vec<&str> = keys.iter().copied().filter(|k| rest.contains_key(*k)).collect();
- if hit.is_empty() {
- return Ok(());
- }
- Err(BosError::bad_params(format!(
- "以下只读派生列不接受入参(服务端按档位/条目折算落库):{}",
- hit.join("、")
- )))
- }
- /// 月数折算(§2.3:年=12/季=3/月=1)。
- pub(crate) fn term_months(term: &str) -> Result<u32, BosError> {
- match term {
- "yearly" => Ok(12),
- "quarterly" => Ok(3),
- "monthly" => Ok(1),
- other => Err(BosError::bad_params(format!(
- "term 须∈ {TERMS:?},实得 {other}"
- ))),
- }
- }
- /// 加 `n` 个月并把不存在的日期折到月末(§5.2「该月无对应日取月末」)。
- pub(crate) fn add_months_clamped(d: NaiveDate, n: u32) -> NaiveDate {
- let total = d.year() as u64 * 12 + (d.month0() as u64) + n as u64;
- let year = (total / 12) as i64;
- let month = ((total % 12) + 1) as u32;
- let dim = days_in_month(year, u64::from(month));
- let day = d.day().min(dim);
- NaiveDate::from_ymd_opt(year as i32, month, day).unwrap_or(d)
- }
- fn days_in_month(year: i64, month: u64) -> u32 {
- let m = month as u32;
- match m {
- 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
- 4 | 6 | 9 | 11 => 30,
- 2 => {
- if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
- 29
- } else {
- 28
- }
- }
- _ => 30,
- }
- }
- /// 年订阅价格=`term` × 月结算标准金额(季=月×3、月=月;年取档位年价原值)。
- pub(crate) fn annual_by_term(plan_annual: i64, monthly: i64, term: &str) -> i64 {
- match term {
- "monthly" => monthly,
- "quarterly" => monthly.saturating_mul(3),
- _ => plan_annual,
- }
- }
- /// JSONB 出口列 → 字符串数组(dev 用 JSONB 承载 `TEXT[]`,可能回数组也可能回 JSON 串)。
- pub(crate) fn exits_of(v: Option<&Value>, field: &str) -> Result<Vec<String>, BosError> {
- let bad = || BosError::bad_params(format!("{field} 须为字符串数组(线路出口原值)"));
- match v {
- None | Some(Value::Null) => Ok(Vec::new()),
- Some(Value::String(s)) => serde_json::from_str::<Vec<String>>(s)
- .map_err(|_| BosError::bad_params(format!("{field} 不是字符串数组的 JSON:{s}"))),
- Some(Value::Array(arr)) => arr
- .iter()
- .map(|x| {
- x.as_str()
- .map(str::to_string)
- .filter(|s| !s.trim().is_empty())
- .ok_or_else(bad)
- })
- .collect(),
- Some(_) => Err(bad()),
- }
- }
- /// 出口列出参:JSONB 原样回(⛔ 摊平、⛔ 用摘要冒充原值)。
- pub(crate) fn exits_json(v: Option<&Value>) -> Value {
- match v {
- Some(Value::String(s)) => serde_json::from_str::<Value>(s).unwrap_or(Value::Null),
- Some(x) => x.clone(),
- None => Value::Null,
- }
- }
- /// 读侧的日期口径:设计列 → 一期骨架列(存量种子只有旧列有值)。
- pub(crate) fn start_text(r: &SubRow) -> Option<String> {
- opt_trim(r.start_date.as_ref())
- .or_else(|| opt_trim(r.effective_date.as_ref()))
- .map(|s| s.to_string())
- }
- pub(crate) fn end_text(r: &SubRow) -> Option<String> {
- opt_trim(r.end_date.as_ref())
- .or_else(|| opt_trim(r.expire_date.as_ref()))
- .map(|s| s.to_string())
- }
- /// 状态三态的读侧落点:库里的终态(`cancelled`/`replaced`/`early_stopped`)原样保留,
- /// 其余按三要素推导。
- ///
- /// 为什么不直接回库值:库里 `status` 由日终任务翻转,而 `SUB-EFF` 本轮⛔ 未做 ⇒ 直接回库值
- /// 会把「已到期」显示成「生效中」;也不⛔ 在日期不可判时硬套三态(会凭空判成到期)。
- /// `early_stopped`=提前停机:起止日不变,⛔ 再按日期推回生效中。
- pub(crate) fn status_display(r: &SubRow, today: &str) -> (String, String, Option<String>) {
- let terminal = |s: &str| s == "cancelled" || s == "replaced" || s == "early_stopped";
- let label = |k: &str| match k {
- "pending" => "待生效",
- "active" => "生效中",
- "expired" => "已到期",
- "replaced" => "已替换",
- "cancelled" => "已退订",
- "early_stopped" => "提前停机",
- _ => "未知",
- };
- if terminal(r.status.as_str()) {
- return (r.status.clone(), label(r.status.as_str()).to_string(), None);
- }
- match (start_text(r), end_text(r)) {
- (Some(s), Some(e)) => {
- let k = subscription_status_of(&s, &e, today).as_str().to_string();
- (k.clone(), label(&k).to_string(), None)
- }
- _ => (
- r.status.clone(),
- label(&r.status).to_string(),
- Some(format!(
- "订阅 {0} 的 start_date/end_date 不完整,状态不按三要素推导,原样回库里 status。",
- r.subscription_id
- )),
- ),
- }
- }
- /// 行级可操作性:到期/已替换/已退订的订阅⛔ 升降配、修改、删除(§5.3/§5.7)。
- fn editability(r: &SubRow, display_key: &str) -> (bool, Option<String>) {
- if display_key != "pending" && display_key != "active" {
- return (
- false,
- Some(format!(
- "订阅状态={},不升降配/续订/修改/删除",
- display_key
- )),
- );
- }
- if opt_trim(r.contract_id.as_ref()).is_none() {
- return (
- true,
- Some("该订阅未关联合同(仅升降配不),合同开通态一栏显示「—」且不显示未开通。".to_string()),
- );
- }
- (true, None)
- }
- // ───────────────────────── 行与出参 ─────────────────────────
- /// 订阅行(读侧快照):`succession` 公共层与合同写口共用同一形态 ⇒ 字段 `pub(crate)`。
- #[derive(Clone, Deserialize)]
- pub(crate) struct SubRow {
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) subscription_id: String,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) customer_id: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) contract_id: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) contract_item_id: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) plan_id: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) plan_name: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) plan_kind: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) plan_owner_customer_id: Option<String>,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) status: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) plan_family: Option<String>,
- /// 历史值:三分类收敛后新行恒 `NULL`(I6 停用),读侧只做只读回显。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) sub_mode: Option<String>,
- pub(crate) line_exits: Option<Value>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) line_exit_key: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) start_date: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) end_date: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) term: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) trial_months: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) discount_monthly_cents: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) annual_price_cents: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) monthly_settle_cents: Option<String>,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) quota_slots: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) replaces_subscription_id: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) order_no: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) actual_opened_at: Option<String>,
- /// 提前停机日(`service_stop` 回填生效写入;起止日不变)。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) early_stopped_at: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) effective_date: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) expire_date: Option<String>,
- /// 订阅份数(`subscription.quantity`,2026-11-17 落列):可叠加档可 > 1,其余恒 1。
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) quantity: String,
- /// 附加订阅的父订阅(D-2/D-9):`addon` 必有父、`link` 恒空;父可属另一份合同。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) parent_subscription_id: Option<String>,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) created_at: String,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) row_version: String,
- }
- /// 列表行的钱列形态(§5.2 段 4「¥20,000(折算 ¥1,667/月)」)。
- fn money_json(r: &SubRow) -> Value {
- let annual = as_opt_num(r.annual_price_cents.as_deref());
- let monthly = as_opt_num(r.monthly_settle_cents.as_deref());
- let display = match (&annual, &monthly) {
- (Value::Number(a), Value::Number(m)) => Some(format!("{a}(折算 {m}/月)")),
- _ => None,
- };
- json!({
- "annual_price_cents": annual,
- "monthly_settle_cents": monthly,
- "monthly_settle_display": display,
- "trial_months": as_opt_num(r.trial_months.as_deref()),
- "discount_monthly_cents": as_opt_num(r.discount_monthly_cents.as_deref()),
- })
- }
- /// 列表/详情共用的行出参:`plan_name` 走**快照列**(⛔ 现取 `catalog_plan`)。
- fn to_json(
- r: &SubRow,
- customer_name: Option<&str>,
- contract_no: Option<&str>,
- today: &str,
- ) -> Value {
- let (key, label, note) = status_display(r, today);
- let (editable, reason) = editability(r, &key);
- json!({
- "subscription_id": r.subscription_id,
- "customer_id": r.customer_id,
- "customer_name": customer_name,
- "contract_id": r.contract_id,
- "contract_no": contract_no,
- "contract_item_id": r.contract_item_id,
- "plan_id": r.plan_id,
- "plan_name": r.plan_name,
- "plan_kind": r.plan_kind,
- "plan_owner_customer_id": r.plan_owner_customer_id,
- "status": r.status,
- "status_display": { "key": key, "label": label, "note": note },
- "plan_family": r.plan_family,
- "sub_mode": r.sub_mode,
- "line_exits": exits_json(r.line_exits.as_ref()),
- "line_exit_key": r.line_exit_key,
- "term": r.term,
- "start_date": start_text(r),
- "end_date": end_text(r),
- "annual_price_cents": as_opt_num(r.annual_price_cents.as_deref()),
- "monthly_settle_cents": as_opt_num(r.monthly_settle_cents.as_deref()),
- "trial_months": as_opt_num(r.trial_months.as_deref()),
- "discount_monthly_cents": as_opt_num(r.discount_monthly_cents.as_deref()),
- "quota_slots": as_num(&r.quota_slots),
- "quantity": as_num(&r.quantity),
- "parent_subscription_id": r.parent_subscription_id,
- "replaces_subscription_id": r.replaces_subscription_id,
- "order_no": r.order_no,
- "actual_opened_at": r.actual_opened_at,
- "early_stopped_at": r.early_stopped_at,
- "effective_date": r.effective_date,
- "expire_date": r.expire_date,
- "created_at": r.created_at,
- "row_version": as_num(&r.row_version),
- "editable": editable,
- "reason": reason,
- })
- }
- // ───────────────────────── 取数小件 ─────────────────────────
- #[derive(Deserialize)]
- struct IdRow {
- #[serde(deserialize_with = "de::as_string")]
- v: String,
- }
- #[derive(Deserialize)]
- struct CountRow {
- #[serde(deserialize_with = "de::as_string")]
- c: String,
- }
- /// 按 ID+可见范围取整行。
- async fn scoped_sub(
- state: &AppState,
- auth: &bos_scope::AuthContext,
- sub_id: &str,
- ) -> Result<Option<SubRow>, BosError> {
- let mut p = Params::default();
- let mut w: Vec<String> = Vec::new();
- w.push(customer_scope_pred(state, auth, &mut p, "s.customer_id").await?);
- let s = p.push(Value::String(sub_id.to_string()));
- w.push(format!("s.subscription_id = {s}::text"));
- let sql = format!("{SELECT_COLS} FROM subscription s {}", p.where_clause(&w));
- state.db.query_one::<SubRow>(&sql, p.values()).await
- }
- /// 客户在册**且**落在当前账号可见范围(§5.2 第 1 步;越权=`KLT-M221`)。
- async fn customer_visible(
- state: &AppState,
- auth: &bos_scope::AuthContext,
- customer_id: &str,
- ) -> Result<Option<String>, BosError> {
- let mut p = Params::default();
- let mut w: Vec<String> = Vec::new();
- w.push(customer_scope_pred(state, auth, &mut p, "c.customer_id").await?);
- let c = p.push(Value::String(customer_id.to_string()));
- w.push(format!("c.customer_id = {c}::text AND c.deleted_at IS NULL"));
- let sql = format!(
- "SELECT c.customer_name AS v FROM customer c {}",
- p.where_clause(&w)
- );
- Ok(state
- .db
- .query_one::<IdRow>(&sql, p.values())
- .await?
- .map(|r| r.v))
- }
- /// 可见范围谓词由 [`customer_scope_pred`] 统一给出(区域展开出的客户同样受该谓词约束),
- /// 本模块⛔ 另取一份「可见客户集合」=两份口径迟早分叉。
- /// 区域 → 客户集合展开(§5.7「区域筛选按客户挂载区域展开」=本册⛔ 按区域列查本册表)。
- ///
- /// 挂载表只有**直接父节点**,故须经 `dim_node_ancestor` 把筛选节点向下展开一层
- /// (`ancestor_id = 筛选节点` 的整棵子树都命中)。
- async fn customers_under_regions(state: &AppState, region_ids: &[String]) -> Result<Vec<String>, BosError> {
- let ids: Vec<String> = region_ids.iter().map(|s| trimmed(s)).filter(|s| !s.is_empty()).collect();
- if ids.is_empty() {
- return Ok(Vec::new());
- }
- let mut p = Params::default();
- let r = push_in(&mut p, "a.ancestor_id", &ids, "text");
- let sql = format!(
- "SELECT DISTINCT m.customer_id AS v FROM customer_region_mount m \
- JOIN dim_node_ancestor a ON a.node_id = m.parent_node_id \
- WHERE {r} AND m.customer_id IS NOT NULL ORDER BY 1"
- );
- Ok(state
- .db
- .query_all::<IdRow>(&sql, p.values())
- .await?
- .into_iter()
- .map(|r| r.v)
- .collect())
- }
- /// 某客户的全部订阅(I6/额度对齐/变更链的取数底座)。
- pub(crate) async fn subs_of_customer(state: &AppState, customer_id: &str) -> Result<Vec<SubRow>, BosError> {
- let mut p = Params::default();
- let c = p.push(Value::String(customer_id.to_string()));
- let sql = format!(
- "{SELECT_COLS} FROM subscription s WHERE s.customer_id = {c}::text ORDER BY s.subscription_id"
- );
- state.db.query_all::<SubRow>(&sql, p.values()).await
- }
- /// 档位行(含可用区间与首次引用打点)。`succession` 公共层读同一形态 ⇒ 字段 `pub(crate)`。
- #[derive(Deserialize)]
- pub(crate) struct PlanRow {
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) plan_id: String,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) plan_name: String,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) plan_kind: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) customer_id: Option<String>,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) status: String,
- /// 交付形态 `link`/`addon`:条目与订阅的形态**只从这里来**(库上 `ck_plan_family` 兜底)。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) plan_family: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) sub_account_quota: Option<String>,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) annual_price_cents: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) monthly_settle_cents: Option<String>,
- pub(crate) line_exits: Option<Value>,
- /// 首次引用打点:`Some` ⇒ 该档已被引用过(§5.2「已引用过的档位⛔ 下架」同源)。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) first_referred_at: Option<String>,
- }
- impl PlanRow {
- /// 交付形态(库上 `ck_plan_family` 已保证只有两值;缺失/脏值按 `link` 处理并落读侧告警)。
- pub(crate) fn family(&self) -> PlanFamily {
- match self.plan_family.as_deref().map(PlanFamily::parse) {
- Some(Ok(f)) => f,
- _ => {
- tracing::warn!(plan_id = %self.plan_id, raw = ?self.plan_family, "档位交付形态缺失/非法,按 link 处理");
- PlanFamily::Link
- }
- }
- }
- pub(crate) fn to_ref(&self) -> PlanRef {
- PlanRef {
- plan_id: self.plan_id.clone(),
- plan_name: self.plan_name.clone(),
- plan_kind: self.plan_kind.clone(),
- owner_customer_id: opt_trim(self.customer_id.as_ref()).map(str::to_string),
- plan_family: self.family(),
- sub_account_quota: self
- .sub_account_quota
- .as_deref()
- .and_then(|s| s.trim().parse::<i64>().ok())
- .unwrap_or(0),
- annual_price_cents: self
- .annual_price_cents
- .trim()
- .parse::<i64>()
- .unwrap_or(0),
- monthly_settle_cents: self
- .monthly_settle_cents
- .as_deref()
- .and_then(|s| s.trim().parse::<i64>().ok()),
- available: self.status == "active",
- }
- }
- pub(crate) fn monthly(&self) -> i64 {
- 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))
- }
- }
- pub(crate) async fn plan_rows(state: &AppState, ids: &[String]) -> Result<Vec<PlanRow>, BosError> {
- if ids.is_empty() {
- return Ok(Vec::new());
- }
- let mut p = Params::default();
- let in_pred = push_in(&mut p, "p.plan_id", ids, "text");
- let sql = format!("{PLAN_COLS} FROM catalog_plan p WHERE {in_pred}");
- state.db.query_all::<PlanRow>(&sql, p.values()).await
- }
- pub(crate) async fn plan_row(state: &AppState, plan_id: &str) -> Result<Option<PlanRow>, BosError> {
- Ok(plan_rows(state, &[plan_id.to_string()]).await?.pop())
- }
- /// 合同行。
- #[derive(Deserialize)]
- pub(crate) struct ContractRow {
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) contract_id: String,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) customer_id: String,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) contract_no: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) external_no: Option<String>,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) status: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) end_date: Option<String>,
- /// 合同总额(`contract.amount_cents`,分)。可空 ⇒ 客户端「总金额」列显「—」,
- /// ⛔ 回落 `subscription.annual_price_cents`(那是订阅价,升降配后必然不等)。
- #[serde(default, deserialize_with = "de::as_opt_string")]
- pub(crate) amount_cents: Option<String>,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) attachment_url: Option<String>,
- }
- const CONTRACT_COLS: &str = "SELECT k.contract_id, k.customer_id, k.contract_no, k.external_no, k.status, \
- k.end_date, k.amount_cents, k.attachment_url";
- pub(crate) async fn contracts_of_customer(
- state: &AppState,
- customer_id: &str,
- ) -> Result<Vec<ContractRow>, BosError> {
- let mut p = Params::default();
- let c = p.push(Value::String(customer_id.to_string()));
- let sql = format!(
- "{CONTRACT_COLS} FROM contract k WHERE k.customer_id = {c}::text ORDER BY k.contract_id"
- );
- state.db.query_all::<ContractRow>(&sql, p.values()).await
- }
- pub(crate) async fn contract_row(state: &AppState, contract_id: &str) -> Result<Option<ContractRow>, BosError> {
- let mut p = Params::default();
- let c = p.push(Value::String(contract_id.to_string()));
- let sql = format!("{CONTRACT_COLS} FROM contract k WHERE k.contract_id = {c}::text");
- state.db.query_one::<ContractRow>(&sql, p.values()).await
- }
- /// 合同服务构成条目(`plan_id` 必填:条目只剩「档位 × 份数」)。`succession` 共用 ⇒ 字段 `pub(crate)`。
- #[derive(Deserialize)]
- pub(crate) struct ItemRow {
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) item_id: String,
- #[serde(deserialize_with = "de::as_string")]
- pub(crate) contract_id: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) plan_id: Option<String>,
- /// 档位份数(2026-11-17:随条目带入订阅 `subscription.quantity`)。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) quantity: Option<String>,
- /// 交付形态(落库列;=所引档位的 `plan_family`,应用层已校验一致)。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) item_family: Option<String>,
- /// 条目形态(D-9):`new`/`increment`。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) item_mode: Option<String>,
- /// 父条目(D-7/D-2):附加条目指向同合同的 `link` 条目;增量条目恒空。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) serves_item_id: Option<String>,
- /// 增量条目的既有链路订阅(D-9):父订阅可属另一份合同。
- #[serde(deserialize_with = "de::as_opt_string")]
- pub(crate) ref_subscription_id: Option<String>,
- pub(crate) line_exits: Option<Value>,
- }
- const ITEM_COLS: &str = "SELECT i.item_id, i.contract_id, i.plan_id, i.quantity, \
- i.item_family, i.item_mode, i.serves_item_id, i.ref_subscription_id, i.line_exits";
- pub(crate) async fn items_of_contracts(
- state: &AppState,
- contract_ids: &[String],
- ) -> Result<Vec<ItemRow>, BosError> {
- if contract_ids.is_empty() {
- return Ok(Vec::new());
- }
- let mut p = Params::default();
- let in_pred = push_in(&mut p, "i.contract_id", contract_ids, "text");
- let sql = format!("{ITEM_COLS} FROM contract_service_item i WHERE {in_pred} ORDER BY i.item_id");
- state.db.query_all::<ItemRow>(&sql, p.values()).await
- }
- /// 开通态探测(§5.2 段 5:工单一维本轮未接线=`Unconfigured`;本域自读 `actual_opened_at`)。
- ///
- /// 取数失败 ⇒ `KLT-S406` 整体失败,⛔ 降级成「全部未开通」(那会把已交付合同摆进候选、
- /// 再经 `KLT-M223` 永久封死补录路径)。
- async fn opened_map_for(
- state: &AppState,
- contracts: &[ContractRow],
- ) -> Result<HashMap<String, Opened>, BosError> {
- let ids: Vec<String> = contracts.iter().map(|c| c.contract_id.clone()).collect();
- let mut actual: HashMap<String, Vec<Option<String>>> = HashMap::new();
- if !ids.is_empty() {
- let mut p = Params::default();
- let in_pred = push_in(&mut p, "s.contract_id", &ids, "text");
- let sql = format!(
- "SELECT s.contract_id AS k, s.actual_opened_at AS v FROM subscription s WHERE {in_pred}"
- );
- #[derive(Deserialize)]
- struct Pair {
- #[serde(deserialize_with = "de::as_string")]
- k: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- v: Option<String>,
- }
- let rows = state.db.query_all::<Pair>(&sql, p.values()).await.map_err(|e| {
- BosError::klt(
- KltCode::S406,
- format!("读取订阅实际开通日失败,开通态不可判定(不降级成「未开通」):{e}"),
- )
- })?;
- for r in rows {
- actual.entry(r.k).or_default().push(r.v);
- }
- }
- let probes: Vec<(String, OpenedProbe)> = contracts
- .iter()
- .map(|c| {
- (
- c.contract_id.clone(),
- OpenedProbe {
- open_tickets: CrossRead::Unconfigured,
- subscription_actual_opened_at: actual
- .get(&c.contract_id)
- .cloned()
- .unwrap_or_default(),
- },
- )
- })
- .collect();
- contracts_opened(&probes).map_err(|e| {
- BosError::klt(KltCode::S406, format!("开通态判定失败(不降级成「未开通」):{e}"))
- })
- }
- // ───────────────────────── §5.2 套餐候选 ─────────────────────────
- /// `POST /subscription/plan_options@v1`。
- ///
- /// 两段候选=本客户自定义档 + 全部固定档,⛔ 他客户自定义档;
- /// 每行带只读 `plan_family`(交付形态)与可选性/不可选原因。
- pub async fn plan_options(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionOptionsReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
- return json_err(e);
- }
- let cid = match req_field("customer_id", &body.customer_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // 读口同样把客户当不可信输入重算 ⇒ `KLT-M221`(一次判定,⛔ 重复查库)
- if let Err(e) = require_customer(&state, &auth, &cid).await {
- return json_err(e);
- }
- let kw = opt_trim(body.keyword.as_ref());
- let mut p = Params::default();
- let mut w: Vec<String> = vec![format!(
- "(p.plan_kind = {}::text OR (p.plan_kind = {}::text AND p.customer_id = {}::text))",
- p.push(Value::String("fixed".to_string())),
- p.push(Value::String("custom".to_string())),
- p.push(Value::String(cid.clone()))
- )];
- if let Some(k) = p.push_like(kw) {
- w.push(format!("p.plan_name LIKE {k}"));
- }
- let sql = format!(
- "{PLAN_COLS} FROM catalog_plan p {} ORDER BY p.plan_kind, p.plan_name, p.plan_id",
- p.where_clause(&w)
- );
- let rows = match state.db.query_all::<PlanRow>(&sql, p.values()).await {
- Ok(r) => r,
- Err(e) => return json_err(e),
- };
- // 引用次数单独取(⛔ 相关子查询混进档位行),与本册其它计数同源走 `listq::count_by`
- let plan_ids: Vec<String> = rows.iter().map(|r| r.plan_id.clone()).collect();
- let referred = match count_by(state.db.as_ref(), "subscription", "plan_id", &plan_ids).await {
- Ok(m) => m,
- Err(e) => return json_err(e),
- };
- let items: Vec<Value> = rows
- .iter()
- .map(|o| {
- let pr = o.to_ref();
- let (available, reason) = plan_selectability(&pr, &cid);
- let rc = referred.get(&o.plan_id).copied().unwrap_or(0);
- json!({
- "plan_id": o.plan_id,
- "plan_name": o.plan_name,
- "plan_kind": o.plan_kind,
- "owner_customer_id": o.customer_id,
- "plan_family": pr.plan_family.as_str(),
- "annual_price_cents": as_num(&o.annual_price_cents),
- "monthly_settle_cents": as_num(&o.monthly().to_string()),
- "sub_account_quota": as_opt_num(o.sub_account_quota.as_deref()),
- "line_exits": exits_json(o.line_exits.as_ref()),
- "referred_count": rc,
- "first_referred": o.first_referred_at.is_some(),
- "available": available,
- "unavailable_reason": reason,
- })
- })
- .collect();
- json_ok(json!({
- "customer_id": cid,
- "items": items,
- "total": items.len(),
- "notes": [
- "「交付形态」(link/addon)与额度、带宽、出口一并随档位,前端不重实现;\
- 叠加服务额度恒 0,条目/订阅份数 ≥1;跨境链路份数恒 1。",
- TICKET_UNCONFIGURED_NOTE,
- ],
- "columns_pending": COLUMNS_PENDING,
- }))
- }
- /// 档位可选性(§5.2「不可选=KLT-M228」的读侧同源判据;写侧兜底仍走 I12a/I12b)。
- ///
- /// ⚠️ 档位⛔ 有「可用日期窗口」列(`catalog_plan` 在册列只到 `status`/`first_referred_at`,
- /// 设计稿未给 `available_from`/`available_to`)⇒ 停用只按 `status` 判,⛔ 造列。
- pub(crate) fn plan_selectability(pr: &PlanRef, customer_id: &str) -> (bool, Option<String>) {
- if !pr.available {
- return (false, Some("档位已停用,不被新订阅选中".to_string()));
- }
- if let Some(owner) = pr.owner_customer_id.as_deref() {
- if owner != customer_id {
- return (false, Some(format!("自定义档归属客户 {owner},不跨客户选用")));
- }
- }
- (true, None)
- }
- // ───────────────────── 后置审计(§4.11/08 册 §8.1·§8.3)─────────────────────
- /// 订阅审计快照的**统一取值面**(§8.2:同一字段前后必须同型 ⇒ 新增/编辑/叠加/换约/删除共用)。
- ///
- /// 金额一律按「分」记(§8.1);`line_exits` 记编码数组;⛔ 把整表原文塞进审计。
- #[derive(Clone)]
- pub(crate) struct SubAuditView {
- subscription_id: String,
- customer_id: String,
- status: String,
- plan_id: Option<String>,
- plan_name: Option<String>,
- plan_family: Option<String>,
- sub_mode: Option<String>,
- line_exits: Option<Value>,
- term: Option<String>,
- start_date: Option<String>,
- end_date: Option<String>,
- trial_months: Option<i64>,
- discount_monthly_cents: Option<i64>,
- annual_price_cents: Option<i64>,
- monthly_settle_cents: Option<i64>,
- contract_id: Option<String>,
- contract_item_id: Option<String>,
- order_no: Option<String>,
- replaces_subscription_id: Option<String>,
- }
- impl SubAuditView {
- pub(crate) fn of_row(r: &SubRow) -> Self {
- Self {
- subscription_id: r.subscription_id.clone(),
- customer_id: r.customer_id.clone(),
- status: r.status.clone(),
- plan_id: r.plan_id.clone(),
- plan_name: r.plan_name.clone(),
- plan_family: r.plan_family.clone(),
- sub_mode: r.sub_mode.clone(),
- line_exits: r.line_exits.clone(),
- term: r.term.clone(),
- start_date: r.start_date.clone(),
- end_date: r.end_date.clone(),
- trial_months: as_opt_num(r.trial_months.as_deref()).as_i64(),
- discount_monthly_cents: as_opt_num(r.discount_monthly_cents.as_deref()).as_i64(),
- annual_price_cents: as_opt_num(r.annual_price_cents.as_deref()).as_i64(),
- monthly_settle_cents: as_opt_num(r.monthly_settle_cents.as_deref()).as_i64(),
- contract_id: r.contract_id.clone(),
- contract_item_id: r.contract_item_id.clone(),
- order_no: r.order_no.clone(),
- replaces_subscription_id: r.replaces_subscription_id.clone(),
- }
- }
- pub(crate) fn to_json(&self) -> Value {
- json!({
- "subscription_id": self.subscription_id,
- "customer_id": self.customer_id,
- "status": self.status,
- "plan_id": self.plan_id,
- "plan_name": self.plan_name,
- "plan_family": self.plan_family,
- "sub_mode": self.sub_mode,
- "line_exits": self.line_exits,
- "term": self.term,
- "start_date": self.start_date,
- "end_date": self.end_date,
- "trial_months": self.trial_months,
- "discount_monthly_cents": self.discount_monthly_cents,
- "annual_price_cents": self.annual_price_cents,
- "monthly_settle_cents": self.monthly_settle_cents,
- "contract_id": self.contract_id,
- "contract_item_id": self.contract_item_id,
- "order_no": self.order_no,
- "replaces_subscription_id": self.replaces_subscription_id,
- })
- }
- /// 同型快照 ⇒ 字段级 diff(§8.1 CU-18:记改了哪些字段+原值→新值)
- fn diff(&self, before: &SubAuditView) -> Value {
- let (b, a) = (before.to_json(), self.to_json());
- let (Some(b), Some(a)) = (b.as_object(), a.as_object()) else {
- return json!([]);
- };
- let mut m = serde_json::Map::new();
- for k in b.keys().chain(a.keys()) {
- if k == "subscription_id" {
- continue;
- }
- let (bv, av) = (b.get(k), a.get(k));
- if bv != av {
- m.insert(k.clone(), json!({ "old": bv, "new": av }));
- }
- }
- Value::Object(m)
- }
- }
- /// 写一条订阅后置审计(§4.11:`write_audit` 是唯一写入口;动作名走 08 册 §8.3 登记表:
- /// `subscription.create`/`subscription.replace`/`subscription.update`/`subscription.delete`)。
- ///
- /// 与其余域同口径:业务短批落库后同请求内补写,⛔ 审计失败把主流程带崩 ⇒ 只回 `audit_written:false`。
- pub(crate) async fn write_sub_audit(
- state: &AppState,
- auth: &bos_scope::AuthContext,
- action: &str,
- subscription_id: &str,
- before: Option<Value>,
- after: Option<Value>,
- detail: Value,
- ) -> bool {
- let ev = bos_platform::audit::AuditEvent {
- actor_user_id: auth.user_id.clone(),
- action: action.to_string(),
- resource_type: "subscription".to_string(),
- resource_id: subscription_id.to_string(),
- before,
- after,
- detail: Some(detail),
- };
- match state.db.write_audit(&ev).await {
- Ok(()) => true,
- Err(e) => {
- tracing::warn!(
- "subscription 后置审计未写入(action={action},subscription_id={subscription_id}):{e}"
- );
- false
- }
- }
- }
- // ───────────────────────── 合同候选 ─────────────────────────
- /// 合同候选的契约空态文案(TC-CU-50 步骤 1 逐字:下拉里出现的就是这一句)
- const CONTRACT_OPTIONS_EMPTY_TEXT: &str = "—(该客户没有可选的未开通合同)";
- /// 合同是否已到期(TC-CU-51 步骤 1:已开通与**已到期**的⛔ 出现在候选里)。
- ///
- /// 一律按**服务端当日**判定(⛔ 信前端传值);日期取前 10 字符(`YYYY-MM-DD`)做字典序比较。
- /// 缺失或形态不可用 ⇒ `false`(⛔ 当成已到期剔除,与 §4.9 `lifecycle()` 的「⛔ 猜」同口径)。
- fn contract_expired(end_date: Option<&String>, today: &str) -> bool {
- let Some(raw) = opt_trim(end_date) else {
- return false;
- };
- let key: String = raw.chars().take(10).collect();
- let b = key.as_bytes();
- b.len() == 10 && b[4] == b'-' && b[7] == b'-' && key.as_str() < today
- }
- /// `POST /subscription/contract_options@v1`。
- ///
- /// 只出「未开通」合同(开通态=开户工单 ∪ 关联订阅 `actual_opened_at`),两级=合同 → 尚未有订阅的
- /// 条目;`custom_spec` 条目带其派生档。⛔ 月结算标准金额出现在本口出参。
- pub async fn contract_options(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionOptionsReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
- return json_err(e);
- }
- let cid = match req_field("customer_id", &body.customer_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // 取数失败⛔ 判成「不可见」(M221 会掩盖故障):可见性只由 `require_customer` 一处给出
- if let Err(e) = require_customer(&state, &auth, &cid).await {
- return json_err(e);
- }
- let contracts = match contracts_of_customer(&state, &cid).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let opened = match opened_map_for(&state, &contracts).await {
- Ok(m) => m,
- Err(e) => return json_err(e),
- };
- // 候选过滤(TC-CU-51 步骤 1):已开通 ⇒ 剔除;**已到期** ⇒ 同样剔除(此前只看 `not_opened`
- // ⇒ 期间已过的合同仍进候选,换一份数据就能建出错订阅=D-68)。到期按服务端当日算。
- let t = today();
- let mut opened_n = 0usize;
- let mut expired_n = 0usize;
- let mut undetermined_n = 0usize;
- let mut free: Vec<&ContractRow> = Vec::new();
- for c in &contracts {
- match opened.get(&c.contract_id) {
- Some(Opened::NotOpened) if contract_expired(c.end_date.as_ref(), &t) => expired_n += 1,
- Some(Opened::NotOpened) => free.push(c),
- Some(_) => opened_n += 1,
- // 开通态取不到=不可判定 ⇒ ⛔ 放进候选(与原先只认 `not_opened` 的保守口径一致)
- None => undetermined_n += 1,
- }
- }
- if free.is_empty() {
- // TC-CU-50 步骤 1:一个都没有 ⇒ 下拉给空态句。空态是**正常结果**、⛔ 错误(写入侧的拦截
- // 仍走 `KLT-M222`),这里回 200 + 机器可读标记 + 契约文案,前端直接渲染空态。
- let reason = if contracts.is_empty() {
- "no_contract"
- } else if opened_n == 0 && undetermined_n == 0 {
- "all_expired"
- } else if expired_n == 0 && undetermined_n == 0 {
- "all_opened"
- } else {
- "all_excluded"
- };
- return json_ok(json!({
- "customer_id": cid,
- "items": [],
- "total": 0,
- "empty_state": true,
- "empty_text": CONTRACT_OPTIONS_EMPTY_TEXT,
- "empty_reason": reason,
- "excluded": {
- "opened": opened_n,
- "expired": expired_n,
- "undetermined": undetermined_n
- },
- "notes": [
- "一期「未开通」=该合同无任何名下订阅(含已取消);已到期合同同样不进候选(TC-CU-51)",
- "到期判定按服务端当日比较合同止期,不采信前端传入的日期",
- "工单侧读口未接线 ⇒ opened_state=unconfigured,本结论仅覆盖「是否已有订阅」+止期"
- ]
- }));
- }
- let ids: Vec<String> = free.iter().map(|c| c.contract_id.clone()).collect();
- let items = match items_of_contracts(&state, &ids).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // 已被订阅引用的条目⛔ 再被选(§5.2「尚未有订阅的条目」)。
- let mut referenced: HashSet<String> = HashSet::new();
- if !ids.is_empty() {
- let mut p = Params::default();
- let in_pred = match push_in_owned(&mut p, "s.contract_id", &ids) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let sql = format!(
- "SELECT s.contract_item_id AS v FROM subscription s \
- WHERE {in_pred} AND s.contract_item_id IS NOT NULL"
- );
- match state.db.query_all::<IdRow>(&sql, p.values()).await {
- Ok(rows) => referenced = rows.into_iter().map(|r| r.v).collect(),
- Err(e) => return json_err(e),
- }
- }
- let plan_ids: Vec<String> = items.iter().filter_map(|i| i.plan_id.clone()).collect();
- let plans = match plan_rows(&state, &plan_ids).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let plan_by_id: HashMap<&str, &PlanRow> = plans.iter().map(|r| (r.plan_id.as_str(), r)).collect();
- let mut out: Vec<Value> = Vec::new();
- for c in free {
- let rows: Vec<Value> = items
- .iter()
- .filter(|i| i.contract_id == c.contract_id && !referenced.contains(&i.item_id))
- .map(|i| {
- let pid = opt_trim(i.plan_id.as_ref());
- let pr = pid.and_then(|id| plan_by_id.get(id)).map(|r| r.to_ref());
- let (available, reason) = match pr.as_ref() {
- Some(pr) => plan_selectability(pr, &cid),
- None => (false, Some("该条目未关联可选档位".to_string())),
- };
- json!({
- "item_id": i.item_id,
- "plan_id": pid,
- "plan_name": pr.as_ref().map(|p| p.plan_name.clone()),
- "item_family": i.item_family,
- // 份数仍在条目上(订阅 `quantity` 由它带入;`addon` 可 > 1,`link` 恒 1)。
- // ⚠️ DB 列经 `as_opt_string` 读成文本;此处必须 `as_opt_num` 下成 JSON 数值,
- // 否则前端原样回填 `/subscription/create@v1` 会被 serde 拒成
- // `invalid type: string "1", expected i64`(D-02 / KLT-S20004)。
- "quantity": as_opt_num(i.quantity.as_deref()),
- // 价格随所引档位(条目上不再有价格列)⇒ 一律从档位投影。
- "annual_price_cents": pr.as_ref().map(|p| p.annual_price_cents),
- "line_exits": exits_json(i.line_exits.as_ref()),
- "available": available,
- "unavailable_reason": reason,
- })
- })
- .collect();
- // D-33:`contract_no` 保持既有前端在用的「外部单号优先」旧口径(⛔ 直接改口径打断前端);
- // 真合同号在 `internal_no`。同客户多份合同共用一个外部单号时下拉会出现同名选项 ⇒
- // 前端下拉改渲染 `option_label`(内部合同号为主、外部单号括注 ⇒ 天然唯一)。
- let option_label = match opt_trim(c.external_no.as_ref()) {
- Some(e) => format!("{}(外部单号 {e})", c.contract_no),
- None => c.contract_no.clone(),
- };
- out.push(json!({
- "contract_id": c.contract_id,
- "contract_no": opt_trim(c.external_no.as_ref()).unwrap_or(c.contract_no.as_str()),
- "internal_no": c.contract_no,
- "external_no": opt_trim(c.external_no.as_ref()),
- "option_label": option_label,
- "status": c.status,
- "end_date": c.end_date,
- "attachment_url": c.attachment_url,
- "opened": false,
- "items": rows,
- }));
- }
- json_ok(json!({
- "customer_id": cid,
- "items": out,
- "total": out.len(),
- "empty_state": false,
- "empty_text": Value::Null,
- "notes": [
- "出参不出现「月结算标准金额」:月结算只在选定档位后由 monthly_settle_of 折算并只读显示。",
- TICKET_UNCONFIGURED_NOTE,
- ],
- "columns_pending": COLUMNS_PENDING,
- }))
- }
- /// `push_in` 的空集保险版(调用方已保证非空,空集=内部错误而非「不过滤」)。
- fn push_in_owned(p: &mut Params, col: &str, ids: &[String]) -> Result<String, BosError> {
- if ids.is_empty() {
- return Err(BosError::internal("push_in_owned 不接受空 ID 集合(空集会退化成不过滤)"));
- }
- Ok(push_in(p, col, ids, "text"))
- }
- // ───────────────────────── 写侧:共用折算 ─────────────────────────
- /// 交付形态:**只读档位**(D-15:条目/订阅都不再是第二来源)。
- ///
- /// 载荷里带了不同值 ⇒ `11103`(⛔ 静默改写);带了同值=确认回显,放行。
- fn family_of(payload: Option<&String>, plan: &PlanRow) -> Result<PlanFamily, BosError> {
- let plan_family = plan.family();
- if let Some(raw) = opt_trim(payload) {
- let got = PlanFamily::parse(raw)?;
- if got != plan_family {
- return Err(BosError::bad_params(format!(
- "plan_family 由套餐带入({}),不改写为 {}",
- plan_family.as_str(),
- got.as_str()
- )));
- }
- }
- Ok(plan_family)
- }
- /// 周期与价格的派生结果(§5.2 段 3/4)。`succession` 公共层共用 ⇒ 字段 `pub(crate)`。
- #[derive(Clone)]
- pub(crate) struct Period {
- pub(crate) term: String,
- pub(crate) start: String,
- pub(crate) end: String,
- pub(crate) annual: i64,
- pub(crate) monthly: i64,
- }
- /// `term` → 起止与年费/月结算的唯一折算点(⛔ 落库月数、⛔ 手工填价、⛔ 手工改到期日)。
- ///
- /// 实现收口在 [`super::succession::derive_period_of`]:合同新建页的逐条替换同样要按档位派生,
- /// 两处共用一份算式(⛔ 各写一套)。
- pub(crate) fn derive_period(
- plan: &PlanRow,
- term_raw: Option<&String>,
- start_raw: Option<&String>,
- contract_end: Option<&str>,
- today: &str,
- price_factor_scaled: i64,
- ) -> Result<Period, BosError> {
- super::succession::derive_period_of(
- plan.annual_price_cents.trim().parse::<i64>().unwrap_or(0),
- plan.monthly(),
- &plan.plan_id,
- term_raw,
- start_raw,
- super::succession::EndMode::TermMonths(contract_end),
- today,
- price_factor_scaled,
- )
- }
- /// 按归一化出口键取目录系数(缺席/空集 ⇒ 默认 1)。
- pub(crate) fn factor_scaled_for_exits(
- map: &std::collections::HashMap<String, i64>,
- exits: &bos_invariant::NormalizedExits,
- ) -> i64 {
- use bos_invariant::PRICE_FACTOR_SCALE;
- exits
- .line_exits
- .first()
- .and_then(|k| map.get(k).copied())
- .filter(|v| *v > 0)
- .unwrap_or(PRICE_FACTOR_SCALE)
- }
- /// 出口集合的解析+归一化(条目优先,缺省取档位;空集合=`KLT-L216`)。
- pub(crate) fn derive_exits(item: Option<&ItemRow>, plan: &PlanRow) -> Result<NormalizedExits, BosError> {
- let raw = match item {
- Some(i) => exits_of(i.line_exits.as_ref(), "合同条目 line_exits")?,
- None => Vec::new(),
- };
- let raw = if raw.is_empty() {
- exits_of(plan.line_exits.as_ref(), "档位 line_exits")?
- } else {
- raw
- };
- if raw.is_empty() {
- return Err(BosError::klt(
- KltCode::L216,
- format!("出口集合为空,不可保存/提交(档位 {} 与所选条目均无线路出口)", plan.plan_id),
- ));
- }
- normalize_line_exits(&raw)
- }
- /// 额度对齐目标(§5.6 唯一求和实现=`in_use_quota_sum_batch`,⛔ 本口另实现一套计数)。
- ///
- /// `extra_plan` = 本次要写入/要摘除的订阅所引档位:`Some` 计入(新订、升降配),
- /// 摘除一行时由调用方先从 `rows` 里剔掉再求和(§5.7 第 6 步回退对齐)。
- pub(crate) async fn quota_target(
- state: &AppState,
- customer_id: &str,
- rows: &[SubRow],
- ) -> Result<i64, BosError> {
- let plan_ids: Vec<String> = rows.iter().filter_map(|r| r.plan_id.clone()).collect();
- let plans = plan_rows(state, &plan_ids).await?;
- let mut quota_of_plan: HashMap<String, i64> = HashMap::new();
- for p in plans {
- if let Some(q) = opt_trim(p.sub_account_quota.as_ref()).and_then(|s| s.trim().parse::<i64>().ok()) {
- quota_of_plan.insert(p.plan_id.clone(), q);
- }
- }
- let pairs: Vec<(&str, &str)> = rows
- .iter()
- .filter(|r| IN_USE_STATUS.contains(&r.status.as_str()))
- .filter_map(|r| {
- r.plan_id
- .as_deref()
- .map(|pid| (r.customer_id.as_str(), pid))
- })
- .collect();
- let sums = in_use_quota_sum_batch(&[customer_id], &pairs, "a_of_plan)?;
- Ok(sums.get(customer_id).copied().unwrap_or(0))
- }
- pub(crate) async fn customer_quota(state: &AppState, customer_id: &str) -> Result<i64, BosError> {
- let mut p = Params::default();
- let c = p.push(Value::String(customer_id.to_string()));
- let sql = format!("SELECT c.quota_cents AS v FROM customer c WHERE c.customer_id = {c}::text");
- Ok(state
- .db
- .query_one::<IdRow>(&sql, p.values())
- .await?
- .map(|r| r.v.trim().parse::<i64>().unwrap_or(0))
- .unwrap_or(0))
- }
- /// 额度对齐语句(§5.7 第 3/6 步:与库里现值不符 ⇒ 以应占额度为准修正)。
- pub(crate) fn quota_stmt(customer_id: &str, target: i64) -> DmlStatement {
- let mut p = Params::default();
- let c = p.push(Value::String(customer_id.to_string()));
- let q = p.push(Value::from(target));
- DmlStatement::new(
- format!(
- "UPDATE customer SET quota_cents = {q}::bigint, updated_at = NOW() WHERE customer_id = {c}::text"
- ),
- p.values().to_vec(),
- )
- }
- /// 额度调整的**业务变更历史**(订单§5.5/客户§2.2:`customer_field_history(field_key='quota')`
- /// 写前后额度;与审计同事务双写、口径不互替)。
- ///
- /// 存在理由(TC-CU-53 步骤 5):此前额度只改 `customer.quota_cents`,客户「归属变更」页
- /// 看不到这次调整,审计也只有订单动作 ⇒ 额度从 0 变 5 在后置校验里查无实据。
- fn quota_history_stmt(customer_id: &str, before: i64, after: i64, actor: &str) -> DmlStatement {
- let mut p = Params::default();
- let id = p.push(Value::String(ops::ids::snowflake().to_string()));
- let c = p.push(Value::String(customer_id.to_string()));
- let o = p.push(Value::String(before.to_string()));
- let n = p.push(Value::String(after.to_string()));
- let a = p.push(Value::String(actor.to_string()));
- DmlStatement::new(
- format!(
- "INSERT INTO customer_field_history (id, customer_id, field_key, old_display, \
- new_display, operator_user_id, changed_at) \
- VALUES ({id}::bigint, {c}::text, 'quota'::text, {o}::text, {n}::text, {a}::text, now())"
- ),
- p.values().to_vec(),
- )
- }
- /// 后置额度对齐结果(`SUB-EFF` 用:订阅§12.1.3 `C44`)。
- pub(crate) struct QuotaAlignOutcome {
- /// `(customer_id, 对齐前, 对齐后)`——只记真正发生写入的客户。
- pub updated: Vec<(String, i64, i64)>,
- /// `(customer_id, 失败原因)`——只失败该客户,其余客户继续。
- pub failed: Vec<(String, String)>,
- }
- /// `SUB-EFF` 后置额度对齐:按客户重算 `customer.quota_cents` 目标值(订阅§5.5/§12.1.3)。
- ///
- /// 入参是**候选集命中的客户**,不是「实际翻转成功」的客户:翻转已提交而对齐失败时,
- /// 下一轮 `changed=0` 仍需重算,否则额度永远偏高且无报错。
- ///
- /// 求和唯一实现=[`in_use_quota_sum_batch`];本函数不自己数订阅、不自己算缺口。
- /// 逐客户调用(⛔ 整批一把),一个客户缺档位额度只失败该客户。
- pub(crate) async fn align_quota_for_customers(
- state: &AppState,
- customer_ids: &[String],
- ) -> Result<QuotaAlignOutcome, BosError> {
- let mut out = QuotaAlignOutcome {
- updated: Vec::new(),
- failed: Vec::new(),
- };
- if customer_ids.is_empty() {
- return Ok(out);
- }
- // 1) 在册在用订阅(额度计入 pending 与 active)+引用档位
- let mut p = Params::default();
- let in_c = push_in(&mut p, "s.customer_id", customer_ids, "text");
- let in_s: Vec<String> = IN_USE_STATUS.iter().map(|s| s.to_string()).collect();
- let in_s = push_in(&mut p, "s.status", &in_s, "text");
- let sql = format!(
- "SELECT s.customer_id, s.plan_id, s.subscription_id, s.quota_slots FROM subscription s \
- WHERE {in_c} AND {in_s} AND s.plan_id IS NOT NULL"
- );
- #[derive(Deserialize)]
- struct SubPlanRow {
- #[serde(deserialize_with = "de::as_string")]
- customer_id: String,
- #[serde(deserialize_with = "de::as_string")]
- plan_id: String,
- #[serde(deserialize_with = "de::as_string")]
- subscription_id: String,
- #[serde(deserialize_with = "de::as_string")]
- quota_slots: String,
- }
- let sub_rows = state.db.query_all::<SubPlanRow>(&sql, p.values()).await?;
- // 2) 档位额度快照(缺列/取不到=该客户失败,⛔ 回落成 0)
- let plan_ids: Vec<String> = sub_rows
- .iter()
- .map(|r| r.plan_id.clone())
- .collect::<HashSet<_>>()
- .into_iter()
- .collect();
- let mut quota_of_plan: HashMap<String, i64> = HashMap::new();
- if !plan_ids.is_empty() {
- let mut pp = Params::default();
- let in_p = push_in(&mut pp, "p.plan_id", &plan_ids, "text");
- let psql = format!(
- "SELECT p.plan_id, p.sub_account_quota FROM catalog_plan p WHERE {in_p}"
- );
- #[derive(Deserialize)]
- struct PlanQuotaRow {
- #[serde(deserialize_with = "de::as_string")]
- plan_id: String,
- #[serde(deserialize_with = "de::as_opt_string")]
- sub_account_quota: Option<String>,
- }
- for row in state.db.query_all::<PlanQuotaRow>(&psql, pp.values()).await? {
- if let Some(q) = opt_trim(row.sub_account_quota.as_ref()).and_then(|v| v.trim().parse::<i64>().ok()) {
- quota_of_plan.insert(row.plan_id, q);
- }
- }
- }
- // 3) 逐客户:现算目标 → 与库值不符才写
- for cid in customer_ids {
- let pairs: Vec<(&str, &str)> = sub_rows
- .iter()
- .filter(|r| r.customer_id == *cid)
- .map(|r| (r.customer_id.as_str(), r.plan_id.as_str()))
- .collect();
- let target = match in_use_quota_sum_batch(&[cid.as_str()], &pairs, "a_of_plan) {
- Ok(mut m) => m.remove(cid.as_str()).unwrap_or(0),
- Err(e) => {
- out.failed.push((cid.clone(), e.to_string()));
- continue;
- }
- };
- let before = match customer_quota(state, cid).await {
- Ok(v) => v,
- Err(e) => {
- out.failed.push((cid.clone(), e.to_string()));
- continue;
- }
- };
- // D-41(需求§4.2)+M4:席位按**订阅**补建(同一客户多份订阅各管各的席位包)。
- // ⛔ 只在「额度发生变化」时才补(主账号晚于订阅开通、上一轮补建失败的订阅,都靠这里
- // 在后续轮次收敛),且**只补不删**(缩减侧只记说明)。失败⛔ 影响额度结论。
- for r in sub_rows.iter().filter(|r| r.customer_id == *cid) {
- let t = r.quota_slots.trim().parse::<i64>().unwrap_or(0);
- let seats = super::sub_provision::align_seats_of(state, &r.subscription_id, t).await;
- if let Some(reason) = &seats.failed {
- out.failed.push((
- cid.clone(),
- format!("订阅 {} 分账号补建:{reason}", r.subscription_id),
- ));
- }
- }
- if before == target {
- continue;
- }
- let stmt = quota_stmt(cid, target);
- match state.db.dml(&stmt.sql, &stmt.params).await {
- Ok(1) => out.updated.push((cid.clone(), before, target)),
- Ok(n) => out.failed.push((
- cid.clone(),
- format!("客户额度对齐命中 {n} 行(≠ 1),按失败记账等下一轮收敛"),
- )),
- Err(e) => out.failed.push((cid.clone(), e.to_string())),
- }
- }
- Ok(out)
- }
- /// 组装新订阅 INSERT 的列与占位值(无条件/条件插共用)。
- fn insert_cols_vals(v: &NewValues, p: &mut Params) -> (Vec<&'static str>, Vec<String>) {
- let ph = |p: &mut Params, val: Value, cast: &str| -> String {
- let s = p.push(val);
- if cast.is_empty() {
- s
- } else {
- format!("{s}::{cast}")
- }
- };
- let mut cols: Vec<&str> = vec![
- "subscription_id",
- "customer_id",
- "status",
- "plan_id",
- "plan_name",
- "plan_kind",
- "plan_owner_customer_id",
- "plan_family",
- "sub_mode",
- "line_exits",
- "line_exit_key",
- "term",
- "start_date",
- "end_date",
- "annual_price_cents",
- "monthly_settle_cents",
- "quota_slots",
- "quantity",
- ];
- let mut vals: Vec<String> = vec![
- ph(p, Value::String(v.subscription_id.clone()), "text"),
- ph(p, Value::String(v.customer_id.clone()), "text"),
- ph(p, Value::String(v.status.clone()), "text"),
- ph(p, Value::String(v.plan_id.clone()), "text"),
- ph(p, Value::String(v.plan_name.clone()), "text"),
- ph(p, Value::String(v.plan_kind.clone()), "text"),
- ph(
- p,
- v.plan_owner_customer_id.clone().map(Value::String).unwrap_or(Value::Null),
- "text",
- ),
- ph(p, Value::String(v.plan_family.clone()), "text"),
- ph(p, v.sub_mode.clone().map(Value::String).unwrap_or(Value::Null), "text"),
- ph(p, v.line_exits.clone(), "text::jsonb"),
- ph(p, Value::String(v.line_exit_key.clone()), "text"),
- ph(p, Value::String(v.term.clone()), "text"),
- ph(p, Value::String(v.start_date.clone()), "date"),
- ph(p, Value::String(v.end_date.clone()), "date"),
- ph(p, Value::from(v.annual_price_cents), "bigint"),
- ph(p, Value::from(v.monthly_settle_cents), "bigint"),
- ph(p, Value::from(v.quota_slots), "int"),
- ph(p, Value::from(v.quantity), "int"),
- ];
- if let Some(cid) = v.contract_id.as_ref() {
- cols.push("contract_id");
- vals.push(ph(p, Value::String(cid.clone()), "text"));
- }
- if let Some(iid) = v.contract_item_id.as_ref() {
- cols.push("contract_item_id");
- vals.push(ph(p, Value::String(iid.clone()), "text"));
- }
- if let Some(t) = v.trial_months {
- cols.push("trial_months");
- vals.push(ph(p, Value::from(t), "int"));
- }
- if let Some(d) = v.discount_monthly_cents {
- cols.push("discount_monthly_cents");
- vals.push(ph(p, Value::from(d), "bigint"));
- }
- if let Some(rid) = v.replaces_subscription_id.as_ref() {
- cols.push("replaces_subscription_id");
- vals.push(ph(p, Value::String(rid.clone()), "text"));
- }
- if let Some(pid) = v.parent_subscription_id.as_ref() {
- cols.push("parent_subscription_id");
- vals.push(ph(p, Value::String(pid.clone()), "text"));
- }
- (cols, vals)
- }
- /// 新订阅行 INSERT(六项快照+派生价格;`order_no`/`actual_opened_at` 由工单竣工回传,本轮留空)。
- pub(crate) fn insert_stmt(v: &NewValues) -> DmlStatement {
- let mut p = Params::default();
- let (cols, vals) = insert_cols_vals(v, &mut p);
- DmlStatement::new(
- format!(
- "INSERT INTO subscription ({}) VALUES ({})",
- cols.join(", "),
- vals.join(", ")
- ),
- p.values().to_vec(),
- )
- }
- /// 升降配替换专用:仅当截原已落地(原行 `expired` 且 `end_date=prev_end`)才插入新订阅。
- ///
- /// UDS 短批原子提交但**不因前句 0 行中止**(见 `uds.rs`);无条件 INSERT 会在错 `row_version`
- /// 时仍落新行(D-03)。条件插与工单侧「条件写+条件插」同法——截原失败 ⇒ INSERT 0 行。
- pub(crate) fn insert_replacement_stmt(v: &NewValues, orig_id: &str, prev_end: &str) -> DmlStatement {
- let mut p = Params::default();
- let (cols, vals) = insert_cols_vals(v, &mut p);
- let orig = p.push(Value::String(orig_id.to_string()));
- let cust = p.push(Value::String(v.customer_id.clone()));
- let prev = p.push(Value::String(prev_end.to_string()));
- DmlStatement::new(
- format!(
- "INSERT INTO subscription ({}) SELECT {} WHERE EXISTS (\
- SELECT 1 FROM subscription s \
- WHERE s.subscription_id = {orig}::text \
- AND s.customer_id = {cust}::text \
- AND s.status = 'expired' \
- AND s.end_date = {prev}::date)",
- cols.join(", "),
- vals.join(", ")
- ),
- p.values().to_vec(),
- )
- }
- /// 首次引用打点(§5.2 第 4 步:同事务打点=引用冻结的生效点,⛔ 提交后异步补写)。
- ///
- /// ⚠️ 写侧影响行数恒为 1:早期写的是 `… WHERE plan_id = $1 AND first_referred_at IS NULL`,
- /// 同一档位被**第二份**订阅引用时该语句命中 0 行,[`assert_batch`] 便判「打点=0(期望 1)」
- /// 并回 `KLT-S20007`——而短批已原子提交(新订阅早已落库),调用方看到失败却查得到数据。
- /// ⇒ 用 `COALESCE(first_referred_at, NOW())`:已打点的档位写回原值(⛔ 追溯改首次引用时间),
- /// 命中行数恒为 1,语义仍是「首次引用时刻」。
- pub(crate) fn first_referred_stmt(plan_id: &str) -> DmlStatement {
- let mut p = Params::default();
- let a = p.push(Value::String(plan_id.to_string()));
- DmlStatement::new(
- format!(
- "UPDATE catalog_plan SET first_referred_at = COALESCE(first_referred_at, NOW()) \
- WHERE plan_id = {a}::text"
- ),
- p.values().to_vec(),
- )
- }
- /// 待写入的新订阅行(已折算完全部派生值)。
- #[derive(Clone)]
- pub(crate) struct NewValues {
- /// 服务端发号(`SUB-{6位}`);[`insert_stmt`] 的 `subscription_id` 列靠它落库。
- pub(crate) subscription_id: String,
- pub(crate) customer_id: String,
- pub(crate) status: String,
- pub(crate) plan_id: String,
- pub(crate) plan_name: String,
- pub(crate) plan_kind: String,
- pub(crate) plan_owner_customer_id: Option<String>,
- pub(crate) plan_family: String,
- /// 历史列:三分类收敛后新行恒 `None`(I6 停用,不再派生订阅方式)。
- pub(crate) sub_mode: Option<String>,
- pub(crate) line_exits: Value,
- pub(crate) line_exit_key: String,
- pub(crate) term: String,
- pub(crate) start_date: String,
- pub(crate) end_date: String,
- pub(crate) annual_price_cents: i64,
- pub(crate) monthly_settle_cents: i64,
- pub(crate) quota_slots: i64,
- /// 订阅份数(2026-11-17):可叠加档可 > 1,其余恒 1。
- pub(crate) quantity: i64,
- pub(crate) contract_id: Option<String>,
- pub(crate) contract_item_id: Option<String>,
- pub(crate) trial_months: Option<i64>,
- pub(crate) discount_monthly_cents: Option<i64>,
- pub(crate) replaces_subscription_id: Option<String>,
- /// 附加订阅的父订阅(D-2/D-9):`link` 恒空;`addon` 必填(库上 `ck_sub_parent` 兜底)。
- pub(crate) parent_subscription_id: Option<String>,
- }
- /// 发号(`SUB-000123`,与 customer/import_batch 的发号器同一张表)。
- pub(crate) async fn new_subscription_id(state: &AppState) -> Result<String, BosError> {
- let year = chrono::Local::now()
- .format("%Y")
- .to_string()
- .parse::<i32>()
- .map_err(|e| BosError::internal(format!("取当年年份失败:{e}")))?;
- let n = next_seq(state.db.as_ref(), "subscription", "subscription", year).await?;
- Ok(format!("SUB-{n:06}"))
- }
- /// 六步短批的事后自检(UDS ⛔ 批内条件中止 ⇒ 只能事后核影响行数并如实点名)。
- pub(crate) fn assert_batch(results: &[bos_platform::clients::uds::DmlStatementResult], want: &[(&str, u64)]) -> Result<(), BosError> {
- let hit = |i: usize| results.get(i).and_then(|r| r.affected_rows).unwrap_or(0);
- let mut bad: Vec<String> = Vec::new();
- for (i, (label, n)) in want.iter().enumerate() {
- if hit(i) != *n {
- bad.push(format!("{label}={}(期望 {n})", hit(i)));
- }
- }
- if bad.is_empty() {
- return Ok(());
- }
- Err(BosError::internal(format!(
- "写侧短批影响行数异常:{};整批已原子提交,须人工核对",
- bad.join(";")
- )))
- }
- /// 写入后的统一回读出参。
- async fn row_out(
- state: &AppState,
- sub_id: &str,
- op: &str,
- notes: Vec<String>,
- extra: Value,
- ) -> Result<Value, BosError> {
- let mut p = Params::default();
- let s = p.push(Value::String(sub_id.to_string()));
- let sql = format!("{SELECT_COLS} FROM subscription s WHERE s.subscription_id = {s}::text");
- let r = state
- .db
- .query_one::<SubRow>(&sql, p.values())
- .await?
- .ok_or_else(|| {
- BosError::internal(format!("写入后回读未在册:订阅 {sub_id}(短批已提交,须人工核对)"))
- })?;
- let names = pairs_by(state.db.as_ref(), "customer", "customer_id", "customer_name", &[r.customer_id.clone()]).await?;
- let contract_no = match opt_trim(r.contract_id.as_ref()) {
- Some(cid) => contract_row(state, cid)
- .await?
- .map(|c| opt_trim(c.external_no.as_ref()).unwrap_or(c.contract_no.as_str()).to_string()),
- None => None,
- };
- let t = today();
- let mut v = to_json(
- &r,
- names.get(&r.customer_id).and_then(|x| x.first()).map(String::as_str),
- contract_no.as_deref(),
- &t,
- );
- v["op"] = json!(op);
- v["notes"] = json!(notes);
- v["columns_pending"] = json!(COLUMNS_PENDING);
- if let Some(obj) = extra.as_object() {
- for (k, val) in obj {
- v[k.clone()] = val.clone();
- }
- }
- Ok(v)
- }
- async fn row_out_resp(state: &AppState, sub_id: &str, op: &str, notes: Vec<String>, extra: Value) -> Response {
- match row_out(state, sub_id, op, notes, extra).await {
- Ok(v) => json_ok(v),
- Err(e) => json_err(e),
- }
- }
- // ───────────────────────── 写侧:新订 ─────────────────────────
- /// 附加订阅的父订阅解析(D-2/D-9)。
- ///
- /// 两条来源,按 `item_mode` 分:
- /// 1. `increment`(增量合同)⇒ 条目自带的 `ref_subscription_id`(可属**另一份合同**);
- /// 2. 普通附加条目 ⇒ `serves_item_id` 指向本合同里的 `link` 条目,再找该条目落成的 `link` 订阅
- /// (由台账先建;本合同可能还没建,则本条报错,而不是建一条无父的附加订阅)。
- ///
- /// 三条硬口径(与库层 `ck_sub_parent` 互补):同客户 ∧ 父为 `link` ∧ 父**在期**
- /// (`status IN ('pending','active')` ∧ 未过结束日)。⛔ 校验「父子同合同」——D-9 明确父可跨合同。
- async fn resolve_parent_sub(
- state: &AppState,
- customer_id: &str,
- item: Option<&ItemRow>,
- items: &[ItemRow],
- today: &str,
- ) -> Result<String, BosError> {
- #[derive(Deserialize)]
- struct P {
- #[serde(deserialize_with = "de::as_string")]
- subscription_id: String,
- #[serde(default, deserialize_with = "de::as_opt_string")]
- family: Option<String>,
- #[serde(default, deserialize_with = "de::as_opt_string")]
- status: Option<String>,
- #[serde(default, deserialize_with = "de::as_opt_string")]
- customer_id: Option<String>,
- #[serde(default, deserialize_with = "de::as_opt_string")]
- end_date: Option<String>,
- }
- let item = item.ok_or_else(|| {
- BosError::klt(
- KltCode::M228,
- "附加订阅必须有父订阅:请求未关联合同条目,无从解析父链路(D-2)",
- )
- })?;
- let mode = opt_trim(item.item_mode.as_ref()).unwrap_or("new");
- let rid = if mode == "increment" {
- opt_trim(item.ref_subscription_id.as_ref())
- .ok_or_else(|| {
- BosError::klt(
- KltCode::M228,
- format!("条目 {} 是增量条目,但未填引用订阅号(D-9)", item.item_id),
- )
- })?
- .to_string()
- } else {
- let pid = opt_trim(item.serves_item_id.as_ref()).ok_or_else(|| {
- BosError::klt(
- KltCode::M228,
- format!("附加条目 {} 未选父条目(D-7),无法确定父订阅", item.item_id),
- )
- })?;
- if !items.iter().any(|i| i.item_id == pid) {
- return Err(BosError::klt(
- KltCode::M228,
- format!("附加条目 {} 的父条目 {pid} 不在本合同内", item.item_id),
- ));
- }
- // 父条目落成的 `link` 订阅(可能有多条,取结束日最晚的一条在期行)。
- let sql = "SELECT subscription_id::text AS subscription_id FROM subscription \
- WHERE customer_id = $1::text AND contract_item_id = $2::text \
- AND plan_family = 'link' AND status IN ('pending', 'active') \
- ORDER BY end_date DESC NULLS LAST LIMIT 1";
- let hit = state
- .db
- .query_one::<P>(
- sql,
- &[
- Value::String(customer_id.to_string()),
- Value::String(pid.to_string()),
- ],
- )
- .await?;
- let Some(h) = hit else {
- return Err(BosError::klt(
- KltCode::M228,
- format!("父条目 {pid} 还没有对应的跨境链路订阅:请先建父链路订阅,再建附加订阅(D-2)"),
- ));
- };
- h.subscription_id
- };
- let row = state
- .db
- .query_one::<P>(
- "SELECT subscription_id::text AS subscription_id, coalesce(plan_family, '')::text AS family, \
- coalesce(status, '')::text AS status, coalesce(customer_id, '')::text AS customer_id, \
- coalesce(end_date::text, '')::text AS end_date FROM subscription \
- WHERE subscription_id = $1::text LIMIT 1",
- &[Value::String(rid.clone())],
- )
- .await?
- .ok_or_else(|| BosError::klt(KltCode::M228, format!("父订阅 {rid} 不存在(D-9)")))?;
- if row.customer_id.as_deref() != Some(customer_id) {
- return Err(BosError::klt(
- KltCode::M228,
- format!(
- "父订阅 {rid} 属客户 {},与本客户不同(D-9)",
- row.customer_id.unwrap_or_default()
- ),
- ));
- }
- if row.family.as_deref() != Some("link") {
- return Err(BosError::klt(
- KltCode::M228,
- format!("父订阅 {rid} 的交付形态不是 link:附加订阅只能挂在跨境链路上(D-9)"),
- ));
- }
- let st = row.status.unwrap_or_default();
- if st != "pending" && st != "active" {
- return Err(BosError::klt(
- KltCode::M228,
- format!("父订阅 {rid} 状态为「{st}」,不在期(D-9)"),
- ));
- }
- if row.end_date.as_deref().is_some_and(|d| !d.is_empty() && d < today) {
- return Err(BosError::klt(
- KltCode::M228,
- format!("父订阅 {rid} 已过结束日,不在期(D-9)"),
- ));
- }
- Ok(rid)
- }
- /// `POST /subscription/create@v1`(§5.2 五步前置校验 + 六步事务)。
- pub async fn create(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionCreateReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
- return json_err(e);
- }
- if let Err(e) = reject_read_only(&body.rest, &CREATE_READ_ONLY) {
- return json_err(e);
- }
- // ① 客户(必填)
- let cid = match req_field("customer_id", &body.customer_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // ② 可见性 ⇒ KLT-M221
- let customer_name = match require_customer(&state, &auth, &cid).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // ③ 合同与条目
- let pid = match req_field("plan_id", &body.plan_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let contract_id = match body
- .contract_id
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- {
- Some(v) => v.to_string(),
- None => {
- return json_err(BosError::bad_params(
- "请选择合同编号:订单必须引用该客户已登记且未开通的合同",
- ))
- }
- };
- let contract = match contract_row(&state, &contract_id).await {
- Ok(Some(c)) => c,
- Ok(None) => {
- return json_err(BosError::klt(
- KltCode::M222,
- format!("载荷里的合同 {contract_id} 不在册,本客户没有可承接的「未开通」合同"),
- ))
- }
- Err(e) => return json_err(e),
- };
- if contract.customer_id != cid {
- return json_err(BosError::klt(
- KltCode::M221,
- format!(
- "载荷里的合同 {contract_id} 归属客户 {},与本订阅客户 {cid} 不同(I12b)",
- contract.customer_id
- ),
- ));
- }
- if let Err(e) = check_i12b_same_customer(Some(&contract.customer_id), &cid) {
- return json_err(e);
- }
- match opened_map_for(&state, std::slice::from_ref(&contract)).await {
- Ok(m) => match m.get(&contract_id) {
- Some(Opened::Opened) => {
- return json_err(BosError::klt(
- KltCode::M223,
- format!("合同 {contract_id} 已开通,不再新增订阅(补录走合同侧「变更重开」)"),
- ))
- }
- Some(Opened::NotOpened) => {}
- None => {
- return json_err(BosError::klt(
- KltCode::S406,
- format!("合同 {contract_id} 的开通态不可判定(不当成未开通放行)"),
- ))
- }
- },
- Err(e) => return json_err(e),
- }
- let item_id = opt_trim(body.contract_item_id.as_ref()).map(str::to_string);
- let items = match items_of_contracts(&state, &[contract_id.clone()]).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let item = match item_id.as_ref() {
- Some(iid) => match items.iter().find(|i| &i.item_id == iid) {
- Some(i) => Some(i),
- None => {
- return json_err(BosError::klt(
- KltCode::M228,
- format!("条目 {iid} 不是合同 {contract_id} 的服务构成条目(档位不可选)"),
- ))
- }
- },
- // 合同内一条匹配条目都没有时合同仍可选,出口由操作人在合同内任选 ⇒ 本轮允许空(§5.2 末段)。
- None => None,
- };
- if let Some(i) = item {
- if let Some(ip) = opt_trim(i.plan_id.as_ref()) {
- if ip != pid {
- return json_err(BosError::klt(
- KltCode::M228,
- format!("条目 {} 关联档位 {ip},与所选档位 {pid} 不匹配", i.item_id),
- ));
- }
- }
- }
- let plan = match plan_row(&state, &pid).await {
- Ok(Some(p)) => p,
- Ok(None) => {
- return json_err(BosError::klt(
- KltCode::M228,
- format!("档位 {pid} 不在册,档位不可选"),
- ))
- }
- Err(e) => return json_err(e),
- };
- let t = today();
- let pr = plan.to_ref();
- let (selectable, unavail) = plan_selectability(&pr, &cid);
- if !selectable {
- return json_err(BosError::klt(
- KltCode::M228,
- format!(
- "档位不可选:{}",
- unavail.unwrap_or_else(|| "未指明原因".to_string())
- ),
- ));
- }
- if let Err(e) = check_plan_available(Some(&pr), &cid) {
- return json_err(e);
- }
- // I12b 已在上方按**合同**判过(合同与客户同属);档位侧只需要「自定义档归属本客户」
- // ——该判据在 [`check_plan_available`] 内(固定档 `owner_customer_id` 为空属正常,
- // ⛔ 拿它当 I12b 的输入:固定档会被误判成「合同不存在」)。
- let exits = match derive_exits(item, &plan) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let factor_map = match super::line_exit::price_factor_map(state.db.as_ref()).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let price_factor_scaled = factor_scaled_for_exits(&factor_map, &exits);
- // ④ 价格与周期(全部服务端派生;年价/月标准先乘出口系数)
- let period = match derive_period(
- &plan,
- body.term.as_ref(),
- body.start_date.as_ref(),
- opt_trim(contract.end_date.as_ref()),
- &t,
- price_factor_scaled,
- ) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let family = match family_of(body.plan_family.as_ref(), &plan) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // ⑤ 父订阅(D-2/D-9):附加订阅必挂一条**在期链路**,父可属另一份合同。
- // `increment` 条目直接引用既有链路订阅;普通附加条目走它在本合同里的父条目 →
- // 父条目对应的 `link` 订阅(由台账先建)。`link` 恒无父(库上 `ck_sub_parent` 兜底)。
- let parent_subscription_id = match family {
- PlanFamily::Addon => match resolve_parent_sub(&state, &cid, item, &items, &t).await {
- Ok(v) => Some(v),
- Err(e) => return json_err(e),
- },
- PlanFamily::Link => None,
- };
- if let Err(e) = check_i13_trial_months(body.trial_months, body.discount_monthly_cents) {
- return json_err(e);
- }
- // 份数(D-8 `ck_sub_qty`):`link` 恒 1(一条链路=一份),`addon` 1~9999。
- let quantity = match body.quantity {
- None => 1,
- Some(q) => q,
- };
- if !family.quantity_ok(quantity) {
- return json_err(BosError::bad_params(format!(
- "档位 {} 的交付形态为「{}」,份数必须是{}(收到 {quantity})",
- plan.plan_id,
- family.as_str(),
- if family == PlanFamily::Link { " 1" } else { " 1~9999" }
- )));
- }
- let id = match new_subscription_id(&state).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let nv = NewValues {
- subscription_id: id.clone(),
- customer_id: cid.clone(), status: subscription_status_of(&period.start, &period.end, &t).as_str().to_string(),
- plan_id: plan.plan_id.clone(),
- plan_name: plan.plan_name.clone(),
- plan_kind: plan.plan_kind.clone(),
- plan_owner_customer_id: opt_trim(plan.customer_id.as_ref()).map(str::to_string),
- plan_family: family.as_str().to_string(),
- sub_mode: None,
- line_exits: Value::Array(exits.line_exits.iter().cloned().map(Value::String).collect()),
- line_exit_key: exits.line_exit_key.clone(),
- term: period.term.clone(),
- start_date: period.start.clone(),
- end_date: period.end.clone(),
- annual_price_cents: period.annual,
- monthly_settle_cents: period.monthly,
- // 额度贡献=档位额度 × 份数(与合同写口同口径),额度求和仍只读 `quota_slots`。
- quota_slots: pr.sub_account_quota.saturating_mul(quantity),
- quantity,
- contract_id: Some(contract_id.clone()),
- contract_item_id: item_id.clone(),
- trial_months: body.trial_months,
- discount_monthly_cents: body.discount_monthly_cents,
- replaces_subscription_id: None,
- parent_subscription_id: parent_subscription_id.clone(),
- };
- // 额度对齐目标=在册在用行 + 本行
- let mut for_quota = match subs_of_customer(&state, &cid).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- for_quota.push(SubRowPlaceholder::for_new(&id, &nv));
- let target = match quota_target(&state, &cid, &for_quota).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let before = match customer_quota(&state, &cid).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // D-08:写库前校验承接团队含即将生成的交付类型,避免订阅成功却静默漏单。
- match ops::handlers::open_gen::predict_delivery_type(state.db.as_ref(), &cid, false).await {
- Ok(tt) => {
- if let Err(e) = ops::handlers::open_gen::assert_team_accepts_type(state.db.as_ref(), &cid, tt).await {
- return json_err(e);
- }
- }
- Err(e) => return json_err(e),
- }
- let mut stmts: Vec<DmlStatement> = Vec::new();
- stmts.push(insert_stmt(&nv));
- stmts.push(first_referred_stmt(&pid));
- if before != target {
- stmts.push(quota_stmt(&cid, target));
- stmts.push(quota_history_stmt(&cid, before, target, &auth.user_id));
- }
- let results = match state.db.dml_batch(&stmts).await {
- Ok(r) => r,
- Err(e) => return json_err(e),
- };
- let mut want: Vec<(&str, u64)> = vec![
- ("新订阅 INSERT", 1),
- ("catalog_plan.first_referred_at 打点", 1),
- ];
- if before != target {
- want.push(("客户额度对齐", 1));
- want.push(("客户额度变更历史", 1));
- }
- if let Err(e) = assert_batch(&results, &want) {
- return json_err(e);
- }
- let mut notes: Vec<String> = vec![
- TICKET_UNCONFIGURED_NOTE.to_string(),
- "order_no/actual_opened_at 由开户工单竣工回传回填,本轮新建留空(§5.2)。".to_string(),
- format!(
- "年订阅价格按订阅时长 {} 折算为 {} 分,月结算标准金额={} 分(monthly_settle_of 唯一折算点)。",
- period.term, period.annual, period.monthly
- ),
- ];
- if item_id.is_none() {
- notes.push(
- "本订阅未关联合同条目(合同内无匹配条目时出口按档位自身出口落库),合同开通态一栏显示「—」。"
- .to_string(),
- );
- }
- // 工单§3.2.3 时点 1/2/3+§7.5(D-35/D-42):订阅保存=开户/服务开通工单的唯一宿主,
- // 建单在保存动作内同步完成(作业册§12.1.6 段 1 ⛔ 异步补偿)。工单侧失败⛔ 回滚
- // 已提交的订阅(工单§3.1 第二条),只把原因如实写回 `notes`+`delivery_ticket`(⛔ 静默)。
- let delivery = match auth.user_id.trim().parse::<i64>() {
- Ok(actor) => {
- ops::handlers::open_gen::run(
- &state.db,
- &ops::handlers::open_gen::SubTicketInput {
- customer_id: cid.clone(),
- subscription_id: id.clone(),
- // 计划执行日=本订阅的服务开始日(合同开始日/台账填的未来日)。
- start_date: nv.start_date.clone(),
- plan_name: nv.plan_name.clone(),
- line_exits: exits.line_exits.clone(),
- quota_slots: pr.sub_account_quota,
- actor_user_id: actor,
- original: None,
- // 附加订阅(D-2/D-9):父订阅随建单下传,决定并入父单还是只出服务开通单。
- parent_subscription_id: parent_subscription_id.clone(),
- // 订阅台账「新增订阅」没有任何续签来源 ⇒ 无从判定「服务内容未变」。
- service_unchanged: false,
- // D-11:运营商订单号一合同一号,取所挂合同的 `external_no`。
- carrier_order_no: contract.external_no.clone(),
- },
- )
- .await
- }
- Err(_) => ops::handlers::open_gen::GenOutcome::delivery_skipped(format!(
- "当前登录账号 ID 非数字({}),不写入工单的提交人(bigint)⇒ 本次未生成交付工单,\
- 请到工单台人工补发(工单§3.2.3 时点 1/2/3)。",
- auth.user_id
- )),
- };
- notes.push(delivery.note.clone());
- // D-41(需求§4.2/客户册§5.2):订阅保存=额度变更落点,分账号由系统按套餐额度**自动补建**
- // (⛔ 手工新增)。与交付工单同一形态:订阅主档先提交,补建在其后同步执行,失败⛔ 回滚
- // 已提交的订阅,只把原因如实写回 `notes`+审计 `detail_json.sub_accounts`(⛔ 静默)。
- let seats = super::sub_provision::align_seats_of(&state, &id, nv.quota_slots).await;
- notes.push(seats.note());
- // 后置审计 `subscription.create`(08 册 §8.1 CU-17/§8.3):此前该动作在 `bos_audit_log` 里
- // 0 行=D-25。`before_json` 新增时为空;额度前后、两个金额与折算来源、order_no 冻结事实照记。
- let after_view = SubAuditView::of_row(&SubRowPlaceholder::for_new(&id, &nv)).to_json();
- let detail = json!({
- "layout": "multi",
- "plan_id": nv.plan_id,
- "plan_name_snapshot": nv.plan_name,
- "plan_family": nv.plan_family,
- "sub_mode": nv.sub_mode,
- "line_exits": nv.line_exits,
- "line_exit_key": nv.line_exit_key,
- "term": nv.term,
- "start_date": nv.start_date,
- "end_date": nv.end_date,
- "annual_price_cents": nv.annual_price_cents,
- "monthly_settle_cents": nv.monthly_settle_cents,
- "amount_source": "annual 取所选口径价,monthly 由 monthly_settle_of 唯一折算点得出",
- "quota_slots_before": before,
- "quota_slots_target": target,
- "quota_change": {
- "field": "quota_cents",
- "before": before,
- "after": target,
- "written": before != target,
- "history_key": if before != target { Some("quota") } else { None },
- },
- "contract_id": nv.contract_id,
- "contract_item_id": nv.contract_item_id,
- "item_matched": item_id.is_some(),
- "delivery_ticket": delivery.to_json(),
- "sub_accounts": seats.to_json(),
- "order_no_note": "order_no 录入即冻结 ⇒ 新建留空,由开户工单竣工回传回填",
- "replaces_subscription_id": nv.replaces_subscription_id,
- });
- let audit_written = write_sub_audit(
- &state,
- &auth,
- "subscription.create",
- &id,
- None,
- Some(after_view),
- detail,
- )
- .await;
- row_out_resp(
- &state,
- &id,
- "created",
- notes,
- json!({
- "audit_written": audit_written,
- "customer_name": customer_name,
- "delivery_ticket": delivery.to_json(),
- "quota_align": { "before": before, "target": target, "written": before != target },
- "derived": {
- "term": period.term,
- "start_date": period.start,
- "end_date": period.end,
- "annual_price_cents": period.annual,
- "monthly_settle_cents": period.monthly,
- "line_exit_key": exits.line_exit_key,
- "plan_family": family.as_str(),
- },
- }),
- )
- .await
- }
- /// 客户在册且在可见范围内 ⇒ 回客户名;越权或不在册=`KLT-M221`。
- pub(crate) async fn require_customer(
- state: &AppState,
- auth: &bos_scope::AuthContext,
- customer_id: &str,
- ) -> Result<String, BosError> {
- customer_visible(state, auth, customer_id)
- .await?
- .ok_or_else(|| {
- BosError::klt(
- KltCode::M221,
- format!("客户不存在或超出当前账号可见范围:{customer_id}"),
- )
- })
- }
- // ───────────────────────── 写侧:升降配 ─────────────────────────
- /// 原订阅已被换过的次数(`replaces_subscription_id` 唯一 ⇒ ≥1 即⛔ 再换)。
- pub(crate) async fn replacement_count(state: &AppState, origin_id: &str) -> Result<i64, BosError> {
- let mut p = Params::default();
- let a = p.push(Value::String(origin_id.to_string()));
- let sql = format!(
- "SELECT COUNT(1) AS c FROM subscription r WHERE r.replaces_subscription_id = {a}::text"
- );
- Ok(state
- .db
- .query_one::<CountRow>(&sql, p.values())
- .await?
- .map(|r| r.c.trim().parse::<i64>().unwrap_or(0))
- .unwrap_or(0))
- }
- /// `POST /subscription/change@v1`(§5.3)。
- ///
- /// 客户/合同/条目/用途分类全部沿用或跟随新档位(载荷出现即 `11103`);
- /// ⛔ 出口一致性校验(分类与出口均随档位变,拦截等于禁止换分类);I6 照常(`KLT-M224`)。
- pub async fn change(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionChangeReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
- return json_err(e);
- }
- if let Err(e) = reject_read_only(&body.rest, &CHANGE_READ_ONLY) {
- return json_err(e);
- }
- let rid = match req_field("replaces_subscription_id", &body.replaces_subscription_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let orig = match scoped_sub(&state, &auth, &rid).await {
- Ok(Some(c)) => c,
- Ok(None) => {
- return json_err(BosError::not_found(format!(
- "原订阅不存在或超出当前账号可见范围:{rid}"
- )))
- }
- Err(e) => return json_err(e),
- };
- let t = today();
- let (key, label, _) = status_display(&orig, &t);
- if key != "pending" && key != "active" {
- return json_err(BosError::bad_params(format!(
- "原订阅 {rid} 状态={label}({key}),不升降配(§5.3)"
- )));
- }
- match replacement_count(&state, &rid).await {
- Ok(0) => {}
- Ok(k) => {
- return json_err(BosError::klt(
- KltCode::M226,
- format!("原订阅 {rid} 已被升降配换过 {k} 次:replaces_subscription_id 至多被指向一次"),
- ))
- }
- Err(e) => return json_err(e),
- }
- let cid = orig.customer_id.clone();
- // 契约 `/subscription/change@v1`:`contract_id` 为必填「新合同」(不得沿用原合同),
- // `contract_item_id` 为新合同条目。缺省时回退到原订阅合同(兼容旧调用与「同合同换档」)。
- if let Some(given) = opt_trim(body.customer_id.as_ref()) {
- if given != cid {
- return json_err(BosError::klt(
- KltCode::M221,
- format!("载荷客户 {given} 与原订阅客户 {cid} 不同:升降配不换客户(§5.3)"),
- ));
- }
- }
- let (contract_id, reused_contract) = match opt_trim(body.contract_id.as_ref()) {
- Some(c) => (c.to_string(), false),
- None => match opt_trim(orig.contract_id.as_ref()) {
- Some(c) => (c.to_string(), true),
- None => {
- return json_err(BosError::klt(
- KltCode::M221,
- format!("原订阅 {rid} 未关联合同,且载荷未给 contract_id:升降配须引用新合同"),
- ))
- }
- },
- };
- let contract = match contract_row(&state, &contract_id).await {
- Ok(Some(c)) => c,
- Ok(None) => {
- return json_err(BosError::klt(
- KltCode::M222,
- format!("载荷里的合同 {contract_id} 不在册,升降配不承接"),
- ))
- }
- Err(e) => return json_err(e),
- };
- if contract.customer_id != cid {
- return json_err(BosError::klt(
- KltCode::M221,
- format!(
- "载荷里的合同 {contract_id} 归属客户 {},与原订阅客户 {cid} 不同(I12b)",
- contract.customer_id
- ),
- ));
- }
- if let Err(e) = check_i12b_same_customer(Some(&contract.customer_id), &cid) {
- return json_err(e);
- }
- let pid = match req_field("plan_id", &body.plan_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let plan = match plan_row(&state, &pid).await {
- Ok(Some(p)) => p,
- Ok(None) => {
- return json_err(BosError::klt(KltCode::M228, format!("新档位 {pid} 不在册,档位不可选")))
- }
- Err(e) => return json_err(e),
- };
- let pr = plan.to_ref();
- if let (_, Some(reason)) = plan_selectability(&pr, &cid) {
- return json_err(BosError::klt(KltCode::M228, format!("档位不可选:{reason}")));
- }
- if let Err(e) = check_plan_available(Some(&pr), &cid) {
- return json_err(e);
- }
- // I12b 的判据是「**合同**与客户同属一个客户」,上面已按 `contract.customer_id` 校验过(§5.3)。
- // 此处⛔ 再拿「**档位**归属客户」过一次 I12b:固定档 `catalog_plan.customer_id` 为空是正常
- // 形态(平台通用档),空归属落进 `None` 分支会被报成「合同不存在」(60005),
- // ⇒ 所有固定档的升降配恒失败(缺陷 D-73)。自定义档的归属约束已由
- // [`plan_selectability`]+[`check_plan_available`](I11:自定义档只能被归属它的客户订阅)覆盖。
- // 条目:载荷给了 `contract_item_id` 就按它取(并校验档位匹配),否则按新档位在合同内反查。
- let items = match items_of_contracts(&state, &[contract_id.clone()]).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let item = match opt_trim(body.contract_item_id.as_ref()) {
- Some(iid) => match items.iter().find(|i| i.item_id == iid) {
- Some(i) => {
- let bound = opt_trim(i.plan_id.as_ref());
- if let Some(ip) = bound {
- if ip != pid {
- return json_err(BosError::klt(
- KltCode::M228,
- format!("条目 {iid} 关联档位 {ip},与所选档位 {pid} 不匹配"),
- ));
- }
- }
- Some(i)
- }
- None => {
- return json_err(BosError::klt(
- KltCode::M228,
- format!("条目 {iid} 不是合同 {contract_id} 的服务构成条目(档位不可选)"),
- ))
- }
- },
- None => items.iter().find(|i| opt_trim(i.plan_id.as_ref()) == Some(pid.as_str())),
- };
- // 交付形态只读档位(载荷⛔ 带 plan_family)。
- let family = plan.family();
- if let Err(e) = check_i13_trial_months(body.trial_months, body.discount_monthly_cents) {
- return json_err(e);
- }
- let exits = match derive_exits(item, &plan) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // I6/额度按**最终态**判一次(§5.3):剔除原订阅、加入新订阅后再复检。
- // 候选集必须**排除被替换的原订阅**:升降配正是「用新行顶掉原行」,原行本就还在库里,
- // ⛔ 把它算进「同分类×同出口已有一份」——旧写法让任何一次升降配都被自己的原行拦下
- // (KLT-M224/60217「请在该行点『升降配』」,而用户点的正是升降配;缺陷 D-74)。
- let existing = match subs_of_customer(&state, &cid).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let id = match new_subscription_id(&state).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let factor_map = match super::line_exit::price_factor_map(state.db.as_ref()).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let exits_for_factor = match derive_exits(item, &plan) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let pin = super::succession::PlanInput {
- plan: &plan,
- item,
- contract_id: &contract_id,
- contract_end: opt_trim(contract.end_date.as_ref()),
- term: body.term.as_ref(),
- start_date: body.start_date.as_ref(),
- trial_months: body.trial_months,
- discount_monthly_cents: body.discount_monthly_cents,
- row_version: body.row_version,
- // 升降配替换只承接 `link` 订阅(叠加服务随父),故无父。
- parent_subscription_id: None,
- mode: super::succession::MatchMode::FollowPlan,
- price_factor_scaled: factor_scaled_for_exits(&factor_map, &exits_for_factor),
- };
- let planned = match super::succession::plan_change(&state, &cid, &orig, &id, &pin, &t, "").await
- {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let planned_once = std::slice::from_ref(&planned);
- let nv = planned.new.clone();
- let period = planned.period.clone();
- let prev_end = planned.prev_end.clone();
- let same_day_cut = planned.same_day_cut;
- let target =
- match super::succession::quota_target_final(&state, &cid, &existing, planned_once, &[])
- .await
- {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let before = match customer_quota(&state, &cid).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- // D-08:写库前校验承接团队含即将生成的交付类型。
- let original_delivered = orig
- .actual_opened_at
- .as_deref()
- .is_some_and(|s| !s.trim().is_empty());
- match ops::handlers::open_gen::predict_delivery_type(state.db.as_ref(), &cid, original_delivered)
- .await
- {
- Ok(tt) => {
- if let Err(e) =
- ops::handlers::open_gen::assert_team_accepts_type(state.db.as_ref(), &cid, tt).await
- {
- return json_err(e);
- }
- }
- Err(e) => return json_err(e),
- }
- let mut stmts: Vec<DmlStatement> = super::succession::change_dml(&planned);
- let has_quota = before != target;
- if has_quota {
- stmts.push(quota_stmt(&cid, target));
- }
- // M4:席位先改挂到新订阅(0 行=原订阅本就没有席位,属正常)——放在断言语句之后,
- // ⛔ 计入 `assert_batch` 的期望行数。
- stmts.push(super::succession::seat_migration_stmt(
- &planned.orig.subscription_id,
- &planned.new.subscription_id,
- ));
- // D-2「父替换 ⇒ 子改挂」:附加子订阅的父指针改到新订阅(0 行=原订阅无叠加服务)。
- stmts.push(super::succession::reparent_children_stmt(
- &planned.orig.subscription_id,
- &planned.new.subscription_id,
- ));
- let results = match state.db.dml_batch(&stmts).await {
- Ok(r) => r,
- Err(e) => return json_err(e),
- };
- let mut want: Vec<(&str, u64)> = super::succession::CHANGE_DML_LABELS
- .iter()
- .map(|s| (*s, 1))
- .collect();
- if has_quota {
- want.push(("客户额度对齐", 1));
- }
- if let Err(e) = assert_batch(&results, &want) {
- // ⛔ 把任何行数异常都冒充成「乐观锁冲突」:只有**截原**落空才是 §5.3 的前置不符
- let cut_rows = results.first().and_then(|r| r.affected_rows).unwrap_or(0);
- if cut_rows == 0 {
- return json_err(BosError::klt(
- KltCode::M225,
- format!("承接的原订阅 {rid} 状态已变更(原订阅未能截原),请重新加载该行后再试"),
- ));
- }
- return json_err(e);
- }
- let mut notes: Vec<String> = vec![
- TICKET_UNCONFIGURED_NOTE.to_string(),
- "不做出口一致性校验(§5.3:分类与出口均随档位变,拦截等于禁止换分类),本轮未做该校验。"
- .to_string(),
- format!(
- "年订阅价格按订阅时长 {} 折算为 {} 分,月结算标准金额={} 分;原订阅结束日截到 {prev_end}。",
- period.term, period.annual, period.monthly
- ),
- ];
- if reused_contract {
- notes.push(format!(
- "本轮未给 contract_id,沿用原订阅合同 {contract_id}(契约建议另签新合同后再升降配)。"
- ));
- } else if orig.contract_id.as_deref() != Some(contract_id.as_str()) {
- notes.push(format!(
- "承接合同由 {} 换为 {contract_id}(新订单引用新合同,原合同保留为历史)。",
- orig.contract_id.clone().unwrap_or_else(|| "(空)".to_string())
- ));
- }
- if same_day_cut {
- notes.push(format!(
- "原订阅生效日 {} 不早于新生效日前一日,截原结束日钳到 {prev_end}(同日承接,原订阅保留生效当日)。",
- orig.start_date.clone().unwrap_or_else(|| "(空)".to_string())
- ));
- }
- // 工单§3.2.3 时点 3:升降配=「在用客户新增订阅」⇒ 生成服务开通工单(无开停记录),
- // 与新建同宿主、同形态(P5-D3:此前升降配只写「未接线」提示、0 张工单)。
- let delivery = match auth.user_id.trim().parse::<i64>() {
- Ok(actor) => {
- ops::handlers::open_gen::run(
- &state.db,
- &ops::handlers::open_gen::SubTicketInput {
- customer_id: cid.clone(),
- subscription_id: id.clone(),
- // 升降配的执行日=新订阅的服务开始日(新档位生效日)。
- start_date: period.start.clone(),
- plan_name: nv.plan_name.clone(),
- line_exits: exits.line_exits.clone(),
- quota_slots: pr.sub_account_quota,
- actor_user_id: actor,
- original: Some(super::succession::original_sub(&state, &orig).await),
- parent_subscription_id: None,
- // 台账升降配=服务内容变了。
- service_unchanged: false,
- // D-11:升降配承接的新合同号(号随合同,⛔ 沿用原订阅的冻结号)。
- carrier_order_no: contract.external_no.clone(),
- },
- )
- .await
- }
- Err(_) => ops::handlers::open_gen::GenOutcome::delivery_skipped(format!(
- "当前登录账号 ID 非数字({}),不写入工单的提交人(bigint)⇒ 本次未生成交付工单,\
- 请到工单台人工补发(工单§3.2.3 时点 3)。",
- auth.user_id
- )),
- };
- notes.push(delivery.note.clone());
- // D-41(需求§4.2):升降配=额度变更落点。升配侧按新额度补建席位;降配侧**只补不删**,
- // 超出的席位⛔ 删号(随到期停机转停用),差异如实写回 `notes`+审计 `detail_json.sub_accounts`。
- let seats = super::sub_provision::align_seats_of(&state, &id, nv.quota_slots).await;
- notes.push(seats.note());
- // 后置审计 `subscription.replace`(08 册 §8.1 CU-17/§8.3=`pair` 版式:原订阅 `end_date`
- // 与 `status` 记原值→新值,另记原/新合同编号)。此前升降配全程 0 行审计。
- let before_view = SubAuditView::of_row(&orig).to_json();
- let after_view = SubAuditView::of_row(&SubRowPlaceholder::for_new(&id, &nv)).to_json();
- let detail = json!({
- "layout": "pair",
- "replaces_subscription_id": rid.clone(),
- "origin_contract_id": orig.contract_id.clone(),
- "new_contract_id": contract_id.clone(),
- "old_end_date": { "old": orig.end_date.clone(), "new": prev_end.clone() },
- "old_status": { "old": orig.status.clone(), "new": "expired" },
- "new_plan_id": nv.plan_id.clone(),
- "new_plan_name": nv.plan_name.clone(),
- "line_exits": nv.line_exits.clone(),
- "annual_price_cents": nv.annual_price_cents,
- "monthly_settle_cents": nv.monthly_settle_cents,
- "quota_slots_before": before,
- "quota_slots_target": target,
- "sub_accounts": seats.to_json(),
- "exit_check_note": "不做出口一致性校验(§5.3)⇒ 本轮未做,如实记",
- });
- let audit_written = write_sub_audit(
- &state,
- &auth,
- "subscription.replace",
- &id,
- Some(before_view),
- Some(after_view),
- detail,
- )
- .await;
- row_out_resp(
- &state,
- &id,
- "changed",
- notes,
- json!({
- "audit_written": audit_written,
- "replaces_subscription_id": rid,
- "quota_align": { "before": before, "target": target, "written": before != target },
- "derived": {
- "term": period.term,
- "start_date": period.start,
- "end_date": period.end,
- "annual_price_cents": period.annual,
- "monthly_settle_cents": period.monthly,
- "line_exit_key": exits.line_exit_key,
- "plan_family": family.as_str(),
- "contract_id": contract_id,
- "contract_item_id": nv.contract_item_id,
- },
- }),
- )
- .await
- }
- /// 升降配额度对齐用的行占位(把 [`NewValues`] 折算成一行「将来在册」的订阅行)。
- pub(crate) struct SubRowPlaceholder;
- impl SubRowPlaceholder {
- pub(crate) fn for_new(id: &str, v: &NewValues) -> SubRow {
- SubRow {
- subscription_id: id.to_string(),
- customer_id: v.customer_id.clone(),
- contract_id: v.contract_id.clone(),
- contract_item_id: v.contract_item_id.clone(),
- plan_id: Some(v.plan_id.clone()),
- plan_name: Some(v.plan_name.clone()),
- plan_kind: Some(v.plan_kind.clone()),
- plan_owner_customer_id: v.plan_owner_customer_id.clone(),
- status: v.status.clone(),
- plan_family: Some(v.plan_family.clone()),
- sub_mode: v.sub_mode.clone(),
- line_exits: None,
- line_exit_key: Some(v.line_exit_key.clone()),
- start_date: Some(v.start_date.clone()),
- end_date: Some(v.end_date.clone()),
- term: Some(v.term.clone()),
- trial_months: v.trial_months.map(|x| x.to_string()),
- discount_monthly_cents: v.discount_monthly_cents.map(|x| x.to_string()),
- annual_price_cents: Some(v.annual_price_cents.to_string()),
- monthly_settle_cents: Some(v.monthly_settle_cents.to_string()),
- quota_slots: v.quota_slots.to_string(),
- quantity: v.quantity.to_string(),
- parent_subscription_id: v.parent_subscription_id.clone(),
- replaces_subscription_id: v.replaces_subscription_id.clone(),
- order_no: None,
- actual_opened_at: None,
- early_stopped_at: None,
- effective_date: None,
- expire_date: None,
- created_at: String::new(),
- row_version: String::new(),
- }
- }
- }
- // ═══════════════════════════ §5.7 修改(白名单两列) ═══════════════════════════
- /// 修改载荷:白名单只有 `trial_months` + `discount_monthly_cents`(§5.7)。
- ///
- /// 换套餐/换合同 ⇒ `KLT-M229`(改订走升降配承接或先停用再新开);其余键 ⇒ `11103`
- /// 逐一点名(⛔ 静默忽略=把「改了结束日」当成一次成功的修改)。
- fn reject_update_payload(rest: &Map<String, Value>) -> Result<(), BosError> {
- let m229: Vec<&str> = UPDATE_M229_KEYS
- .iter()
- .copied()
- .filter(|k| rest.contains_key(*k))
- .collect();
- if !m229.is_empty() {
- return Err(BosError::klt(
- KltCode::M229,
- format!(
- "修改不换套餐/换合同({}):改订一律走「升降配承接」或「先服务停用再新开」(§5.7)",
- m229.join("、")
- ),
- ));
- }
- let mut keys: Vec<&str> = rest
- .keys()
- .map(String::as_str)
- .filter(|k| !UPDATE_WHITELIST.contains(k))
- .collect();
- if keys.is_empty() {
- return Ok(());
- }
- keys.sort_unstable();
- Err(BosError::bad_params(format!(
- "修改白名单只有 {},以下键不受理:{}",
- UPDATE_WHITELIST.join("/"),
- keys.join("、")
- )))
- }
- /// `POST /subscription/update@v1`(§5.7)。
- pub async fn update(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionUpdateReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
- return json_err(e);
- }
- if let Err(e) = reject_update_payload(&body.rest) {
- return json_err(e);
- }
- let sid = match req_field("subscription_id", &body.subscription_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let r = match scoped_sub(&state, &auth, &sid).await {
- Ok(Some(v)) => v,
- Ok(None) => {
- return json_err(BosError::not_found(format!(
- "订阅不存在或超出当前账号可见范围:{sid}"
- )))
- }
- Err(e) => return json_err(e),
- };
- let t = today();
- let (key, label, _) = status_display(&r, &t);
- if key != "pending" && key != "active" {
- return json_err(BosError::bad_params(format!(
- "订阅 {sid} 状态={label},不修改(§5.7:到期/已替换/已退订只读)"
- )));
- }
- // I13 用**改后**的试用/优惠期组合判(本口只改这两列=唯一能碰 I13 的写入口)
- let cur_trial = as_opt_num(r.trial_months.as_deref()).as_i64();
- let cur_disc = as_opt_num(r.discount_monthly_cents.as_deref()).as_i64();
- let trial = body.trial_months.or(cur_trial);
- let disc = body.discount_monthly_cents.or(cur_disc);
- if let Err(e) = check_i13_trial_months(trial, disc) {
- return json_err(e);
- }
- let mut p = Params::default();
- let set: Vec<String> = vec![
- format!(
- "trial_months = {}::int",
- p.push(trial.map(Value::from).unwrap_or(Value::Null))
- ),
- format!(
- "discount_monthly_cents = {}::bigint",
- p.push(disc.map(Value::from).unwrap_or(Value::Null))
- ),
- "row_version = row_version + 1".to_string(),
- "updated_at = NOW()".to_string(),
- ];
- // 乐观锁:`row_version` 进谓词(UDS ⛔ 行锁能力,条件更新是唯一防线)
- let preds: Vec<String> = vec![
- format!("subscription_id = {}::text", p.push(Value::String(sid.clone()))),
- format!("row_version = {}::int", p.push(Value::from(body.row_version))),
- format!("status = {}::text", p.push(Value::String(r.status.clone()))),
- ];
- let sql = format!(
- "UPDATE subscription SET {} {}",
- set.join(", "),
- p.where_clause(&preds)
- );
- let affected = match state.db.dml(&sql, p.values()).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- if affected == 0 {
- return json_err(BosError::klt(
- KltCode::S407,
- format!("订阅 {sid} 已被他人改动(row_version 不符),请重新加载后重试(§5.7)"),
- ));
- }
- let notes: Vec<String> = vec![
- format!(
- "本轮修改列={};订阅时长/结束日/两个金额不可改(§5.7)。",
- UPDATE_WHITELIST.join("/")
- ),
- TICKET_UNCONFIGURED_NOTE.to_string(),
- ];
- // 后置审计 `subscription.update`(08 册 §8.1 CU-18/§8.3=`diff` 版式):只记改了哪些列+
- // 原值→新值,并如实记「结束日/两个金额⛔ 经本口改动」。此前编辑订阅 0 行审计=D-25。
- let before_view = SubAuditView::of_row(&r);
- let mut after_view = before_view.clone();
- after_view.trial_months = trial;
- after_view.discount_monthly_cents = disc;
- let detail = json!({
- "layout": "diff",
- "fields": after_view.diff(&before_view),
- "whitelist": UPDATE_WHITELIST,
- "end_date_untouched": true,
- "annual_price_untouched": true,
- "monthly_settle_untouched": true,
- "i13_checked": true,
- });
- let audit_written = write_sub_audit(
- &state,
- &auth,
- "subscription.update",
- &sid,
- Some(before_view.to_json()),
- Some(after_view.to_json()),
- detail,
- )
- .await;
- row_out_resp(
- &state,
- &sid,
- "updated",
- notes,
- json!({
- "audit_written": audit_written,
- "updated_fields": UPDATE_WHITELIST,
- "row_version": body.row_version + 1,
- "trial_months": trial,
- "discount_monthly_cents": disc,
- }),
- )
- .await
- }
- // ═══════════════════════════ §5.5 删除前检查与删除 ═══════════════════════════
- /// 删除阻塞(§5.5 两栏)=账单明细 + 变更链。
- ///
- /// 账单明细只读口本轮未接线 ⇒ [`CrossRead::Unconfigured`](按登记回落值=「无账单」),
- /// 出参**必须**说明该回落⛔ 构成「无阻塞结论」;变更链=本订阅作为**原订阅**被指向的行。
- async fn delete_blocks(state: &AppState, r: &SubRow) -> Result<SubscriptionBlocks, BosError> {
- let mut p = Params::default();
- let a = p.push(Value::String(r.subscription_id.clone()));
- let sql = format!(
- "SELECT s.subscription_id AS v FROM subscription s \
- WHERE s.replaces_subscription_id = {a}::text ORDER BY s.subscription_id"
- );
- let rows = state.db.query_all::<IdRow>(&sql, p.values()).await?;
- let chain: Vec<String> = rows.into_iter().map(|x| x.v).collect();
- check_subscription_deletable(&CrossRead::<bool>::Unconfigured, &[], &chain)
- }
- /// 在期附加子订阅(D-2 生命周期:**父删 ⇒ 有在期子的父不可删**)。
- ///
- /// 「在期」按库里的 `status` 取 `pending`/`active`:删除闸门不推导日期态(到期行可删是
- /// 既有口径),子订阅只要没进真终态就还在履约,父一删它就会变成没有父的 `addon`
- /// (`parent_subscription_id` 悬空,`ck_sub_parent` 只保证非空、不保证父还在)。
- async fn live_children(state: &AppState, parent_id: &str) -> Result<Vec<String>, BosError> {
- let mut p = Params::default();
- let a = p.push(Value::String(parent_id.to_string()));
- let sql = format!(
- "SELECT s.subscription_id AS v FROM subscription s \
- WHERE s.parent_subscription_id = {a}::text \
- AND s.status IN ('pending', 'active') ORDER BY s.subscription_id"
- );
- let rows = state.db.query_all::<IdRow>(&sql, p.values()).await?;
- Ok(rows.into_iter().map(|x| x.v).collect())
- }
- /// 真终态(已退订/被承接)⛔ 任何写操作。
- ///
- /// ⚠️「到期」**⛔** 算这里的闸门:删除的阻塞按 05 册 §5.6 只有两类(已产生账单明细
- /// ⇒`KLT-M227`/被 `replaces_subscription_id` 指为变更链原订阅⇒`KLT-M230`),
- /// 03 册 §5.2「当前可否编辑」=权限 ∧ 未被替代 ∧ 删除预检——到期本身⛔ 是判据
- /// (13 册回滚场景「订阅建错且未出账 ⇒ `delete_check` → 删除」正是到期行可删的正例)。
- fn terminal_guard(r: &SubRow, today: &str, op: &str) -> Result<(String, String), BosError> {
- let (key, label, _) = status_display(r, today);
- if key == "cancelled" || key == "replaced" || key == "early_stopped" {
- return Err(BosError::bad_params(format!(
- "订阅 {} 状态={label},不允许{op}(已退订/被承接/提前停机=真终态,只读)",
- r.subscription_id
- )));
- }
- Ok((key, label))
- }
- /// `POST /subscription/delete_check@v1`:删除弹窗的两栏阻塞(账单明细 + 变更链)。
- pub async fn delete_check(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionIdReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
- return json_err(e);
- }
- let sid = match req_field("subscription_id", &body.subscription_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let r = match scoped_sub(&state, &auth, &sid).await {
- Ok(Some(v)) => v,
- Ok(None) => {
- return json_err(BosError::not_found(format!(
- "订阅不存在或超出当前账号可见范围:{sid}"
- )))
- }
- Err(e) => return json_err(e),
- };
- let blocks = match delete_blocks(&state, &r).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let children = match live_children(&state, &sid).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let t = today();
- let (key, label, _) = status_display(&r, &t);
- let mut status_blocks: Vec<String> = if key == "pending" || key == "active" {
- Vec::new()
- } else {
- vec![format!("状态={label},不删除(§5.7)")]
- };
- // D-2 生命周期:有在期附加子订阅的父不可删(先停子或整链路停用)。
- if !children.is_empty() {
- status_blocks.push(format!(
- "该订阅下还有 {} 条在期附加子订阅({}),父删会让子订阅失去归属(D-2);\
- 请先停用子订阅或整链路做服务停用",
- children.len(),
- children.join("、")
- ));
- }
- let mut notes: Vec<String> = vec![format!(
- "{BILLING_UNCONFIGURED_NOTE}本次检查**未取得**「无账单阻塞」结论。"
- )];
- notes.extend(blocks.note.clone());
- json_ok(json!({
- "subscription_id": r.subscription_id,
- "can_delete": status_blocks.is_empty(),
- "status": key,
- "status_label": label,
- "blocks": {
- "billing_details": blocks.billing_details,
- "change_chain": blocks.change_chain,
- "live_children": children,
- },
- "status_blocks": status_blocks,
- "billing_state": "unconfigured",
- "notes": notes,
- }))
- }
- /// `POST /subscription/delete@v1`:删除 + 第 6 步额度回退(同一批语句)。
- pub async fn delete(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionIdReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
- return json_err(e);
- }
- let sid = match req_field("subscription_id", &body.subscription_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let r = match scoped_sub(&state, &auth, &sid).await {
- Ok(Some(v)) => v,
- Ok(None) => {
- return json_err(BosError::not_found(format!(
- "订阅不存在或超出当前账号可见范围:{sid}"
- )))
- }
- Err(e) => return json_err(e),
- };
- let t = today();
- if let Err(e) = terminal_guard(&r, &t, "删除") {
- return json_err(e);
- }
- // 阻塞复算(⛔ 让前端只靠 delete_check 的结论下单:两次调用之间状态可能已变)
- if let Err(e) = delete_blocks(&state, &r).await {
- return json_err(e);
- }
- // D-2 生命周期:有在期子的父不可删(与 delete_check 同源复算)。
- match live_children(&state, &sid).await {
- Ok(v) if !v.is_empty() => {
- return json_err(BosError::klt(
- KltCode::M230,
- format!(
- "订阅 {sid} 下还有 {} 条在期附加子订阅({}),父删会让子订阅失去归属(D-2):\
- 请先停用子订阅或整链路做服务停用",
- v.len(),
- v.join("、")
- ),
- ));
- }
- Ok(_) => {}
- Err(e) => return json_err(e),
- }
- // §5.7 第 6 步:额度回退=剔除本行后重算应占额度(升降配不重复计入由求和口径自然保证)
- let rest_rows: Vec<SubRow> = match subs_of_customer(&state, &r.customer_id).await {
- Ok(v) => v.into_iter().filter(|x| x.subscription_id != sid).collect(),
- Err(e) => return json_err(e),
- };
- let target = match quota_target(&state, &r.customer_id, &rest_rows).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let before = match customer_quota(&state, &r.customer_id).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let mut p = Params::default();
- let preds: Vec<String> = vec![
- format!("subscription_id = {}::text", p.push(Value::String(sid.clone()))),
- format!("status = {}::text", p.push(Value::String(r.status.clone()))),
- ];
- let mut stmts: Vec<DmlStatement> = vec![DmlStatement::new(
- format!("DELETE FROM subscription {}", p.where_clause(&preds)),
- p.values().to_vec(),
- )];
- if before != target {
- stmts.push(quota_stmt(&r.customer_id, target));
- }
- let results = match state.db.dml_batch(&stmts).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let mut want: Vec<(&str, u64)> = vec![("订阅行 DELETE", 1)];
- if stmts.len() > 1 {
- want.push(("客户额度回退", 1));
- }
- if let Err(e) = assert_batch(&results, &want) {
- return json_err(e);
- }
- let mut notes: Vec<String> = vec![
- format!(
- "{BILLING_UNCONFIGURED_NOTE}本次删除**未取得**「无账单阻塞」结论,需在只读口接线后复核。"
- ),
- "档位 `catalog_plan.first_referred_at` 打点不回滚(§5.7:引用事实不可逆,档位不回到可下架)。"
- .to_string(),
- format!(
- "额度按「应占额度」对齐:删除前 {before} 分,应占 {target} 分,释放 {} 分。",
- before - target
- ),
- ];
- // D-41(需求§4.2):删除订阅=额度缩减侧 ⇒ 分账号**只补不删**,超出的席位一行不删(随到期
- // 停机转停用),只把「为什么不删」如实写回 `notes`+审计 `detail_json.sub_accounts`。
- let seats = super::sub_provision::align_seats_of(&state, &r.subscription_id, 0).await;
- notes.push(seats.note());
- // 后置审计 `subscription.delete`(08 册 §8.1 CU-19/§8.3):真删 ⇒ `before_json` 记完整关键字段
- // 快照、`after_json` 为空;额度前后/释放值、账单口径未接线声明、打点不回滚声明照记。
- let detail = json!({
- "layout": "multi",
- "quota_before": before,
- "quota_target": target,
- "quota_released": before - target,
- "sub_accounts": seats.to_json(),
- "plan_id": r.plan_id,
- "plan_name_snapshot": r.plan_name,
- "contract_id": r.contract_id,
- "order_no": r.order_no,
- "billing_note": BILLING_UNCONFIGURED_NOTE.to_string(),
- "first_referred_at_note": "catalog_plan.first_referred_at 打点不回滚(引用事实不可逆)",
- });
- let audit_written = write_sub_audit(
- &state,
- &auth,
- "subscription.delete",
- &sid,
- Some(SubAuditView::of_row(&r).to_json()),
- None,
- detail,
- )
- .await;
- json_ok(json!({
- "deleted": true,
- "audit_written": audit_written,
- "subscription_id": sid,
- "quota_released": before - target,
- "quota_align": { "before": before, "target": target, "written": before != target },
- "notes": notes,
- }))
- }
- // ═══════════════════════ §5.6/§5.7 列表:get_list 与 list_all 共用一份实现 ═══════════════════════
- /// 列表的**唯一**查询实现(§5.1「不为两个页面写两套查询——一旦分叉,计数同源迟早破」)。
- ///
- /// 两个入口只差入参:订阅管理页 `customer_id` 必填;全部订阅页客户可选、可跨客户、
- /// 可带区域筛选(区域经 `dim_node_ancestor` 展开成客户集合,⛔ 本册表带区域列)。
- /// 订阅的出账聚合(详情页四卡:应收合计/已出账/未出账/累计成本)。
- ///
- /// 取数真源(第 6 册):
- /// * 应收合计/累计成本/期次数=`billing_receivable` 按 `subscription_id` 求和
- /// (`receivable_cents`/`cost_deduct_cents`);
- /// * 已出账金额=`bill_detail.share_base_cents` 中**已执行批次**且明细未作废(`status='active'`)
- /// 的合计(与账单明细页同一谓词);
- /// * 未出账=应收合计 − 已出账(不足 0 按 0,异常差额由明细页核对)。
- ///
- /// 无应收行 ⇒ 四值回 `null` + `state="no_receivable"`(⛔ 回 0 冒充「没有钱」);有行 ⇒
- /// `state="ok"`。⛔ 回连 `catalog_plan`/`contract` 现价推算。
- async fn billing_summary(
- state: &AppState,
- ids: &[String],
- ) -> Result<HashMap<String, Value>, BosError> {
- let mut out: HashMap<String, Value> = HashMap::new();
- if ids.is_empty() {
- return Ok(out);
- }
- let mut recv: HashMap<String, (i64, i64, i64)> = HashMap::new();
- let mut billed: HashMap<String, i64> = HashMap::new();
- let mut p = Params::default();
- let in_pred = push_in(&mut p, "subscription_id", ids, "text");
- let q_in = push_in(&mut p, "d.subscription_id", ids, "text");
- // UDS 收拢:应收聚合 + 已出账 原 2 跳 → 1 条 UNION ALL。
- // ⚠️ 聚合函数与左括号之间留空格(额度求和断言不误触)。
- let sql = format!(
- "SELECT 'recv' AS kind, subscription_id AS k, \
- COALESCE(SUM (receivable_cents), 0)::text AS a, \
- COALESCE(SUM (cost_deduct_cents), 0)::text AS b, COUNT(1)::text AS c \
- FROM billing_receivable WHERE {in_pred} GROUP BY subscription_id \
- UNION ALL \
- SELECT 'billed' AS kind, d.subscription_id AS k, \
- COALESCE(SUM (d.share_base_cents), 0)::text AS a, '' AS b, '' AS c \
- FROM bill_detail d JOIN reconcile_batch b ON b.batch_no = d.batch_no \
- WHERE {q_in} AND d.status = 'active' AND b.status = 'executed' \
- GROUP BY d.subscription_id"
- );
- for r in state.db.query_all::<Value>(&sql, p.values()).await? {
- let kind = r.get("kind").and_then(Value::as_str).unwrap_or_default();
- let k = r.get("k").and_then(Value::as_str).unwrap_or_default().to_string();
- if k.is_empty() {
- continue;
- }
- let parse = |key: &str| {
- r.get(key).and_then(|v| match v {
- Value::String(s) => s.trim().parse::<i64>().ok(),
- other => other.as_i64(),
- }).unwrap_or(0)
- };
- match kind {
- "recv" => {
- recv.insert(k, (parse("a"), parse("b"), parse("c")));
- }
- "billed" => {
- billed.insert(k, parse("a"));
- }
- _ => {}
- }
- }
- for id in ids {
- let v = match recv.get(id) {
- None => json!({
- "state": "no_receivable",
- "receivable_cents": Value::Null,
- "billed_cents": Value::Null,
- "unbilled_cents": Value::Null,
- "cost_cents": Value::Null,
- "periods": 0,
- }),
- Some((receivable, cost, periods)) => {
- let b = billed.get(id).copied().unwrap_or(0);
- json!({
- "state": "ok",
- "receivable_cents": receivable,
- "billed_cents": b,
- "unbilled_cents": (*receivable - b).max(0),
- "cost_cents": cost,
- "periods": periods,
- })
- }
- };
- out.insert(id.clone(), v);
- }
- Ok(out)
- }
- /// 订阅列表展示名回填(客户名 + 合同编号)单 UDS。
- async fn sub_list_names(
- db: &bos_platform::clients::uds::UdsClient,
- customer_ids: &[String],
- contract_ids: &[String],
- ) -> Result<(HashMap<String, Vec<String>>, HashMap<String, Vec<String>>), BosError> {
- let mut names: HashMap<String, Vec<String>> = HashMap::new();
- let mut contract_nos: HashMap<String, Vec<String>> = HashMap::new();
- if customer_ids.is_empty() && contract_ids.is_empty() {
- return Ok((names, contract_nos));
- }
- let mut p = Params::default();
- let mut parts = Vec::new();
- if !customer_ids.is_empty() {
- let in_pred = push_in(&mut p, "customer_id", customer_ids, "text");
- parts.push(format!(
- "SELECT 'c' AS kind, customer_id AS k, customer_name AS v FROM customer WHERE {in_pred}"
- ));
- }
- if !contract_ids.is_empty() {
- let in_pred = push_in(&mut p, "k.contract_id", contract_ids, "text");
- parts.push(format!(
- "SELECT 'k' AS kind, k.contract_id AS k, \
- COALESCE(NULLIF(k.external_no, ''), k.contract_no) AS v \
- FROM contract k WHERE {in_pred}"
- ));
- }
- #[derive(Deserialize)]
- struct Row {
- #[serde(deserialize_with = "de::as_string")]
- kind: String,
- #[serde(deserialize_with = "de::as_string")]
- k: String,
- #[serde(deserialize_with = "de::as_string")]
- v: String,
- }
- for r in db.query_all::<Row>(&parts.join(" UNION ALL "), p.values()).await? {
- match r.kind.as_str() {
- "c" => names.entry(r.k).or_default().push(r.v),
- "k" => {
- if !r.v.trim().is_empty() {
- contract_nos.entry(r.k).or_default().push(r.v);
- }
- }
- _ => {}
- }
- }
- Ok((names, contract_nos))
- }
- async fn list_records(
- state: &AppState,
- auth: &bos_scope::AuthContext,
- body: &SubscriptionListReq,
- customer_required: bool,
- // `list_all` 台账页不展示出账四卡 ⇒ 跳过 `billing_summary`(Wave B:业务跳 4→3);
- // `get_list`/详情仍要随行下发。
- include_billing: bool,
- ) -> Result<Value, BosError> {
- let mut unknown: Vec<&str> = body.rest.keys().map(String::as_str).collect();
- if !unknown.is_empty() {
- unknown.sort_unstable();
- return Err(BosError::bad_params(format!(
- "不支持的检索条件:{}(可用 keyword/status/plan_kind/line_exit/expiring_within_days/\
- customer_id/contract_id/region_ids/page/page_size)",
- unknown.join("、")
- )));
- }
- let cid = opt_trim(body.customer_id.as_ref());
- if customer_required && cid.is_none() {
- return Err(BosError::bad_params(
- "customer_id 必填:订阅管理页按客户列出该客户的全部订阅(§5.1)",
- ));
- }
- let t = today();
- let mut p = Params::default();
- let mut w: Vec<String> = vec![customer_scope_pred(state, auth, &mut p, "s.customer_id").await?];
- if let Some(c) = cid {
- w.push(format!("s.customer_id = {}::text", p.push(Value::String(c.to_string()))));
- }
- if let Some(regions) = opt_region_ids(body.region_ids.as_ref()) {
- let ids = customers_under_regions(state, regions).await?;
- w.push(push_in(&mut p, "s.customer_id", &ids, "text"));
- }
- // 关键字需 JOIN 客户名/合同号 ⇒ FROM 带 LEFT JOIN(仅筛选时也 JOIN,口径单一)。
- let need_kw_join = opt_trim(body.keyword.as_ref()).is_some();
- if let Some(k) = p.push_like(opt_trim(body.keyword.as_ref())) {
- w.push(format!(
- "(s.plan_name LIKE {k} OR s.subscription_id LIKE {k} \
- OR COALESCE(s.order_no, '') LIKE {k} \
- OR COALESCE(cu.customer_name, '') LIKE {k} \
- OR COALESCE(ct.contract_no, '') LIKE {k} \
- OR COALESCE(ct.external_no, '') LIKE {k})"
- ));
- }
- if let Some(ct) = opt_trim(body.contract_id.as_ref()) {
- w.push(format!("s.contract_id = {}::text", p.push(Value::String(ct.to_string()))));
- }
- if let Some(pk) = opt_trim(body.plan_kind.as_ref()) {
- match pk {
- "fixed" | "custom" => {
- w.push(format!(
- "s.plan_kind = {}::text",
- p.push(Value::String(pk.to_string()))
- ));
- }
- other => {
- return Err(BosError::bad_params(format!(
- "plan_kind 只接受 fixed/custom,收到「{other}」"
- )));
- }
- }
- }
- if let Some(exit) = p.push_like(opt_trim(body.line_exit.as_ref())) {
- // 快照 jsonb 以文本 LIKE 命中出口名(与台账下拉同源;⛔ 相关 EXISTS)。
- w.push(format!("COALESCE(s.line_exits::text, '') LIKE {exit}"));
- }
- if let Some(days) = body.expiring_within_days {
- if days < 0 {
- return Err(BosError::bad_params(format!(
- "expiring_within_days 须 ≥ 0,收到 {days}"
- )));
- }
- let until = NaiveDate::parse_from_str(&t, "%Y-%m-%d")
- .unwrap_or_else(|_| chrono::Local::now().date_naive())
- + chrono::Duration::days(days);
- let td = p.push(Value::String(t.clone()));
- let until_p = p.push(Value::String(date_text(until)));
- // 快到期=止期 ∈ [today, today+N];已到期(止期 < today)不算。日期上限在 Rust 算好,
- // ⛔ SQL `date + int`(UDS/DataFusion 对日期算术支持不稳定)。
- w.push("COALESCE(s.end_date, s.expire_date) IS NOT NULL".to_string());
- w.push(format!("COALESCE(s.end_date, s.expire_date)::date >= {td}::date"));
- w.push(format!("COALESCE(s.end_date, s.expire_date)::date <= {until_p}::date"));
- }
- if let Some(st) = opt_trim(body.status.as_ref()) {
- // 状态三态是**读侧推导**(本轮⛔ 日终翻转任务)⇒ 筛选谓词与 `status_display` 同源
- match st {
- "cancelled" | "replaced" | "early_stopped" => {
- w.push(format!("s.status = {}::text", p.push(Value::String(st.to_string()))));
- }
- "pending" => {
- let td = p.push(Value::String(t.clone()));
- w.push("s.status NOT IN ('cancelled','replaced','early_stopped')".to_string());
- w.push(format!("COALESCE(s.start_date, s.effective_date) > {td}::date"));
- }
- "active" => {
- let td = p.push(Value::String(t.clone()));
- w.push("s.status NOT IN ('cancelled','replaced','early_stopped')".to_string());
- w.push(format!("COALESCE(s.start_date, s.effective_date) <= {td}::date"));
- w.push(format!("COALESCE(s.end_date, s.expire_date) >= {td}::date"));
- }
- "expired" => {
- let td = p.push(Value::String(t.clone()));
- w.push("s.status NOT IN ('cancelled','replaced','early_stopped')".to_string());
- w.push(format!("COALESCE(s.end_date, s.expire_date) < {td}::date"));
- }
- other => {
- return Err(BosError::bad_params(format!(
- "未知订阅状态筛选值:{other}(可选 pending/active/expired/cancelled/replaced/early_stopped)"
- )))
- }
- }
- }
- // ⚠️ `total()` 只接受 `FROM … WHERE …` 片段(它自己前缀 `SELECT COUNT(1) AS c`),
- // 把 `SELECT_COLS` 拼进来会成 `SELECT COUNT(1) AS c SELECT …` ⇒ UDS 侧解析报错。
- let from_clause = if need_kw_join {
- "FROM subscription s \
- LEFT JOIN customer cu ON cu.customer_id = s.customer_id \
- LEFT JOIN contract ct ON ct.contract_id = s.contract_id"
- } else {
- "FROM subscription s"
- };
- let from_where = format!("{from_clause} {}", p.where_clause(&w));
- let total = total(state.db.as_ref(), &from_where, p.values()).await?;
- let (lim, off) = p.push_page(&body.pg);
- let sql =
- format!("{SELECT_COLS} {from_where} ORDER BY s.customer_id, s.subscription_id DESC LIMIT {lim} OFFSET {off}");
- let rows = state.db.query_all::<SubRow>(&sql, p.values()).await?;
- let ids: Vec<String> = rows.iter().map(|r| r.customer_id.clone()).collect();
- let contract_ids: Vec<String> = rows
- .iter()
- .filter_map(|r| opt_trim(r.contract_id.as_ref()).map(str::to_string))
- .collect();
- // UDS 收拢:客户名 + 合同编号 原 2 跳 → 1 条 UNION。
- let (names, contract_nos) = sub_list_names(state.db.as_ref(), &ids, &contract_ids).await?;
- let items: Vec<Value> = rows
- .iter()
- .map(|r| {
- let contract_no = r
- .contract_id
- .as_deref()
- .and_then(|id| contract_nos.get(id))
- .and_then(|v| v.first())
- .map(String::as_str);
- to_json(
- r,
- names.get(&r.customer_id).and_then(|v| v.first()).map(String::as_str),
- contract_no,
- &t,
- )
- })
- .collect();
- // 出账聚合(详情页四卡):一次批量算本页全部订阅,⛔ 逐行 N+1。
- // Wave B:`list_all` 台账不展示四卡 ⇒ `include_billing=false` 跳过本跳(业务约 3);
- // 详情改走 `subscription/get`;`get_list`(客户订阅管理)仍随行下发。
- let mut items = items;
- if include_billing {
- let sub_ids: Vec<String> = rows.iter().map(|r| r.subscription_id.clone()).collect();
- let mut billing = billing_summary(state, &sub_ids).await?;
- for (i, r) in rows.iter().enumerate() {
- if let Some(v) = items.get_mut(i) {
- v["billing"] = billing.remove(&r.subscription_id).unwrap_or_else(|| json!({
- "state": "no_receivable",
- "receivable_cents": Value::Null,
- "billed_cents": Value::Null,
- "unbilled_cents": Value::Null,
- "cost_cents": Value::Null,
- "periods": 0,
- }));
- }
- }
- }
- Ok(json!({
- "items": items,
- "total": total,
- "page": body.pg.page,
- "page_size": body.pg.page_size,
- "notes": [
- "关键字命中 plan_name/subscription_id/order_no/客户名/合同号(LEFT JOIN)。",
- "状态三态为读侧推导(本轮无日终状态任务);`editable`/`reason` 与状态同源。",
- if include_billing {
- "本应答随行下发出账四卡(billing_summary)。"
- } else {
- "list_all 跳过 billing_summary;出账四卡请走 subscription/get。"
- },
- ],
- }))
- }
- fn opt_region_ids(v: Option<&Vec<String>>) -> Option<&[String]> {
- v.map(Vec::as_slice).filter(|s| !s.is_empty())
- }
- /// 订阅**读口**放行的角色(`get_list`/`list_all` 共用)。
- ///
- /// 2026-11-14 加 `Enterprise`:客户门户「订阅记录」页此前恒 `60058`。放行的前提是
- /// [`list_records`] 的行集**恒以** [`customer_scope_pred`] 打头(客户主体 ⇒ 等值收窄到本公司,
- /// 越权的 `customer_id` 入参只会命中空集),⛔ 在没有该谓词的读口上照抄这份清单。
- /// 平台侧另需给 `enterprise` 角色绑 `bos.subscription.list`(否则先被网关 AC 拒成 `11001`)。
- ///
- /// 2026-11-16 加 `TeamLead`(P3-D9):团队长在「团队客户 → 客户档案 → 全部订单」里点「查看」会进
- /// `/orders/{id}`,该页取 [`get`] ⇒ 此前恒 `60058`。行集同样由 [`customer_scope_pred`] 收窄到
- /// 本团队在册客户,越权 `customer_id` 只命中空集。
- const SUB_READ_ROLES: [RoleCode; 6] = [
- RoleCode::Admin,
- RoleCode::OpsMain,
- RoleCode::Ops,
- RoleCode::OpsSub,
- RoleCode::Enterprise,
- RoleCode::TeamLead,
- ];
- /// 订阅**详情**读口放行的角色([`get`])。
- ///
- /// 与 [`SUB_READ_ROLES`] 分开列:`Enterprise`(客户主账号)的套餐页走
- /// `subscription/get_list`+门户自读,详情口未接线,⛔ 顺手放开;`TeamLead` 必须放行(P3-D9)。
- const SUB_DETAIL_ROLES: [RoleCode; 5] = [
- RoleCode::Admin,
- RoleCode::OpsMain,
- RoleCode::Ops,
- RoleCode::OpsSub,
- RoleCode::TeamLead,
- ];
- /// `POST /subscription/get_list@v1`:客户管理 → 套餐订阅管理页(唯一写入口的列表)。
- pub async fn get_list(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionListReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&SUB_READ_ROLES) {
- return json_err(e);
- }
- match list_records(&state, &auth, &body, true, true).await {
- Ok(v) => json_ok(v),
- Err(e) => json_err(e),
- }
- }
- /// `POST /subscription/list_all@v1`:全部订阅页(⛔ 新增/编辑/删除入口,只查询)。
- pub async fn list_all(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionListReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&SUB_READ_ROLES) {
- return json_err(e);
- }
- // Wave B:台账不展示出账四卡 ⇒ 跳过 billing_summary(uds 业务跳约 3)。
- match list_records(&state, &auth, &body, false, false).await {
- Ok(v) => json_ok(v),
- Err(e) => json_err(e),
- }
- }
- // ═══════════════════════════ §5.4 详情:五分区 ═══════════════════════════
- /// `POST /subscription/get@v1`:基本/周期/金额/出口/额度五分区 + 条件 `related`。
- pub async fn get(
- State(state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(body): DataBody<SubscriptionGetReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&SUB_DETAIL_ROLES) {
- return json_err(e);
- }
- let sid = match req_field("subscription_id", &body.subscription_id) {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let r = match scoped_sub(&state, &auth, &sid).await {
- Ok(Some(v)) => v,
- Ok(None) => {
- return json_err(BosError::not_found(format!(
- "订阅不存在或超出当前账号可见范围:{sid}"
- )))
- }
- Err(e) => return json_err(e),
- };
- let t = today();
- let names = match pairs_by(
- state.db.as_ref(),
- "customer",
- "customer_id",
- "customer_name",
- &[r.customer_id.clone()],
- )
- .await
- {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let customer_name = names
- .get(&r.customer_id)
- .and_then(|v| v.first())
- .cloned()
- .unwrap_or_default();
- // 合同一栏:未关联合同显示「—」且⛔ 显示「未开通」(§5.4:⛔ 把「无合同」说成一种开通态)
- let mut opened_state: Option<&str> = None;
- let mut contract_no: Option<String> = None;
- if let Some(ct) = opt_trim(r.contract_id.as_ref()) {
- let all = match contracts_of_customer(&state, &r.customer_id).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- if let Some(c) = all.into_iter().find(|c| c.contract_id == ct) {
- contract_no =
- Some(opt_trim(c.external_no.as_ref()).unwrap_or(c.contract_no.as_str()).to_string());
- match opened_map_for(&state, &[c]).await {
- Ok(m) => {
- opened_state = match m.get(ct) {
- Some(Opened::Opened) => Some("opened"),
- Some(Opened::NotOpened) => Some("not_opened"),
- None => None,
- }
- }
- Err(e) => return json_err(e),
- }
- }
- }
- // 变更链(§5.4「关联订阅」):被谁替代 + 替代了谁
- let replaced_by: Vec<Value> = {
- let mut p = Params::default();
- let a = p.push(Value::String(sid.clone()));
- let sql = format!(
- "{SELECT_COLS} FROM subscription s WHERE s.replaces_subscription_id = {a}::text \
- ORDER BY s.subscription_id"
- );
- match state.db.query_all::<SubRow>(&sql, p.values()).await {
- Ok(v) => v.iter().map(|x| brief(x, &t)).collect(),
- Err(e) => return json_err(e),
- }
- };
- let original: Option<Value> = match opt_trim(r.replaces_subscription_id.as_ref()) {
- Some(o) => {
- match scoped_sub(&state, &auth, o).await {
- Ok(Some(row)) => Some(brief(&row, &t)),
- Ok(None) => None,
- Err(e) => return json_err(e),
- }
- }
- None => None,
- };
- let quota_slots = as_opt_num(Some(r.quota_slots.as_str()));
- let customer_quota_cents = match customer_quota(&state, &r.customer_id).await {
- Ok(v) => v,
- Err(e) => return json_err(e),
- };
- let mut v = to_json(&r, Some(customer_name.as_str()), contract_no.as_deref(), &t);
- v["panels"] = json!({
- "basic": {
- "customer_id": r.customer_id,
- "customer_name": customer_name,
- "contract_id": r.contract_id,
- "contract_no": contract_no.clone().unwrap_or_else(|| "—".to_string()),
- "contract_opened_state": opened_state,
- "contract_item_id": r.contract_item_id,
- "order_no": opt_trim(r.order_no.as_ref()).unwrap_or("—"),
- "actual_opened_at": opt_trim(r.actual_opened_at.as_ref()).unwrap_or("—"),
- "early_stopped_at": opt_trim(r.early_stopped_at.as_ref()).unwrap_or("—"),
- "plan_id": r.plan_id,
- "plan_name": r.plan_name,
- "plan_kind": r.plan_kind,
- "created_at": r.created_at,
- "row_version": as_opt_num(Some(r.row_version.as_str())),
- },
- "period": {
- "term": r.term,
- "start_date": start_text(&r),
- "end_date": end_text(&r),
- "effective_date": r.effective_date,
- "expire_date": r.expire_date,
- },
- "amount": money_json(&r),
- "exits": {
- "plan_family": r.plan_family,
- "sub_mode": r.sub_mode,
- "line_exits": exits_json(r.line_exits.as_ref()),
- "line_exit_key": r.line_exit_key,
- },
- "quota": {
- "quota_slots": quota_slots,
- "customer_quota_cents": customer_quota_cents,
- },
- });
- v["related"] = json!({
- "replaced_by": replaced_by,
- "original": original,
- });
- // 套餐月成本只读口未接线 ⇒ 三态里的 `unconfigured`(⛔ 显示 0 元、⛔ 显示「无成本」)
- v["plan_cost_cents"] = json!(null);
- v["plan_cost_state"] = json!("unconfigured");
- // 出账四卡(第 6 册):应收/已出账/未出账/累计成本来自 `billing_receivable` +
- // 已执行批次 `bill_detail`;无应收行 ⇒ 四值 null + `no_receivable`,
- // ⛔ 用 0 元冒充「未出账」。
- let billing = match billing_summary(&state, &[r.subscription_id.clone()]).await {
- Ok(mut m) => m.remove(&r.subscription_id).unwrap_or(Value::Null),
- Err(e) => return json_err(e),
- };
- let billing_state = billing
- .get("state")
- .and_then(Value::as_str)
- .unwrap_or("no_receivable")
- .to_string();
- v["billing"] = billing;
- v["billing_state"] = json!(billing_state);
- let mut notes: Vec<String> = vec![
- COST_UNCONFIGURED_NOTE.to_string(),
- if billing_state == "ok" {
- "出账四卡=应收期次合计(billing_receivable)/已执行批次明细合计(bill_detail),\
- 未出账=应收−已出账;逐期清单与对账批次状态请到对账页核对。"
- .to_string()
- } else {
- "本条订阅尚无应收期次(billing_receivable 无行):四卡按「未配置」呈现,\
- 不以 0 元或「未出账」冒充结论。"
- .to_string()
- },
- ];
- if contract_no.is_none() {
- notes.push("本订阅未关联合同:合同一栏显示「—」,不显示「未开通」(§5.4)。".to_string());
- }
- v["notes"] = json!(notes);
- json_ok(v)
- }
- /// 变更链节点的精简出参(⛔ 详情里递归展开整行)。
- fn brief(r: &SubRow, today: &str) -> Value {
- let (key, label, _) = status_display(r, today);
- json!({
- "subscription_id": r.subscription_id,
- "plan_name": r.plan_name,
- "status": key,
- "status_label": label,
- "start_date": start_text(r),
- "end_date": end_text(r),
- })
- }
- // ═══════════════════════════ stack(D-03:就地续期口已停用) ═══════════════════════════
- /// `POST /subscription/stack@v1`:**D-03 起拒写**。
- ///
- /// 权威「叠加」=新建并存订阅(原订阅不动)+客户在用时经 `create@v1` 触发服务开通工单;
- /// 本口原先「就地改 `end_date`」与 §5.2「结束日不可人工改」/数据模型「叠加=新增行」冲突。
- /// 路由保留、契约入参形态不动,一律指向 `/subscription/create@v1`。
- pub async fn stack(
- State(_state): State<AppState>,
- RequireAuth(auth): RequireAuth,
- DataBody(_body): DataBody<SubscriptionStackReq>,
- ) -> Response {
- if let Err(e) = auth.require_roles(&[RoleCode::Admin, RoleCode::OpsMain, RoleCode::Ops]) {
- return json_err(e);
- }
- json_err(BosError::bad_params(
- "subscription/stack@v1 已停用就地改结束日(D-03):叠加=新建并存订阅,请走 \
- /subscription/create@v1(§5.2 五步校验+六步事务;客户在用时自动生成服务开通工单)"
- .to_string(),
- ))
- }
- // ═══════════════════════════ 单元测试(纯函数+静态断言) ═══════════════════════════
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn 额度变更写客户字段历史且带前后额度() {
- // TC-CU-53 步骤 5:额度调整必须落 `customer_field_history(field_key='quota')`,
- // 且旧值/新值分别是调整前后的席位数字符串(客户「归属变更」页直接展示这两列)。
- let stmt = quota_history_stmt("KL-2026-000058", 0, 5, "377168271910113280");
- assert!(stmt.sql.contains("INSERT INTO customer_field_history"), "{}", stmt.sql);
- assert!(stmt.sql.contains("'quota'::text"), "{}", stmt.sql);
- assert!(stmt.sql.contains("old_display"), "{}", stmt.sql);
- assert!(stmt.sql.contains("new_display"), "{}", stmt.sql);
- let vals: Vec<String> = stmt
- .params
- .iter()
- .map(|v| match v {
- Value::String(s) => s.clone(),
- other => other.to_string(),
- })
- .collect();
- assert!(vals.contains(&"0".to_string()), "{vals:?}");
- assert!(vals.contains(&"5".to_string()), "{vals:?}");
- assert!(vals.contains(&"377168271910113280".to_string()), "{vals:?}");
- }
- fn map(raw: &str) -> Map<String, Value> {
- serde_json::from_str::<Value>(raw).unwrap().as_object().unwrap().clone()
- }
- #[test]
- fn 时长折算先折下一周期生效日再减一天() {
- // §5.2:2026-01-31 按月 ⇒ 下一周期 2026-02-28 ⇒ 结束日 2026-02-27
- let d = NaiveDate::from_ymd_opt(2026, 1, 31).unwrap();
- let next = add_months_clamped(d, 1);
- assert_eq!(date_text(next), "2026-02-28");
- let prev = next - chrono::Duration::days(1);
- assert_eq!(date_text(prev), "2026-02-27");
- // 按年=加 12 个月;按季度=加 3 个月
- assert_eq!(term_months("yearly").unwrap(), 12);
- assert_eq!(term_months("quarterly").unwrap(), 3);
- assert_eq!(term_months("monthly").unwrap(), 1);
- assert!(term_months("weekly").is_err());
- let d2 = NaiveDate::from_ymd_opt(2028, 2, 29).unwrap();
- assert_eq!(date_text(add_months_clamped(d2, 12)), "2029-02-28");
- }
- #[test]
- fn 年价按订阅时长折算且月结算不受时长影响() {
- assert_eq!(annual_by_term(120_000, 10_000, "yearly"), 120_000);
- assert_eq!(annual_by_term(120_000, 10_000, "quarterly"), 30_000);
- assert_eq!(annual_by_term(120_000, 10_000, "monthly"), 10_000);
- }
- #[test]
- fn 新建载荷的只读派生列逐列点名拒收() {
- 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"}"#);
- let e = reject_read_only(&m, &CREATE_READ_ONLY).unwrap_err();
- let s = format!("{e}");
- for k in [
- "annual_price_cents",
- "monthly_settle_cents",
- "end_date",
- "line_exits",
- "sub_mode",
- "order_no",
- "actual_opened_at",
- // D-15:条目形态随条目带入,订阅载荷⛔ 再收
- "item_family",
- ] {
- assert!(s.contains(k), "未点名 {k}:{s}");
- }
- assert!(!s.contains("term"), "term 是新增态唯一入参,不拒收:{s}");
- let ok = map(r#"{"customer_id":"C1","plan_id":"P1","term":"monthly"}"#);
- assert!(reject_read_only(&ok, &CREATE_READ_ONLY).is_ok());
- }
- #[test]
- #[allow(non_snake_case)] // 测试名用中文直述判据口径(错误码后缀保持大写更易检索)
- fn 修改白名单两列其余键点名且换套餐走M229() {
- let swap = map(r#"{"plan_id":"P2"}"#);
- assert!(matches!(
- reject_update_payload(&swap),
- Err(e) if format!("{e}").contains("KLT-M229") || format!("{e:?}").contains("M229")
- ));
- let bad = map(r#"{"end_date":"2027-01-01","term":"monthly","status":"active"}"#);
- let s = format!("{}", reject_update_payload(&bad).unwrap_err());
- for k in ["end_date", "term", "status"] {
- assert!(s.contains(k), "未点名 {k}:{s}");
- }
- assert!(reject_update_payload(&map(r#"{"trial_months":3}"#)).is_ok());
- assert!(reject_update_payload(&Map::new()).is_ok());
- }
- fn row(status: &str, start: Option<&str>, end: Option<&str>) -> SubRow {
- SubRow {
- subscription_id: "SUB-1".to_string(),
- customer_id: "C1".to_string(),
- contract_id: None,
- contract_item_id: None,
- plan_id: Some("P1".to_string()),
- plan_name: Some("标准档".to_string()),
- plan_kind: Some("fixed".to_string()),
- plan_owner_customer_id: None,
- status: status.to_string(),
- plan_family: Some("link".to_string()),
- sub_mode: None,
- line_exits: None,
- line_exit_key: Some("中国香港".to_string()),
- start_date: start.map(str::to_string),
- end_date: end.map(str::to_string),
- term: Some("yearly".to_string()),
- trial_months: None,
- discount_monthly_cents: None,
- annual_price_cents: Some("2000000".to_string()),
- monthly_settle_cents: Some("166666".to_string()),
- quota_slots: "10".to_string(),
- quantity: "1".to_string(),
- parent_subscription_id: None,
- replaces_subscription_id: None,
- order_no: None,
- actual_opened_at: None,
- early_stopped_at: None,
- effective_date: None,
- expire_date: None,
- created_at: "2026-01-01".to_string(),
- row_version: "1".to_string(),
- }
- }
- #[test]
- fn 终态状态不被读侧推导覆盖() {
- let t = "2026-11-09";
- // 库值=生效中,日期已过 ⇒ 推导成已到期(本轮⛔ 日终翻转任务)
- let (k, l, n) = status_display(&row("active", Some("2025-01-01"), Some("2025-12-31")), t);
- assert_eq!(k, "expired");
- assert_eq!(l, "已到期");
- assert!(n.is_none());
- // 终态(已退订/已替换/提前停机)原样保留,⛔ 被日期改写
- let (k2, _, _) = status_display(&row("cancelled", Some("2025-01-01"), Some("2026-12-31")), t);
- assert_eq!(k2, "cancelled");
- let (k3, _, _) = status_display(&row("replaced", Some("2025-01-01"), Some("2026-12-31")), t);
- assert_eq!(k3, "replaced");
- let (k6, l6, _) =
- status_display(&row("early_stopped", Some("2025-01-01"), Some("2026-12-31")), t);
- assert_eq!(k6, "early_stopped");
- assert_eq!(l6, "提前停机");
- // 待生效
- let (k4, _, _) = status_display(&row("pending", Some("2027-01-01"), Some("2027-12-31")), t);
- assert_eq!(k4, "pending");
- // 日期缺失 ⇒ 回库值+说明(⛔ 凭空造一个状态)
- let (k5, _, n5) = status_display(&row("active", None, None), t);
- assert_eq!(k5, "active");
- assert!(n5.is_some());
- }
- #[test]
- fn 终态订阅不可修改不可删除() {
- let t = "2026-11-09";
- assert!(terminal_guard(&row("expired", Some("2025-01-01"), Some("2025-12-31")), t, "删除").is_ok());
- assert!(terminal_guard(&row("cancelled", Some("2025-01-01"), Some("2026-12-31")), t, "删除").is_err());
- assert!(terminal_guard(&row("replaced", Some("2025-01-01"), Some("2026-12-31")), t, "修改").is_err());
- }
- #[test]
- fn 金额出参一处折算点() {
- let v = money_json(&row("active", Some("2026-01-01"), Some("2026-12-31")));
- assert_eq!(v["annual_price_cents"], json!(2000000));
- assert_eq!(v["monthly_settle_cents"], json!(166666));
- assert_eq!(
- v["monthly_settle_display"].as_str().unwrap(),
- "2000000(折算 166666/月)"
- );
- }
- #[test]
- fn 源码静态断言_除月数与冲突改写只有一处实现() {
- let src = include_str!("subscription.rs");
- let lower = src.to_lowercase();
- let conflict = concat!("ON CON", "FLICT");
- assert!(!src.contains(conflict), "UDS 不支持冲突改写");
- assert!(
- !lower.contains(concat!(" cur", "rent_date")),
- "不在 SQL 里取当前日期(时区口径须与 today() 一致)"
- );
- // 月结算与额度求和的唯一实现落在 bos-invariant,本模块⛔ 自行「金额 ÷12」/自行 SUM。
- // ⚠️ 只锁**金额侧**写法:`add_months_clamped` 里的 `total / 12` 是日期取模,
- // 与月结算算式无关,按裸 `/ 12` 断言会把正确的日期数学一起判死。
- for pat in [concat!("cents / 1", "2"), concat!("cents/1", "2")] {
- assert!(
- !src.contains(pat),
- "月结算标准金额只能经 monthly_settle_of 折算(05 册 §3.3 唯一算式)"
- );
- }
- assert!(
- !src.to_uppercase().contains(concat!("SU", "M(")),
- "在用额度求和只能经 in_use_quota_sum_batch(§5.6 唯一实现)"
- );
- assert!(
- !src.contains(concat!(".me", "ssage()")),
- "BosError 不提供该访问器"
- );
- assert!(src.contains("check_subscription_deletable"), "删除阻塞必须走不变量库(M227/M230 同源)");
- }
- }
|