register.go 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938
  1. package contract
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "github.com/go-playground/validator/v10"
  8. "github.com/shopspring/decimal"
  9. "github.com/tealeg/xlsx"
  10. "hongze/fms_api/controller/resp"
  11. "hongze/fms_api/global"
  12. "hongze/fms_api/models/base"
  13. "hongze/fms_api/models/crm"
  14. "hongze/fms_api/models/fms"
  15. "hongze/fms_api/models/system"
  16. "hongze/fms_api/services/alarm_msg"
  17. crmService "hongze/fms_api/services/crm"
  18. fmsService "hongze/fms_api/services/fms"
  19. "hongze/fms_api/utils"
  20. "net/http"
  21. "os"
  22. "path"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "time"
  27. )
  28. // RegisterController 合同登记
  29. type RegisterController struct{}
  30. // List
  31. // @Title 合同登记列表
  32. // @Description 合同登记列表
  33. // @Param Keyword query string false "关键词"
  34. // @Param StartDate query string false "合同开始日期"
  35. // @Param EndDate query string false "合同结束日期"
  36. // @Param ServiceType query int false "套餐类型"
  37. // @Param ContractType query string false "合同类型"
  38. // @Param RegisterStatus query int false "登记状态"
  39. // @Success 200 {object} fms.ContractRegisterItem
  40. // @router /contract/register/list [get]
  41. func (rg *RegisterController) List(c *gin.Context) {
  42. var req fms.ContractRegisterListReq
  43. if e := c.BindQuery(&req); e != nil {
  44. err, ok := e.(validator.ValidationErrors)
  45. if !ok {
  46. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  47. return
  48. }
  49. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  50. return
  51. }
  52. cond := `1 = 1`
  53. pars := make([]interface{}, 0)
  54. // 合同编号/客户姓名/销售/代付方
  55. if req.Keyword != "" {
  56. kw := "%" + req.Keyword + "%"
  57. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR rai_seller_name LIKE ? OR actual_pay_companies LIKE ?)`
  58. pars = append(pars, kw, kw, kw, kw, kw)
  59. }
  60. if req.StartDate != "" && req.EndDate != "" {
  61. st := fmt.Sprint(req.StartDate, " 00:00:00")
  62. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  63. cond += ` AND (create_time BETWEEN ? AND ?)`
  64. pars = append(pars, st, ed)
  65. }
  66. if req.ContractType != "" {
  67. newCond := ""
  68. typeSlices := strings.Split(req.ContractType, ",")
  69. for _, v := range typeSlices {
  70. if v[:1] == "0" {
  71. //自付
  72. if v[1:] == "1" {
  73. newCond += ` (contract_type = 1 AND has_payment=0) `
  74. } else if v[1:] == "2" {
  75. newCond += ` (contract_type = 2 AND has_payment=0) `
  76. } else {
  77. newCond += ` (contract_type = 4 AND has_payment=0) `
  78. }
  79. } else {
  80. //代付
  81. if v[1:] == "1" {
  82. newCond += ` (contract_type = 1 AND has_payment=1) `
  83. } else if v[1:] == "2" {
  84. newCond += ` (contract_type = 2 AND has_payment=1) `
  85. } else {
  86. newCond += ` (contract_type = 4 AND has_payment=1) `
  87. }
  88. }
  89. newCond += " OR "
  90. }
  91. newCond = strings.TrimRight(newCond, "OR ")
  92. cond += " AND " + "(" + newCond + ")"
  93. }
  94. if req.RegisterStatus != 0 {
  95. cond += ` AND register_status = ?`
  96. pars = append(pars, req.RegisterStatus)
  97. }
  98. // 套餐筛选
  99. if req.ServiceTypes != "" {
  100. serviceTypes := strings.Split(req.ServiceTypes, ",")
  101. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  102. if e != nil {
  103. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  104. return
  105. }
  106. if len(registerIds) > 0 {
  107. cond += ` AND contract_register_id IN ?`
  108. pars = append(pars, registerIds)
  109. } else {
  110. cond += ` AND 1 = 2`
  111. }
  112. }
  113. page := new(base.Page)
  114. page.SetPageSize(req.PageSize)
  115. page.SetCurrent(req.Current)
  116. page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
  117. total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
  118. if e != nil {
  119. resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
  120. return
  121. }
  122. registerIds := make([]int, 0)
  123. for i := range list {
  124. registerIds = append(registerIds, list[i].ContractRegisterId)
  125. }
  126. serviceMap := make(map[int]string, 0)
  127. invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  128. paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  129. if len(registerIds) > 0 {
  130. // 获取所有的服务套餐
  131. serviceMap, _, e = fmsService.GetContractServiceNameFormat(registerIds)
  132. if e != nil {
  133. resp.FailMsg("获取失败", e.Error(), c)
  134. return
  135. }
  136. // 获取开票/到款列表
  137. invoiceCond := `contract_register_id IN ?`
  138. invoicePars := make([]interface{}, 0)
  139. invoicePars = append(invoicePars, registerIds)
  140. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  141. if e != nil {
  142. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  143. return
  144. }
  145. for i := range invoiceList {
  146. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  147. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  148. }
  149. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  150. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  151. }
  152. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  153. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  154. }
  155. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  156. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  157. }
  158. }
  159. }
  160. respList := make([]*fms.ContractRegisterList, 0)
  161. for i := range list {
  162. v := new(fms.ContractRegisterList)
  163. if list[i].HasPayment == 1 {
  164. //代付
  165. if list[i].ContractType == 1 {
  166. v.ContractTypeString = "代付合同(新签)"
  167. } else if list[i].ContractType == 2 {
  168. v.ContractTypeString = "代付合同(续约)"
  169. } else {
  170. v.ContractTypeString = "代付合同(补充)"
  171. }
  172. } else {
  173. if list[i].ContractType == 1 {
  174. v.ContractTypeString = "自付合同(新签)"
  175. } else if list[i].ContractType == 2 {
  176. v.ContractTypeString = "自付合同(续约)"
  177. } else {
  178. v.ContractTypeString = "自付合同(补充)"
  179. }
  180. }
  181. v.ContractRegisterItem = list[i]
  182. v.ServicesName = serviceMap[list[i].ContractRegisterId]
  183. v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
  184. v.PaymentList = paymentMap[list[i].ContractRegisterId]
  185. respList = append(respList, v)
  186. }
  187. page.SetTotal(total)
  188. baseData := new(base.BaseData)
  189. baseData.SetPage(page)
  190. baseData.SetList(respList)
  191. resp.OkData("获取成功", baseData, c)
  192. }
  193. // Add
  194. // @Title 新增合同登记
  195. // @Description 新增合同登记
  196. // @Param request body fms.ContractRegisterAddReq true "type json string"
  197. // @Success 200 string "操作成功"
  198. // @router /contract/register/add [post]
  199. func (rg *RegisterController) Add(c *gin.Context) {
  200. req := new(fms.ContractRegisterAddReq)
  201. err := c.ShouldBind(&req)
  202. if err != nil {
  203. errs, ok := err.(validator.ValidationErrors)
  204. if !ok {
  205. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  206. return
  207. }
  208. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  209. return
  210. }
  211. claims, _ := c.Get("adminInfo")
  212. adminInfo := claims.(*system.SysAdmin)
  213. // 日期校验
  214. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  215. if e != nil {
  216. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  217. return
  218. }
  219. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  220. if e != nil {
  221. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  222. return
  223. }
  224. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  225. if req.SignDate != "" {
  226. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  227. if e != nil {
  228. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  229. return
  230. }
  231. signDate = signDateTime
  232. }
  233. // 是否存在相同合同编号的登记
  234. ob := new(fms.ContractRegister)
  235. existCond := `contract_code = ?`
  236. existPars := make([]interface{}, 0)
  237. existPars = append(existPars, req.ContractCode)
  238. exist, e := ob.FetchByCondition(existCond, existPars)
  239. if e != nil && e != utils.ErrNoRow {
  240. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  241. return
  242. }
  243. if exist != nil && exist.ContractRegisterId > 0 {
  244. resp.Fail("合同编号已存在", c)
  245. return
  246. }
  247. // 货币及汇率
  248. rateList, e := fmsService.GetTodayCurrencyRateList()
  249. if e != nil {
  250. resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), c)
  251. return
  252. }
  253. var rate float64
  254. for i := range rateList {
  255. if req.CurrencyUnit == rateList[i].Code {
  256. rate = rateList[i].RMBRate
  257. break
  258. }
  259. }
  260. if rate <= 0 {
  261. resp.FailMsg("操作失败", "货币汇率信息有误", c)
  262. return
  263. }
  264. // 查询销售信息
  265. var (
  266. sellerId int
  267. raiSellerId int
  268. sellerName string
  269. raiSellerName string
  270. )
  271. if req.SellerIds != "" {
  272. admin := new(crm.Admin)
  273. sellerIds := strings.Split(req.SellerIds, ",")
  274. if len(sellerIds) > 2 {
  275. resp.Fail("最多只能选择两个销售", c)
  276. return
  277. }
  278. var pars []interface{}
  279. cond := ` admin_id in (?) `
  280. pars = append(pars, sellerIds)
  281. sellers, e := admin.List(cond, pars)
  282. if e != nil {
  283. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  284. return
  285. }
  286. for _, v := range sellers {
  287. if v.DepartmentId == crm.SellerDepartmentId {
  288. sellerId = v.AdminId
  289. sellerName = v.RealName
  290. } else if v.DepartmentId == crm.RaiSellerDepartmentId {
  291. raiSellerId = v.AdminId
  292. raiSellerName = v.RealName
  293. }
  294. }
  295. }
  296. //新老客户判断
  297. /*newCompany := req.NewCompany
  298. if req.ContractType == 1 {
  299. newCompany = 1
  300. }else if req.ContractType == 2 || req.ContractType == 3 {
  301. newCompany = 0
  302. }
  303. if newCompany != req.NewCompany {
  304. resp.Fail("请输入正确的客户类型", c)
  305. return
  306. }*/
  307. nowTime := time.Now().Local()
  308. ob.ContractRegisterId = req.ContractRegisterId
  309. ob.ContractCode = req.ContractCode
  310. ob.RelateContractCode = req.RelateContractCode
  311. ob.RelateContractMainCode = req.RelateContractMainCode
  312. ob.CrmContractId = req.CrmContractId
  313. ob.ContractSource = req.ContractSource
  314. ob.CompanyName = req.CompanyName
  315. ob.ProductIds = req.ProductIds
  316. ob.SellerId = sellerId
  317. ob.SellerName = sellerName
  318. ob.RaiSellerId = raiSellerId
  319. ob.RaiSellerName = raiSellerName
  320. ob.ContractType = req.ContractType
  321. ob.ContractAmount = req.ContractAmount
  322. ob.CurrencyUnit = req.CurrencyUnit
  323. ob.RMBRate = rate
  324. ob.StartDate = startDate
  325. ob.EndDate = endDate
  326. ob.SignDate = signDate
  327. ob.AgreedPayTime = req.AgreedPayTime
  328. ob.ContractStatus = req.ContractStatus
  329. ob.RegisterStatus = fms.ContractRegisterStatusIng
  330. ob.Remark = req.Remark
  331. ob.ServiceRemark = req.ServiceRemark
  332. ob.HasPayment = req.HasPayment
  333. ob.HasInvoice = req.HasInvoice
  334. ob.ActualPayCompanies = req.ActualPayCompanies
  335. ob.Set()
  336. updateCols := []string{
  337. "ContractCode", "RelateContractCode", "RelateContractMainCode", "CrmContractId", "ContractSource",
  338. "ProductIds", "CompanyName", "SellerId", "SellerName", "StartDate", "EndDate",
  339. "RaiSellerId", "RaiSellerName", "ModifyTime", "ContractType", "ContractAmount", "CurrencyUnit", "RMBRate",
  340. "SignDate", "AgreedPayTime", "ContractStatus", "RegisterStatus", "Remark", "HasPayment", "HasInvoice", "ActualPayCompanies",
  341. }
  342. // 不需要开票到款的代付直接完成登记, 且不允许进行开票/到款登记
  343. if req.HasInvoice == 0 || req.ContractStatus == fms.ContractStatusEnd {
  344. ob.RegisterStatus = fms.ContractRegisterStatusComplete
  345. }
  346. // 新增套餐金额详情内容
  347. serviceAmountMap := make(map[int]float64)
  348. serviceAmountList, e := fmsService.HandleContractServiceAmount(req.ServiceAmount, serviceAmountMap, req.CurrencyUnit)
  349. if e != nil {
  350. resp.FailMsg("操作失败", "新增合同套餐金额信息失败, Err: "+e.Error(), c)
  351. return
  352. }
  353. //判断产品信息
  354. productIds := make(map[int]struct{})
  355. productIdsStr := ""
  356. for _, v := range serviceAmountList {
  357. productIds[v.ProductId] = struct{}{}
  358. }
  359. for proId, _ := range productIds {
  360. productIdsStr += strconv.Itoa(proId) + ","
  361. }
  362. productIdsStr = strings.Trim(productIdsStr, ",")
  363. ob.ProductIds = productIdsStr
  364. // 套餐信息
  365. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  366. if e != nil {
  367. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  368. return
  369. }
  370. // 合同有效时长(计算付款方式)
  371. dayDiff := ob.EndDate.Sub(ob.StartDate).Hours() / 24
  372. // 新增合同及套餐
  373. logList := make([]*fms.ContractRegisterLog, 0)
  374. //是否补录合同
  375. sellerItemMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  376. if req.Supplement == 1 {
  377. //新增到款信息
  378. if ob.HasInvoice == 0 {
  379. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  380. return
  381. }
  382. //修改合同信息-假合同变成真合同
  383. if e = ob.Update(updateCols); e != nil {
  384. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  385. return
  386. }
  387. invoiceOB := new(fms.ContractInvoice)
  388. invoiceCond := `contract_register_id = ?`
  389. invoicePars := make([]interface{}, 0)
  390. invoicePars = append(invoicePars, req.ContractRegisterId)
  391. invoiceList, e := invoiceOB.List(invoiceCond, invoicePars, "")
  392. if e != nil {
  393. resp.FailMsg("操作失败", "获取合同开票到款列表失败, Err: "+e.Error(), c)
  394. return
  395. }
  396. // 获取销售分组信息
  397. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  398. if e != nil {
  399. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  400. return
  401. }
  402. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  403. for i := range sellerList {
  404. sellerMap[sellerList[i].SellerId] = sellerList[i]
  405. }
  406. //处理重复公司名日期等重复的开票到款记录
  407. dupList, e := fms.GetDuplicateContractInvoiceDetailItemList(ob.CompanyName, req.StartDate, req.EndDate)
  408. if e != nil {
  409. err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
  410. return
  411. }
  412. templateIds := make([]int, 0)
  413. for _, detail := range serviceList {
  414. templateIds = append(templateIds, detail.ServiceTemplateId)
  415. }
  416. sort.Ints(templateIds)
  417. ids := make([]string, 0)
  418. for _, id := range templateIds {
  419. ids = append(ids, strconv.Itoa(id))
  420. }
  421. templateIdStr := strings.Join(ids, ",")
  422. nDupList := make([]*fms.DupInvoice, 0)
  423. for _, dup := range dupList {
  424. if templateIdStr == dup.TemplateIds {
  425. nDupList = append(nDupList, dup)
  426. }
  427. }
  428. //先遍历一遍拿到开票销售信息
  429. for _, ppItem := range nDupList {
  430. if ppItem.ContractRegisterId != req.ContractRegisterId {
  431. j := 0
  432. if ppItem.InvoiceType == 3 {
  433. sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
  434. SellerId: ppItem.SellerId,
  435. SellerName: ppItem.SellerName,
  436. GroupId: ppItem.SellerGroupId,
  437. GroupName: ppItem.SellerGroupName,
  438. TeamId: ppItem.SellerTeamId,
  439. TeamName: ppItem.SellerTeamName,
  440. }
  441. j++
  442. }
  443. }
  444. }
  445. for _, ppItem := range invoiceList {
  446. j, k := 0, 0
  447. v := &fms.ContractInvoice{
  448. ContractRegisterId: ob.ContractRegisterId,
  449. ContractCode: ob.ContractCode,
  450. Amount: ppItem.Amount,
  451. OriginAmount: ppItem.OriginAmount,
  452. CurrencyUnit: ppItem.CurrencyUnit,
  453. InvoiceDate: ppItem.InvoiceDate,
  454. SellerId: ppItem.SellerId,
  455. SellerName: ppItem.SellerName,
  456. SellerGroupId: ppItem.SellerGroupId,
  457. SellerGroupName: ppItem.SellerGroupName,
  458. SellerTeamId: ppItem.SellerTeamId,
  459. SellerTeamName: ppItem.SellerTeamName,
  460. AdminId: int(adminInfo.AdminId),
  461. AdminName: adminInfo.RealName,
  462. Remark: ppItem.Remark,
  463. ServiceProductId: ppItem.ServiceProductId,
  464. IsPrePay: 1,
  465. StartDate: ppItem.StartDate,
  466. EndDate: ppItem.EndDate,
  467. }
  468. if ppItem.InvoiceType == 3 {
  469. v.InvoiceType = 1
  470. sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
  471. SellerId: ppItem.SellerId,
  472. SellerName: ppItem.SellerName,
  473. GroupId: ppItem.SellerGroupId,
  474. GroupName: ppItem.SellerGroupName,
  475. TeamId: ppItem.SellerTeamId,
  476. TeamName: ppItem.SellerTeamName,
  477. }
  478. j++
  479. } else if ppItem.InvoiceType == 4 {
  480. v.InvoiceType = 2
  481. if sellerItem, ok := sellerItemMap[k]; ok {
  482. v.SellerId = sellerItem.SellerId
  483. v.SellerName = sellerItem.SellerName
  484. v.SellerGroupId = sellerItem.GroupId
  485. v.SellerGroupName = sellerItem.GroupName
  486. v.SellerTeamId = sellerItem.TeamId
  487. v.SellerTeamName = sellerItem.TeamName
  488. }
  489. k++
  490. }
  491. v.Set()
  492. // 到款登记-付款方式
  493. v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
  494. // 新增的记录
  495. opData := ""
  496. opDataByte, e := json.Marshal(req)
  497. if e != nil {
  498. return
  499. }
  500. opData = string(opDataByte)
  501. opType := fms.ContractRegisterOpTypePrePay
  502. if ppItem.InvoiceType == 3 {
  503. opType = fms.ContractRegisterOpTypePreInvoice
  504. }
  505. newAmount := decimal.NewFromFloat(0).Round(2)
  506. a := decimal.NewFromFloat(v.Amount).Round(2)
  507. newAmount = newAmount.Add(a)
  508. ia, _ := newAmount.Round(2).Float64()
  509. logList = append(logList, &fms.ContractRegisterLog{
  510. ContractRegisterId: ob.ContractRegisterId,
  511. AdminId: int(adminInfo.AdminId),
  512. AdminName: adminInfo.RealName,
  513. OpData: opData,
  514. OpType: opType,
  515. CreateTime: nowTime,
  516. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  517. })
  518. if e := v.Create(); e != nil {
  519. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  520. return
  521. }
  522. //最后删除预到款记录
  523. e = ppItem.Delete()
  524. if e != nil {
  525. resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
  526. return
  527. }
  528. }
  529. for _, ppItem := range nDupList {
  530. if ppItem.ContractRegisterId != req.ContractRegisterId {
  531. j := 0
  532. v := &fms.ContractInvoice{
  533. ContractRegisterId: ob.ContractRegisterId,
  534. ContractCode: ob.ContractCode,
  535. Amount: ppItem.Amount,
  536. OriginAmount: ppItem.OriginAmount,
  537. CurrencyUnit: ppItem.CurrencyUnit,
  538. InvoiceDate: ppItem.InvoiceDate,
  539. SellerId: ppItem.SellerId,
  540. SellerName: ppItem.SellerName,
  541. SellerGroupId: ppItem.SellerGroupId,
  542. SellerGroupName: ppItem.SellerGroupName,
  543. SellerTeamId: ppItem.SellerTeamId,
  544. SellerTeamName: ppItem.SellerTeamName,
  545. AdminId: int(adminInfo.AdminId),
  546. AdminName: adminInfo.RealName,
  547. Remark: ppItem.Remark,
  548. ServiceProductId: ppItem.ServiceProductId,
  549. IsPrePay: 1,
  550. StartDate: ppItem.StartDate,
  551. EndDate: ppItem.EndDate,
  552. }
  553. if ppItem.InvoiceType == 3 {
  554. v.InvoiceType = 1
  555. } else if ppItem.InvoiceType == 4 {
  556. v.InvoiceType = 2
  557. if sellerItem, ok := sellerItemMap[j]; ok {
  558. v.SellerId = sellerItem.SellerId
  559. v.SellerName = sellerItem.SellerName
  560. v.SellerGroupId = sellerItem.GroupId
  561. v.SellerGroupName = sellerItem.GroupName
  562. v.SellerTeamId = sellerItem.TeamId
  563. v.SellerTeamName = sellerItem.TeamName
  564. }
  565. j++
  566. }
  567. v.Set()
  568. // 到款登记-付款方式
  569. v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
  570. // 新增的记录
  571. opData := ""
  572. opDataByte, e := json.Marshal(req)
  573. if e != nil {
  574. return
  575. }
  576. opData = string(opDataByte)
  577. opType := fms.ContractRegisterOpTypePrePay
  578. if ppItem.InvoiceType == 3 {
  579. opType = fms.ContractRegisterOpTypePreInvoice
  580. }
  581. newAmount := decimal.NewFromFloat(0).Round(2)
  582. a := decimal.NewFromFloat(v.Amount).Round(2)
  583. newAmount = newAmount.Add(a)
  584. ia, _ := newAmount.Round(2).Float64()
  585. logList = append(logList, &fms.ContractRegisterLog{
  586. ContractRegisterId: ob.ContractRegisterId,
  587. AdminId: int(adminInfo.AdminId),
  588. AdminName: adminInfo.RealName,
  589. OpData: opData,
  590. OpType: opType,
  591. CreateTime: nowTime,
  592. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  593. })
  594. if e := v.Create(); e != nil {
  595. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  596. return
  597. }
  598. //最后删除预到款记录
  599. e = ppItem.Delete()
  600. if e != nil {
  601. resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
  602. return
  603. }
  604. }
  605. ppOB := new(fms.ContractPreRegister)
  606. items, e := ppOB.FetchByRegisterId(ppItem.ContractRegisterId)
  607. if e != nil {
  608. if e == utils.ErrNoRow {
  609. resp.Fail("预登记记录不存在或已被删除", c)
  610. return
  611. }
  612. resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
  613. return
  614. }
  615. for _, item := range items {
  616. e = item.Delete()
  617. if e != nil {
  618. resp.FailMsg("删除预登记失败", "Err:"+e.Error(), c)
  619. return
  620. }
  621. }
  622. }
  623. ppOB := new(fms.ContractPreRegister)
  624. items, e := ppOB.FetchByRegisterId(req.ContractRegisterId)
  625. if e != nil {
  626. if e == utils.ErrNoRow {
  627. resp.Fail("预登记记录不存在或已被删除", c)
  628. return
  629. }
  630. resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
  631. return
  632. }
  633. for _, item := range items {
  634. e = item.Delete()
  635. if e != nil {
  636. resp.FailMsg("删除预登记失败", "Err:"+e.Error(), c)
  637. return
  638. }
  639. }
  640. //更新合同套餐等内容
  641. if e = fms.UpdateSupplementContractPreRegister(ob, serviceAmountList, serviceList); e != nil {
  642. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  643. return
  644. }
  645. // 校验金额-是否修改状态
  646. go fmsService.CheckContractRegisterAmount(ob.ContractRegisterId)
  647. // 开票到款汇总
  648. go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
  649. // 操作日志
  650. go func() {
  651. logOB := new(fms.ContractRegisterLog)
  652. if e := logOB.AddInBatches(logList); e != nil {
  653. return
  654. }
  655. }()
  656. } else {
  657. if e = fms.CreateContractRegisterAndServices(ob, serviceList, serviceAmountList); e != nil {
  658. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  659. return
  660. }
  661. //处理重复公司名日期等重复的开票到款记录
  662. dupList, e := fms.GetDuplicateContractInvoiceDetailItemList(ob.CompanyName, req.StartDate, req.EndDate)
  663. if e != nil {
  664. err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
  665. return
  666. }
  667. templateIds := make([]int, 0)
  668. for _, detail := range serviceList {
  669. templateIds = append(templateIds, detail.ServiceTemplateId)
  670. }
  671. sort.Ints(templateIds)
  672. ids := make([]string, 0)
  673. for _, id := range templateIds {
  674. ids = append(ids, strconv.Itoa(id))
  675. }
  676. templateIdStr := strings.Join(ids, ",")
  677. nDupList := make([]*fms.DupInvoice, 0)
  678. for _, dup := range dupList {
  679. if templateIdStr == dup.TemplateIds {
  680. nDupList = append(nDupList, dup)
  681. }
  682. }
  683. //先遍历一遍拿到开票销售信息
  684. for _, ppItem := range nDupList {
  685. j := 0
  686. if ppItem.ContractRegisterId != req.ContractRegisterId {
  687. if ppItem.InvoiceType == 3 {
  688. sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
  689. SellerId: ppItem.SellerId,
  690. SellerName: ppItem.SellerName,
  691. GroupId: ppItem.SellerGroupId,
  692. GroupName: ppItem.SellerGroupName,
  693. TeamId: ppItem.SellerTeamId,
  694. TeamName: ppItem.SellerTeamName,
  695. }
  696. }
  697. j++
  698. }
  699. }
  700. for _, ppItem := range nDupList {
  701. j := 0
  702. if ppItem.ContractRegisterId != req.ContractRegisterId {
  703. v := &fms.ContractInvoice{
  704. ContractRegisterId: ob.ContractRegisterId,
  705. ContractCode: ob.ContractCode,
  706. Amount: ppItem.Amount,
  707. OriginAmount: ppItem.OriginAmount,
  708. CurrencyUnit: ppItem.CurrencyUnit,
  709. InvoiceDate: ppItem.InvoiceDate,
  710. SellerId: ppItem.SellerId,
  711. SellerName: ppItem.SellerName,
  712. SellerGroupId: ppItem.SellerGroupId,
  713. SellerGroupName: ppItem.SellerGroupName,
  714. SellerTeamId: ppItem.SellerTeamId,
  715. SellerTeamName: ppItem.SellerTeamName,
  716. AdminId: int(adminInfo.AdminId),
  717. AdminName: adminInfo.RealName,
  718. Remark: ppItem.Remark,
  719. ServiceProductId: ppItem.ServiceProductId,
  720. IsPrePay: 1,
  721. StartDate: ppItem.StartDate,
  722. EndDate: ppItem.EndDate,
  723. }
  724. if ppItem.InvoiceType == 3 {
  725. v.InvoiceType = 1
  726. } else if ppItem.InvoiceType == 4 {
  727. v.InvoiceType = 2
  728. if sellerItem, ok := sellerItemMap[j]; ok {
  729. v.SellerId = sellerItem.SellerId
  730. v.SellerName = sellerItem.SellerName
  731. v.SellerGroupId = sellerItem.GroupId
  732. v.SellerGroupName = sellerItem.GroupName
  733. v.SellerTeamId = sellerItem.TeamId
  734. v.SellerTeamName = sellerItem.TeamName
  735. j++
  736. }
  737. }
  738. v.Set()
  739. // 到款登记-付款方式
  740. v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
  741. // 新增的记录
  742. opData := ""
  743. opDataByte, e := json.Marshal(req)
  744. if e != nil {
  745. return
  746. }
  747. opData = string(opDataByte)
  748. opType := fms.ContractRegisterOpTypePrePay
  749. if ppItem.InvoiceType == 3 {
  750. opType = fms.ContractRegisterOpTypePreInvoice
  751. }
  752. newAmount := decimal.NewFromFloat(0).Round(2)
  753. a := decimal.NewFromFloat(v.Amount).Round(2)
  754. newAmount = newAmount.Add(a)
  755. ia, _ := newAmount.Round(2).Float64()
  756. logList = append(logList, &fms.ContractRegisterLog{
  757. ContractRegisterId: ob.ContractRegisterId,
  758. AdminId: int(adminInfo.AdminId),
  759. AdminName: adminInfo.RealName,
  760. OpData: opData,
  761. OpType: opType,
  762. CreateTime: nowTime,
  763. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  764. })
  765. if e := v.Create(); e != nil {
  766. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  767. return
  768. }
  769. //最后删除预到款记录
  770. e = ppItem.Delete()
  771. if e != nil {
  772. resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
  773. return
  774. }
  775. ppOB := new(fms.ContractPreRegister)
  776. items, e := ppOB.FetchByRegisterId(ppItem.ContractRegisterId)
  777. if e != nil {
  778. if e == utils.ErrNoRow {
  779. resp.Fail("预登记记录不存在或已被删除", c)
  780. return
  781. }
  782. resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
  783. return
  784. }
  785. for _, item := range items {
  786. e = item.Delete()
  787. if e != nil {
  788. resp.FailMsg("删除预登记失败", "Err:"+e.Error(), c)
  789. return
  790. }
  791. }
  792. }
  793. }
  794. // 操作日志
  795. go func() {
  796. logOB := new(fms.ContractRegisterLog)
  797. if e := logOB.AddInBatches(logList); e != nil {
  798. return
  799. }
  800. }()
  801. }
  802. // 操作日志
  803. go func() {
  804. opData := ""
  805. opDataByte, e := json.Marshal(req)
  806. if e != nil {
  807. return
  808. }
  809. opData = string(opDataByte)
  810. logItem := new(fms.ContractRegisterLog)
  811. logItem.ContractRegisterId = ob.ContractRegisterId
  812. logItem.AdminId = int(adminInfo.AdminId)
  813. logItem.AdminName = adminInfo.RealName
  814. logItem.OpData = opData
  815. logItem.OpType = fms.ContractRegisterOpTypeSave
  816. logItem.CreateTime = nowTime
  817. logItem.Remark = req.Remark
  818. if e = logItem.Create(); e != nil {
  819. return
  820. }
  821. }()
  822. resp.Ok("操作成功", c)
  823. }
  824. // Edit
  825. // @Title 编辑合同登记
  826. // @Description 编辑合同登记
  827. // @Param request body fms.ContractRegisterEditReq true "type json string"
  828. // @Success 200 string "操作成功"
  829. // @router /contract/register/edit [post]
  830. func (rg *RegisterController) Edit(c *gin.Context) {
  831. req := new(fms.ContractRegisterEditReq)
  832. err := c.ShouldBind(&req)
  833. if err != nil {
  834. errs, ok := err.(validator.ValidationErrors)
  835. if !ok {
  836. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  837. return
  838. }
  839. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  840. return
  841. }
  842. claims, _ := c.Get("adminInfo")
  843. adminInfo := claims.(*system.SysAdmin)
  844. // 日期校验
  845. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  846. if e != nil {
  847. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  848. return
  849. }
  850. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  851. if e != nil {
  852. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  853. return
  854. }
  855. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  856. if req.SignDate != "" {
  857. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  858. if e != nil {
  859. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  860. return
  861. }
  862. signDate = signDateTime
  863. }
  864. ob := new(fms.ContractRegister)
  865. item, e := ob.Fetch(req.ContractRegisterId)
  866. if e != nil {
  867. if e == utils.ErrNoRow {
  868. resp.Fail("登记记录不存在或已被删除", c)
  869. return
  870. }
  871. resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
  872. return
  873. }
  874. // 查询销售信息
  875. var (
  876. sellerId int
  877. raiSellerId int
  878. sellerName string
  879. raiSellerName string
  880. )
  881. if req.SellerIds != "" {
  882. admin := new(crm.Admin)
  883. sellerIds := strings.Split(req.SellerIds, ",")
  884. if len(sellerIds) > 2 {
  885. resp.Fail("最多只能选择两个销售", c)
  886. return
  887. }
  888. var pars []interface{}
  889. cond := ` admin_id in (?) `
  890. pars = append(pars, sellerIds)
  891. sellers, e := admin.List(cond, pars)
  892. if e != nil {
  893. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  894. return
  895. }
  896. for _, v := range sellers {
  897. if v.DepartmentId == crm.SellerDepartmentId {
  898. sellerId = v.AdminId
  899. sellerName = v.RealName
  900. } else if v.DepartmentId == crm.RaiSellerDepartmentId {
  901. raiSellerId = v.AdminId
  902. raiSellerName = v.RealName
  903. }
  904. }
  905. }
  906. // 是否存在相同合同编号的登记
  907. existCond := `contract_code = ?`
  908. existPars := make([]interface{}, 0)
  909. existPars = append(existPars, req.ContractCode)
  910. exist, e := ob.FetchByCondition(existCond, existPars)
  911. if e != nil && e != utils.ErrNoRow {
  912. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  913. return
  914. }
  915. if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
  916. resp.Fail("合同编号已存在", c)
  917. return
  918. }
  919. originHasInvoice := item.HasInvoice
  920. updateCols := []string{
  921. "ProductIds", "ContractCode", "RelateContractCode", "CrmContractId", "ContractSource", "CompanyName",
  922. "SellerId", "SellerName", "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime", "RaiSellerId", "RaiSellerName",
  923. "ContractStatus", "RegisterStatus", "Remark", "ServiceRemark", "HasPayment", "ModifyTime", "HasInvoice", "ActualPayCompanies",
  924. }
  925. nowTime := time.Now().Local()
  926. item.ProductIds = req.ProductIds
  927. item.ContractCode = req.ContractCode
  928. item.RelateContractCode = req.RelateContractCode
  929. item.RelateContractMainCode = req.RelateContractMainCode
  930. item.CrmContractId = req.CrmContractId
  931. item.ContractSource = req.ContractSource
  932. item.CompanyName = req.CompanyName
  933. item.SellerId = sellerId
  934. item.SellerName = sellerName
  935. item.RaiSellerId = raiSellerId
  936. item.RaiSellerName = raiSellerName
  937. item.ContractType = req.ContractType
  938. item.ContractAmount = req.ContractAmount
  939. item.StartDate = startDate
  940. item.EndDate = endDate
  941. item.SignDate = signDate
  942. item.AgreedPayTime = req.AgreedPayTime
  943. item.ContractStatus = req.ContractStatus
  944. item.RegisterStatus = fms.ContractRegisterStatusIng
  945. item.Remark = req.Remark
  946. item.ServiceRemark = req.ServiceRemark
  947. item.HasPayment = req.HasPayment
  948. item.HasInvoice = req.HasInvoice
  949. item.ActualPayCompanies = req.ActualPayCompanies
  950. item.ModifyTime = nowTime
  951. // 不需要开票到款的直接完成登记, 且不允许进行开票/到款登记
  952. if req.HasInvoice == 0 {
  953. item.RegisterStatus = fms.ContractRegisterStatusComplete
  954. updateCols = append(updateCols, "RegisterStatus")
  955. }
  956. // 开票到款信息
  957. invoiceOB := new(fms.ContractInvoice)
  958. invoiceCond := `contract_register_id = ?`
  959. invoicePars := make([]interface{}, 0)
  960. invoicePars = append(invoicePars, req.ContractRegisterId)
  961. invoiceList, e := invoiceOB.List(invoiceCond, invoicePars, "")
  962. if e != nil {
  963. resp.FailMsg("操作失败", "获取合同开票到款列表失败, Err: "+e.Error(), c)
  964. return
  965. }
  966. invoiceUpdateCols := make([]string, 0)
  967. // 开票到款操作类型: 0-无; 1-更新; 2-删除;
  968. logRemark := req.Remark
  969. invoiceHandleType := 0
  970. if originHasInvoice == 1 && req.HasInvoice == 0 {
  971. // 若从需要开票改为无需开票, 则删除期间新增的所有开票到款登记
  972. invoiceHandleType = 2
  973. } else {
  974. // 修改了货币单位后,同步更新汇率及开票到款的换算金额
  975. if req.CurrencyUnit != item.CurrencyUnit {
  976. rateList, e := fmsService.GetTodayCurrencyRateList()
  977. if e != nil {
  978. resp.FailMsg("操作失败", "获取货币列表及汇率失败, Err: "+e.Error(), c)
  979. return
  980. }
  981. var rate float64
  982. for i := range rateList {
  983. if rateList[i].Code == req.CurrencyUnit {
  984. rate = rateList[i].RMBRate
  985. break
  986. }
  987. }
  988. if rate < 0 {
  989. resp.FailMsg("操作失败", "货币汇率有误", c)
  990. return
  991. }
  992. item.CurrencyUnit = req.CurrencyUnit
  993. item.RMBRate = rate
  994. updateCols = append(updateCols, "CurrencyUnit", "RMBRate")
  995. // 调整开票到款换算后的金额, 保留两位小数
  996. for i := range invoiceList {
  997. invoiceList[i].CurrencyUnit = req.CurrencyUnit
  998. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceList[i].OriginAmount/rate), 64)
  999. invoiceList[i].Amount = a
  1000. }
  1001. invoiceUpdateCols = append(invoiceUpdateCols, "CurrencyUnit", "Amount")
  1002. invoiceHandleType = 1
  1003. logRemark = fmt.Sprintf("金额单位由%s修改为%s\n%s", item.CurrencyUnit, req.CurrencyUnit, logRemark)
  1004. }
  1005. }
  1006. // 新增套餐金额详情内容
  1007. serviceAmountMap := make(map[int]float64)
  1008. serviceAmountList, e := fmsService.HandleContractServiceAmount(req.ServiceAmount, serviceAmountMap, req.CurrencyUnit)
  1009. if e != nil {
  1010. resp.FailMsg("操作失败", "新增合同套餐金额信息失败, Err: "+e.Error(), c)
  1011. return
  1012. }
  1013. //判断产品信息
  1014. productIds := make(map[int]struct{})
  1015. productIdsStr := ""
  1016. for _, v := range serviceAmountList {
  1017. productIds[v.ProductId] = struct{}{}
  1018. }
  1019. for proId, _ := range productIds {
  1020. productIdsStr += strconv.Itoa(proId) + ","
  1021. }
  1022. productIdsStr = strings.Trim(productIdsStr, ",")
  1023. item.ProductIds = productIdsStr
  1024. // 套餐信息
  1025. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  1026. if e != nil {
  1027. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  1028. return
  1029. }
  1030. // 更新合同登记、套餐、开票到款
  1031. if e = fms.UpdateContractRegister(item, updateCols, serviceList, invoiceList, invoiceUpdateCols, invoiceHandleType, serviceAmountList); e != nil {
  1032. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  1033. return
  1034. }
  1035. // 自动分配套餐金额
  1036. go fmsService.CalculatePaymentServiceAmount(item.ContractRegisterId)
  1037. // 校验金额-是否修改状态
  1038. go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
  1039. // 操作日志
  1040. go func() {
  1041. opData := ""
  1042. opDataByte, e := json.Marshal(req)
  1043. if e != nil {
  1044. return
  1045. }
  1046. opData = string(opDataByte)
  1047. logItem := new(fms.ContractRegisterLog)
  1048. logItem.ContractRegisterId = item.ContractRegisterId
  1049. logItem.AdminId = int(adminInfo.AdminId)
  1050. logItem.AdminName = adminInfo.RealName
  1051. logItem.OpData = opData
  1052. logItem.OpType = fms.ContractRegisterOpTypeEdit
  1053. logItem.CreateTime = nowTime
  1054. logItem.Remark = logRemark
  1055. if e = logItem.Create(); e != nil {
  1056. return
  1057. }
  1058. }()
  1059. resp.Ok("操作成功", c)
  1060. }
  1061. // Del
  1062. // @Title 删除合同登记
  1063. // @Description 删除合同登记
  1064. // @Param request body fms.ContractRegisterDelReq true "type json string"
  1065. // @Success 200 string "操作成功"
  1066. // @router /contract/register/del [post]
  1067. func (rg *RegisterController) Del(c *gin.Context) {
  1068. req := new(fms.ContractRegisterDelReq)
  1069. err := c.ShouldBind(&req)
  1070. if err != nil {
  1071. errs, ok := err.(validator.ValidationErrors)
  1072. if !ok {
  1073. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  1074. return
  1075. }
  1076. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  1077. return
  1078. }
  1079. claims, _ := c.Get("adminInfo")
  1080. adminInfo := claims.(*system.SysAdmin)
  1081. ob := new(fms.ContractRegister)
  1082. item, e := ob.Fetch(req.ContractRegisterId)
  1083. if e != nil {
  1084. if e == utils.ErrNoRow {
  1085. resp.Fail("合同登记不存在或已被删除", c)
  1086. return
  1087. }
  1088. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  1089. return
  1090. }
  1091. nowTime := time.Now().Local()
  1092. item.IsDeleted = 1
  1093. item.ModifyTime = nowTime
  1094. updateCols := []string{"IsDeleted", "ModifyTime"}
  1095. if e = item.Update(updateCols); e != nil {
  1096. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  1097. return
  1098. }
  1099. // 删除对应的开票到款登记
  1100. go func() {
  1101. if e = fms.DeleteContractInvoicesByRegisterId(item.ContractRegisterId); e != nil {
  1102. alarm_msg.SendAlarmMsg(fmt.Sprintf("删除合同登记%d后, 删除开票到款记录失败, ErrMsg: %s", item.ContractRegisterId, e.Error()), 3)
  1103. return
  1104. }
  1105. if e = fms.DeleteInvoicePaymentSummaryByRegisterId(item.ContractRegisterId); e != nil {
  1106. alarm_msg.SendAlarmMsg(fmt.Sprintf("删除合同登记%d后, 删除开票到款汇总数据失败, ErrMsg: %s", item.ContractRegisterId, e.Error()), 3)
  1107. return
  1108. }
  1109. }()
  1110. // 操作日志
  1111. go func() {
  1112. opData := ""
  1113. opDataByte, e := json.Marshal(req)
  1114. if e != nil {
  1115. return
  1116. }
  1117. opData = string(opDataByte)
  1118. logItem := new(fms.ContractRegisterLog)
  1119. logItem.ContractRegisterId = req.ContractRegisterId
  1120. logItem.AdminId = int(adminInfo.AdminId)
  1121. logItem.AdminName = adminInfo.RealName
  1122. logItem.OpData = opData
  1123. logItem.OpType = fms.ContractRegisterOpTypeDel
  1124. logItem.CreateTime = nowTime
  1125. if e = logItem.Create(); e != nil {
  1126. return
  1127. }
  1128. }()
  1129. resp.Ok("操作成功", c)
  1130. }
  1131. // Detail
  1132. // @Title 合同登记详情
  1133. // @Description 合同登记详情
  1134. // @Param ContractRegisterId query int false "合同登记ID"
  1135. // @Success 200 {object} fms.ContractRegisterDetail
  1136. // @router /contract/register/detail [get]
  1137. func (rg *RegisterController) Detail(c *gin.Context) {
  1138. var req fms.ContractRegisterDetailReq
  1139. if e := c.BindQuery(&req); e != nil {
  1140. err, ok := e.(validator.ValidationErrors)
  1141. if !ok {
  1142. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1143. return
  1144. }
  1145. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1146. return
  1147. }
  1148. result := new(fms.ContractRegisterDetail)
  1149. // 合同登记信息
  1150. item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
  1151. if e != nil {
  1152. resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
  1153. return
  1154. }
  1155. if item.SellerId != 0 {
  1156. item.SellerIds = strconv.Itoa(item.SellerId)
  1157. if item.RaiSellerId != 0 {
  1158. item.SellerIds += "," + strconv.Itoa(item.RaiSellerId)
  1159. }
  1160. } else {
  1161. if item.RaiSellerId != 0 {
  1162. item.SellerIds = strconv.Itoa(item.RaiSellerId)
  1163. }
  1164. }
  1165. item.SellerIds = strings.Trim(item.SellerIds, ",")
  1166. result.ContractRegisterItem = item
  1167. // 套餐信息
  1168. serviceAmountTempList, e := fms.GetContractServiceAmountByRegisterId(req.ContractRegisterId)
  1169. if e != nil {
  1170. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  1171. return
  1172. }
  1173. serviceAmountList := make([]*fms.ContractServiceAmountItem, 0)
  1174. for _, v := range serviceAmountTempList {
  1175. tmp := &fms.ContractServiceAmountItem{
  1176. ContractRegisterId: v.ContractRegisterId,
  1177. ProductId: v.ProductId,
  1178. ServiceAmount: v.ServiceAmount,
  1179. CurrencyUnit: v.CurrencyUnit,
  1180. }
  1181. serviceAmountList = append(serviceAmountList, tmp)
  1182. }
  1183. result.ServiceAmountList = serviceAmountList
  1184. // 套餐金额信息
  1185. serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
  1186. if e != nil {
  1187. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  1188. return
  1189. }
  1190. result.ServiceList = serviceList
  1191. // 开票/到款信息
  1192. invoiceCond := `contract_register_id = ?`
  1193. invoicePars := make([]interface{}, 0)
  1194. invoicePars = append(invoicePars, req.ContractRegisterId)
  1195. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  1196. if e != nil {
  1197. resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
  1198. return
  1199. }
  1200. result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
  1201. result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
  1202. for i := range invoiceList {
  1203. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake || invoiceList[i].InvoiceType == fms.ContractInvoiceTypePreMake {
  1204. result.InvoiceList = append(result.InvoiceList, invoiceList[i])
  1205. continue
  1206. }
  1207. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay || invoiceList[i].InvoiceType == fms.ContractInvoiceTypePrePay {
  1208. result.PaymentList = append(result.PaymentList, invoiceList[i])
  1209. }
  1210. }
  1211. // 合同登记进度
  1212. logCond := `contract_register_id = ?`
  1213. logPars := make([]interface{}, 0)
  1214. logPars = append(logPars, req.ContractRegisterId)
  1215. logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
  1216. if e != nil {
  1217. resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
  1218. return
  1219. }
  1220. result.Logs = logList
  1221. resp.OkData("获取成功", result, c)
  1222. }
  1223. // UpdateStatus
  1224. // @Title 修改合同状态
  1225. // @Description 修改合同状态
  1226. // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
  1227. // @Success 200 string "操作成功"
  1228. // @router /contract/register/update_status [post]
  1229. func (rg *RegisterController) UpdateStatus(c *gin.Context) {
  1230. req := new(fms.ContractRegisterUpdateStatusReq)
  1231. err := c.ShouldBind(&req)
  1232. if err != nil {
  1233. errs, ok := err.(validator.ValidationErrors)
  1234. if !ok {
  1235. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  1236. return
  1237. }
  1238. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  1239. return
  1240. }
  1241. claims, _ := c.Get("adminInfo")
  1242. adminInfo := claims.(*system.SysAdmin)
  1243. ob := new(fms.ContractRegister)
  1244. item, e := ob.Fetch(req.ContractRegisterId)
  1245. if e != nil {
  1246. if e == utils.ErrNoRow {
  1247. resp.Fail("合同登记不存在或已被删除", c)
  1248. return
  1249. }
  1250. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  1251. return
  1252. }
  1253. nowTime := time.Now().Local()
  1254. item.ContractStatus = req.ContractStatus
  1255. item.ModifyTime = nowTime
  1256. updateCols := []string{"ContractStatus", "ModifyTime"}
  1257. if e = item.Update(updateCols); e != nil {
  1258. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  1259. return
  1260. }
  1261. // 校验金额-是否修改状态
  1262. fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  1263. // 操作日志
  1264. go func() {
  1265. opData := ""
  1266. opDataByte, e := json.Marshal(req)
  1267. if e != nil {
  1268. return
  1269. }
  1270. opData = string(opDataByte)
  1271. logItem := new(fms.ContractRegisterLog)
  1272. logItem.ContractRegisterId = req.ContractRegisterId
  1273. logItem.AdminId = int(adminInfo.AdminId)
  1274. logItem.AdminName = adminInfo.RealName
  1275. logItem.OpData = opData
  1276. logItem.OpType = fms.ContractRegisterOpTypeStatus
  1277. logItem.CreateTime = nowTime
  1278. if e = logItem.Create(); e != nil {
  1279. return
  1280. }
  1281. }()
  1282. resp.Ok("操作成功", c)
  1283. }
  1284. // Invoice
  1285. // @Title 开票/到款登记
  1286. // @Description 开票/到款登记
  1287. // @Param request body fms.ContractInvoiceSaveReq true "type json string"
  1288. // @Success 200 string "操作成功"
  1289. // @router /contract/register/invoice [post]
  1290. func (rg *RegisterController) Invoice(c *gin.Context) {
  1291. req := new(fms.ContractInvoiceSaveReq)
  1292. err := c.ShouldBind(&req)
  1293. if err != nil {
  1294. errs, ok := err.(validator.ValidationErrors)
  1295. if !ok {
  1296. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  1297. return
  1298. }
  1299. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  1300. return
  1301. }
  1302. claims, _ := c.Get("adminInfo")
  1303. adminInfo := claims.(*system.SysAdmin)
  1304. registerOB := new(fms.ContractRegister)
  1305. item, e := registerOB.Fetch(req.ContractRegisterId)
  1306. if e != nil {
  1307. if e == utils.ErrNoRow {
  1308. resp.Fail("合同登记不存在或已被删除", c)
  1309. return
  1310. }
  1311. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  1312. return
  1313. }
  1314. // 合同存在代付不允许开票/到款登记
  1315. if item.HasInvoice == 0 {
  1316. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  1317. return
  1318. }
  1319. noChangeInvoiceIds := make([]int, 0)
  1320. newInvoice := make([]*fms.ContractInvoice, 0)
  1321. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  1322. if len(req.AmountList) > 0 {
  1323. // 合同有效时长(计算付款方式)
  1324. dayDiff := item.EndDate.Sub(item.StartDate).Hours() / 24
  1325. // 获取销售分组信息
  1326. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  1327. if e != nil {
  1328. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  1329. return
  1330. }
  1331. for i := range sellerList {
  1332. sellerMap[sellerList[i].SellerId] = sellerList[i]
  1333. }
  1334. for i := range req.AmountList {
  1335. if req.AmountList[i].Amount <= 0 {
  1336. resp.Fail("登记金额有误", c)
  1337. return
  1338. }
  1339. if req.AmountList[i].InvoiceDate == "" {
  1340. resp.Fail("请选择日期", c)
  1341. return
  1342. }
  1343. if req.AmountList[i].ServiceProductId != 1 && req.AmountList[i].ServiceProductId != 2 {
  1344. resp.Fail("请选择套餐类型", c)
  1345. return
  1346. }
  1347. // 开票登记销售必填
  1348. if req.InvoiceType == fms.ContractInvoiceTypeMake && req.AmountList[i].SellerId <= 0 {
  1349. resp.Fail("请选择销售", c)
  1350. return
  1351. }
  1352. t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
  1353. if e != nil {
  1354. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  1355. return
  1356. }
  1357. if req.AmountList[i].InvoiceId > 0 {
  1358. v := &fms.ContractInvoice{
  1359. ContractInvoiceId: req.AmountList[i].InvoiceId,
  1360. Amount: req.AmountList[i].Amount,
  1361. OriginAmount: req.AmountList[i].OriginAmount,
  1362. CurrencyUnit: item.CurrencyUnit,
  1363. ServiceProductId: req.AmountList[i].ServiceProductId,
  1364. InvoiceDate: t,
  1365. AdminId: int(adminInfo.AdminId),
  1366. AdminName: adminInfo.RealName,
  1367. Remark: req.AmountList[i].Remark,
  1368. }
  1369. v.Set()
  1370. sellerItem := sellerMap[req.AmountList[i].SellerId]
  1371. if sellerItem == nil {
  1372. resp.Fail("销售信息异常", c)
  1373. return
  1374. }
  1375. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  1376. resp.Fail("销售类型和所选套餐类型不一致", c)
  1377. return
  1378. }
  1379. v.SellerId = sellerItem.SellerId
  1380. v.SellerName = sellerItem.SellerName
  1381. v.SellerGroupId = sellerItem.GroupId
  1382. v.SellerGroupName = sellerItem.GroupName
  1383. v.SellerTeamId = sellerItem.TeamId
  1384. v.SellerTeamName = sellerItem.TeamName
  1385. v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
  1386. if e = v.Update([]string{"Amount", "OriginAmount", "CurrencyUnit", "ServiceProductId", "InvoiceDate",
  1387. "AdminId", "AdminName", "Remark", "SellerId", "SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName"}); e != nil {
  1388. resp.FailMsg("操作失败", "更新到款登记失败, Err:"+e.Error(), c)
  1389. return
  1390. }
  1391. //修改对应到款的销售
  1392. summaryItem, err := fms.GetInvoicePaymentSummaryByRegisterIdAndInvoiceId(req.ContractRegisterId, req.AmountList[i].InvoiceId)
  1393. if err != nil {
  1394. resp.FailMsg("获取汇总数据失败", "修改到款销售时获取汇总数据失败, Err: "+err.Error(), c)
  1395. return
  1396. }
  1397. if summaryItem.PaymentId > 0 {
  1398. var paymentItem *fms.ContractInvoice
  1399. paymentItem.ContractInvoiceId = summaryItem.PaymentId
  1400. paymentItem.SellerId = sellerItem.SellerId
  1401. paymentItem.SellerName = sellerItem.SellerName
  1402. paymentItem.SellerGroupId = sellerItem.GroupId
  1403. paymentItem.SellerGroupName = sellerItem.GroupName
  1404. paymentItem.SellerTeamId = sellerItem.TeamId
  1405. paymentItem.SellerTeamName = sellerItem.TeamName
  1406. e = paymentItem.Update([]string{"SellerId", "SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName"})
  1407. if e != nil {
  1408. resp.FailMsg("更新到款销售失败", "更新到款销售失败, Err: "+e.Error(), c)
  1409. return
  1410. }
  1411. }
  1412. noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
  1413. continue
  1414. }
  1415. if req.AmountList[i].InvoiceId == 0 {
  1416. v := &fms.ContractInvoice{
  1417. ContractRegisterId: req.ContractRegisterId,
  1418. ContractCode: item.ContractCode,
  1419. Amount: req.AmountList[i].Amount,
  1420. OriginAmount: req.AmountList[i].OriginAmount,
  1421. CurrencyUnit: item.CurrencyUnit,
  1422. InvoiceType: req.InvoiceType,
  1423. ServiceProductId: req.AmountList[i].ServiceProductId,
  1424. InvoiceDate: t,
  1425. AdminId: int(adminInfo.AdminId),
  1426. AdminName: adminInfo.RealName,
  1427. Remark: req.AmountList[i].Remark,
  1428. }
  1429. v.Set()
  1430. // 开票登记-销售信息
  1431. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  1432. sellerItem := sellerMap[req.AmountList[i].SellerId]
  1433. if sellerItem == nil {
  1434. resp.Fail("销售信息异常", c)
  1435. return
  1436. }
  1437. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  1438. resp.Fail("销售类型和所选套餐类型不一致", c)
  1439. return
  1440. }
  1441. v.SellerId = sellerItem.SellerId
  1442. v.SellerName = sellerItem.SellerName
  1443. v.SellerGroupId = sellerItem.GroupId
  1444. v.SellerGroupName = sellerItem.GroupName
  1445. v.SellerTeamId = sellerItem.TeamId
  1446. v.SellerTeamName = sellerItem.TeamName
  1447. }
  1448. // 到款登记-付款方式
  1449. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1450. sellerItem := sellerMap[req.AmountList[i].SellerId]
  1451. if sellerItem == nil {
  1452. resp.Fail("销售信息异常", c)
  1453. return
  1454. }
  1455. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  1456. resp.Fail("销售类型和所选套餐类型不一致", c)
  1457. return
  1458. }
  1459. v.SellerId = sellerItem.SellerId
  1460. v.SellerName = sellerItem.SellerName
  1461. v.SellerGroupId = sellerItem.GroupId
  1462. v.SellerGroupName = sellerItem.GroupName
  1463. v.SellerTeamId = sellerItem.TeamId
  1464. v.SellerTeamName = sellerItem.TeamName
  1465. v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
  1466. }
  1467. newInvoice = append(newInvoice, v)
  1468. }
  1469. }
  1470. }
  1471. // 获取原有的登记信息
  1472. invoiceCond := `contract_register_id = ? AND invoice_type = ? `
  1473. invoicePars := make([]interface{}, 0)
  1474. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  1475. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  1476. if e != nil {
  1477. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  1478. return
  1479. }
  1480. // 比对原有和现有的登记信息
  1481. logList := make([]*fms.ContractRegisterLog, 0)
  1482. opData := ""
  1483. opDataByte, e := json.Marshal(req)
  1484. if e != nil {
  1485. return
  1486. }
  1487. opData = string(opDataByte)
  1488. opType := fms.ContractRegisterOpTypeInvoice
  1489. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1490. opType = fms.ContractRegisterOpTypePayment
  1491. }
  1492. nowTime := time.Now().Local()
  1493. // 需要删除的记录
  1494. deleteInvoiceIds := make([]int, 0)
  1495. for i := range originInvoiceList {
  1496. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  1497. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  1498. logList = append(logList, &fms.ContractRegisterLog{
  1499. ContractRegisterId: req.ContractRegisterId,
  1500. AdminId: int(adminInfo.AdminId),
  1501. AdminName: adminInfo.RealName,
  1502. OpData: opData,
  1503. OpType: opType,
  1504. CreateTime: nowTime,
  1505. AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  1506. })
  1507. }
  1508. }
  1509. // 新增的记录
  1510. if len(newInvoice) > 0 {
  1511. newAmount := decimal.NewFromFloat(0).Round(2)
  1512. for i := range newInvoice {
  1513. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  1514. newAmount = newAmount.Add(a)
  1515. }
  1516. ia, _ := newAmount.Round(2).Float64()
  1517. logList = append(logList, &fms.ContractRegisterLog{
  1518. ContractRegisterId: req.ContractRegisterId,
  1519. AdminId: int(adminInfo.AdminId),
  1520. AdminName: adminInfo.RealName,
  1521. OpData: opData,
  1522. OpType: opType,
  1523. CreateTime: nowTime,
  1524. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  1525. })
  1526. }
  1527. // 删除并新增登记
  1528. ob := new(fms.ContractInvoice)
  1529. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  1530. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  1531. return
  1532. }
  1533. //如果是开票,强制修改到款记录的销售
  1534. if len(newInvoice) > 0 && req.InvoiceType == fms.ContractInvoiceTypeMake {
  1535. invoiceItem, err := fms.GetContractInvoiceByRegisterIdAndType(req.ContractRegisterId)
  1536. if err != nil && err != utils.ErrNoRow {
  1537. resp.FailMsg("获取到款数据失败", "获取到款数据失败, Err: "+err.Error(), c)
  1538. return
  1539. }
  1540. if err == nil {
  1541. sellerItem := sellerMap[newInvoice[0].SellerId]
  1542. if sellerItem == nil {
  1543. resp.Fail("销售信息异常", c)
  1544. return
  1545. }
  1546. invoiceItem.SellerId = sellerItem.SellerId
  1547. invoiceItem.SellerName = sellerItem.SellerName
  1548. invoiceItem.SellerGroupId = sellerItem.GroupId
  1549. invoiceItem.SellerGroupName = sellerItem.GroupName
  1550. invoiceItem.SellerTeamId = sellerItem.TeamId
  1551. invoiceItem.SellerTeamName = sellerItem.TeamName
  1552. e = invoiceItem.Update([]string{"SellerId", "SellerName", "SellerGroupId", "SellerGroupName", "SellerTeamId", "SellerTeamName"})
  1553. if e != nil {
  1554. resp.FailMsg("更新到款销售失败", "更新到款销售失败, Err: "+e.Error(), c)
  1555. return
  1556. }
  1557. }
  1558. }
  1559. // todo 判断是否符合均分金额的条件,如果符合,需要生成金额分配记录表
  1560. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1561. err = fmsService.CalculatePaymentServiceAmount(req.ContractRegisterId)
  1562. if err != nil {
  1563. resp.FailMsg("自动分配金额失败", "自动分配金额失败, Err: "+err.Error(), c)
  1564. return
  1565. }
  1566. }
  1567. // 校验金额-是否修改状态
  1568. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  1569. // 开票到款汇总
  1570. go fmsService.SummaryInvoicePaymentByContractRegisterId(req.ContractRegisterId)
  1571. // 操作日志
  1572. go func() {
  1573. logOB := new(fms.ContractRegisterLog)
  1574. if e := logOB.AddInBatches(logList); e != nil {
  1575. return
  1576. }
  1577. }()
  1578. resp.Ok("操作成功", c)
  1579. }
  1580. // Export
  1581. // @Title 合同登记-导出
  1582. // @Description 合同登记-导出
  1583. // @Param Keyword query string false "关键词"
  1584. // @Param StartDate query string false "合同开始日期"
  1585. // @Param EndDate query string false "合同结束日期"
  1586. // @Param ServiceType query int false "套餐类型"
  1587. // @Param ContractType query string false "合同类型"
  1588. // @Param RegisterStatus query int false "登记状态"
  1589. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  1590. // @Success 200 string "操作成功"
  1591. // @router /contract/register/export [get]
  1592. func (rg *RegisterController) Export(c *gin.Context) {
  1593. var req fms.ContractRegisterListReq
  1594. if e := c.BindQuery(&req); e != nil {
  1595. err, ok := e.(validator.ValidationErrors)
  1596. if !ok {
  1597. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1598. return
  1599. }
  1600. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1601. return
  1602. }
  1603. cond := `1 = 1`
  1604. pars := make([]interface{}, 0)
  1605. // 合同编号/客户姓名/销售/实际使用方
  1606. if req.Keyword != "" {
  1607. kw := "%" + req.Keyword + "%"
  1608. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  1609. pars = append(pars, kw, kw, kw, kw)
  1610. }
  1611. if req.StartDate != "" && req.EndDate != "" {
  1612. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1613. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1614. cond += ` AND (create_time BETWEEN ? AND ?)`
  1615. pars = append(pars, st, ed)
  1616. }
  1617. if req.ContractType != "" {
  1618. newCond := ""
  1619. typeSlices := strings.Split(req.ContractType, ",")
  1620. for _, v := range typeSlices {
  1621. if v[:1] == "0" {
  1622. //自付
  1623. if v[1:] == "1" {
  1624. newCond += ` (contract_type = 1 AND has_payment=0) `
  1625. } else if v[1:] == "2" {
  1626. newCond += ` (contract_type = 2 AND has_payment=0) `
  1627. } else {
  1628. newCond += ` (contract_type = 4 AND has_payment=0) `
  1629. }
  1630. } else {
  1631. //代付
  1632. if v[1:] == "1" {
  1633. newCond += ` (contract_type = 1 AND has_payment=1) `
  1634. } else if v[1:] == "2" {
  1635. newCond += ` (contract_type = 2 AND has_payment=1) `
  1636. } else {
  1637. newCond += ` (contract_type = 4 AND has_payment=1) `
  1638. }
  1639. }
  1640. newCond += " OR "
  1641. }
  1642. newCond = strings.TrimRight(newCond, "OR ")
  1643. cond += " AND " + "(" + newCond + ")"
  1644. }
  1645. if req.RegisterStatus != 0 {
  1646. cond += ` AND register_status = ?`
  1647. pars = append(pars, req.RegisterStatus)
  1648. }
  1649. if req.ServiceTypes != "" {
  1650. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1651. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1652. if e != nil {
  1653. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1654. return
  1655. }
  1656. if len(registerIds) > 0 {
  1657. cond += ` AND contract_register_id IN ?`
  1658. pars = append(pars, registerIds)
  1659. } else {
  1660. cond += ` AND 1 = 2`
  1661. }
  1662. }
  1663. if req.ListParam == 1 {
  1664. cond += ` AND product_ids = '1' `
  1665. } else if req.ListParam == 2 {
  1666. cond += ` AND product_ids = '2' `
  1667. }
  1668. // 获取列表数据
  1669. cr := new(fms.ContractRegister)
  1670. list, e := cr.List(cond, pars)
  1671. if e != nil {
  1672. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  1673. return
  1674. }
  1675. if len(list) == 0 {
  1676. resp.Fail("无有效数据可导出", c)
  1677. return
  1678. }
  1679. registerIds := make([]int, 0)
  1680. for i := range list {
  1681. registerIds = append(registerIds, list[i].ContractRegisterId)
  1682. }
  1683. // 获取小套餐品种
  1684. cpCond := `product_id = ? AND permission_name <> ?`
  1685. cpPars := make([]interface{}, 0)
  1686. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  1687. cp := new(crm.ChartPermission)
  1688. permissionList, e := cp.List(cpCond, cpPars)
  1689. if e != nil {
  1690. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  1691. return
  1692. }
  1693. permissionLen := len(permissionList)
  1694. permissionNameIdMap := make(map[string]int)
  1695. for i := range permissionList {
  1696. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1697. }
  1698. // 获取所有FICC套餐服务
  1699. serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  1700. if e != nil {
  1701. resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  1702. return
  1703. }
  1704. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1705. otherService := make([]*fms.ContractServiceTemplateItem, 0)
  1706. for i := range serviceList {
  1707. if serviceList[i].Title != "FICC大套餐" && serviceList[i].Title != "FICC小套餐" {
  1708. otherService = append(otherService, serviceList[i])
  1709. }
  1710. }
  1711. otherServiceLen := len(otherService)
  1712. // 获取所有权益套餐服务
  1713. raiServiceList, e := fms.GetContractServiceTemplateAllByProductId(crm.CompanyProductRai)
  1714. if e != nil {
  1715. resp.FailData("获取权益套餐服务失败", "Err:"+e.Error(), c)
  1716. return
  1717. }
  1718. raiServiceIdMap := make(map[int]*fms.ContractServiceTemplateItem)
  1719. for i := range raiServiceList {
  1720. raiServiceIdMap[raiServiceList[i].ServiceTemplateId] = raiServiceList[i]
  1721. }
  1722. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1723. raiOtherService := make([]*fms.ContractServiceTemplateItem, 0)
  1724. raiServiceNotShowMap := make(map[int]struct{})
  1725. for _, v := range raiServiceList {
  1726. if v.Pid > 0 && raiServiceIdMap[v.Pid].Pid > 0 {
  1727. raiServiceNotShowMap[v.Pid] = struct{}{}
  1728. raiServiceNotShowMap[raiServiceIdMap[v.Pid].Pid] = struct{}{}
  1729. } else if v.Pid > 0 {
  1730. raiServiceNotShowMap[v.Pid] = struct{}{}
  1731. }
  1732. }
  1733. for _, v := range raiServiceList {
  1734. if _, ok := raiServiceNotShowMap[v.ServiceTemplateId]; !ok {
  1735. if v.Pid > 0 {
  1736. v.ParentTitle = raiServiceIdMap[v.Pid].Title
  1737. }
  1738. raiOtherService = append(raiOtherService, v)
  1739. }
  1740. }
  1741. otherServiceLen += len(raiOtherService)
  1742. //套餐金额map
  1743. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount)
  1744. // 套餐/开票/到款列表
  1745. serviceMap := make(map[int][]*fms.ContractServiceWithParentTitle)
  1746. serviceChartPermissionsMap := make(map[int][]int)
  1747. invoiceMap := make(map[int][]*fms.ContractInvoice)
  1748. paymentMap := make(map[int][]*fms.ContractInvoice)
  1749. maxInvoice := 0
  1750. maxPayment := 0
  1751. if len(registerIds) > 0 {
  1752. // 获取套餐信息
  1753. csCond := `cv.contract_register_id IN ?`
  1754. csPars := make([]interface{}, 0)
  1755. csPars = append(csPars, registerIds)
  1756. cs := new(fms.ContractService)
  1757. serviceList, e := cs.ListWithWithParentTitle(csCond, csPars)
  1758. if e != nil {
  1759. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  1760. return
  1761. }
  1762. for i := range serviceList {
  1763. cid := serviceList[i].ContractRegisterId
  1764. if serviceMap[cid] == nil {
  1765. serviceMap[cid] = make([]*fms.ContractServiceWithParentTitle, 0)
  1766. }
  1767. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  1768. // 小套餐权限
  1769. if serviceChartPermissionsMap[cid] == nil {
  1770. serviceChartPermissionsMap[cid] = make([]int, 0)
  1771. }
  1772. if serviceList[i].ChartPermissionIds != "" {
  1773. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  1774. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  1775. }
  1776. }
  1777. // 获取合同的套餐金额信息
  1778. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(registerIds)
  1779. if e != nil {
  1780. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1781. return
  1782. }
  1783. for _, v := range serviceAmountList {
  1784. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1785. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1786. }
  1787. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1788. }
  1789. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  1790. ci := new(fms.ContractInvoice)
  1791. csCond = `contract_register_id IN ?`
  1792. csPars = make([]interface{}, 0)
  1793. csPars = append(csPars, registerIds)
  1794. invoiceList, e := ci.List(csCond, csPars, "")
  1795. if e != nil {
  1796. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1797. return
  1798. }
  1799. for k := range invoiceList {
  1800. cid := invoiceList[k].ContractRegisterId
  1801. if invoiceMap[cid] == nil {
  1802. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  1803. }
  1804. if paymentMap[cid] == nil {
  1805. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  1806. }
  1807. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  1808. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  1809. continue
  1810. }
  1811. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  1812. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  1813. continue
  1814. }
  1815. }
  1816. // 取最大开票/到款数
  1817. for j := range invoiceMap {
  1818. if len(invoiceMap[j]) > maxInvoice {
  1819. maxInvoice = len(invoiceMap[j])
  1820. }
  1821. }
  1822. for p := range paymentMap {
  1823. if len(paymentMap[p]) > maxPayment {
  1824. maxPayment = len(paymentMap[p])
  1825. }
  1826. }
  1827. }
  1828. serviceProductIdMap := map[int]string{
  1829. 1: "FICC套餐",
  1830. 2: "权益套餐",
  1831. }
  1832. // 生成Excel文件
  1833. xlsxFile := xlsx.NewFile()
  1834. style := xlsx.NewStyle()
  1835. alignment := xlsx.Alignment{
  1836. Horizontal: "center",
  1837. Vertical: "center",
  1838. WrapText: true,
  1839. }
  1840. style.Alignment = alignment
  1841. style.ApplyAlignment = true
  1842. sheetName := "财务列表"
  1843. sheet, err := xlsxFile.AddSheet(sheetName)
  1844. if err != nil {
  1845. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1846. return
  1847. }
  1848. // 1行表头
  1849. hInt := 0
  1850. titleRow := sheet.AddRow()
  1851. titleRow.SetHeight(40)
  1852. // 1行1列-右合并两格, 下合并1行
  1853. cell1 := titleRow.AddCell()
  1854. if req.ListParam == 0 {
  1855. cell1.HMerge = 9
  1856. } else {
  1857. cell1.HMerge = 9
  1858. }
  1859. cell1.VMerge = 1
  1860. cell1.SetString("客户签约表")
  1861. cell1.SetStyle(style)
  1862. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  1863. titleRow.AddCell().SetString("")
  1864. titleRow.AddCell().SetString("")
  1865. titleRow.AddCell().SetString("")
  1866. titleRow.AddCell().SetString("")
  1867. titleRow.AddCell().SetString("")
  1868. titleRow.AddCell().SetString("")
  1869. titleRow.AddCell().SetString("")
  1870. titleRow.AddCell().SetString("")
  1871. hInt += 9
  1872. if req.ListParam == 0 {
  1873. //如果是全部的话要多一格
  1874. titleRow.AddCell().SetString("")
  1875. hInt += 1
  1876. }
  1877. // 1行2列
  1878. if req.ListParam != 2 {
  1879. cell2 := titleRow.AddCell()
  1880. cell2.VMerge = 1
  1881. cell2.SetString("FICC大套餐")
  1882. cell2.SetStyle(style)
  1883. hInt++
  1884. }
  1885. // 1行3列-右合并小套餐数
  1886. if permissionLen >= 1 && req.ListParam != 2 {
  1887. cell3 := titleRow.AddCell()
  1888. hInt++
  1889. cell3.HMerge = permissionLen - 1
  1890. cell3.VMerge = 1
  1891. cell3.SetString("FICC小套餐")
  1892. cell3.SetStyle(style)
  1893. // 同上右增单元格小套餐数-1的空白单元格用于合并
  1894. for i := 0; i < permissionLen-1; i++ {
  1895. titleRow.AddCell().SetString("")
  1896. hInt++
  1897. }
  1898. }
  1899. if req.ListParam != 2 {
  1900. for i := range otherService {
  1901. cellOther := titleRow.AddCell()
  1902. cellOther.VMerge = 1
  1903. hInt++
  1904. cellOther.SetString(otherService[i].Title)
  1905. cellOther.SetStyle(style)
  1906. }
  1907. }
  1908. if req.ListParam != 1 {
  1909. //权益大套餐
  1910. cell4 := titleRow.AddCell()
  1911. cell4.HMerge = 1
  1912. cell4.VMerge = 1
  1913. cell4.SetString("权益大套餐")
  1914. cell4.SetStyle(style)
  1915. titleRow.AddCell().SetString("")
  1916. hInt += 2
  1917. //权益分行业套餐
  1918. cell5 := titleRow.AddCell()
  1919. cell5.HMerge = 8
  1920. cell5.SetString("权益分行业套餐")
  1921. cell5.SetStyle(style)
  1922. titleRow.AddCell().SetString("")
  1923. titleRow.AddCell().SetString("")
  1924. titleRow.AddCell().SetString("")
  1925. titleRow.AddCell().SetString("")
  1926. titleRow.AddCell().SetString("")
  1927. titleRow.AddCell().SetString("")
  1928. titleRow.AddCell().SetString("")
  1929. titleRow.AddCell().SetString("")
  1930. }
  1931. //第二行,前面几个单元格用于第一行的合并
  1932. titleRow2 := sheet.AddRow()
  1933. titleRow2.SetHeight(30)
  1934. for i := 0; i < hInt; i++ {
  1935. titleRow2.AddCell().SetString("")
  1936. }
  1937. if req.ListParam != 1 {
  1938. //权益分行业套餐
  1939. row2Cell1 := titleRow2.AddCell()
  1940. row2Cell1.HMerge = 1
  1941. row2Cell1.SetString("医药")
  1942. row2Cell1.SetStyle(style)
  1943. titleRow2.AddCell().SetString("")
  1944. row2Cell2 := titleRow2.AddCell()
  1945. row2Cell2.HMerge = 1
  1946. row2Cell2.SetString("消费")
  1947. row2Cell2.SetStyle(style)
  1948. titleRow2.AddCell().SetString("")
  1949. row2Cell3 := titleRow2.AddCell()
  1950. row2Cell3.HMerge = 1
  1951. row2Cell3.SetString("科技")
  1952. row2Cell3.SetStyle(style)
  1953. titleRow2.AddCell().SetString("")
  1954. row2Cell4 := titleRow2.AddCell()
  1955. row2Cell4.HMerge = 1
  1956. row2Cell4.SetString("智造")
  1957. row2Cell4.SetStyle(style)
  1958. titleRow2.AddCell().SetString("")
  1959. row2Cell5 := titleRow2.AddCell()
  1960. row2Cell5.SetString("策略")
  1961. row2Cell5.SetStyle(style)
  1962. }
  1963. // 第三行表头
  1964. titleRow3 := sheet.AddRow()
  1965. titleRow3.SetHeight(60)
  1966. row3Title := make([]string, 0)
  1967. row3TitleParent := make([]string, 0)
  1968. row3Title = append(row3Title, "客户名称", "新客户\n0-是\n1-否", "合同类型\n0-自付合同\n1-代付合同",
  1969. "合同子类型\n续约-0\n新签-1\n补充协议-2", "合同所属方", "代付方", "关联主合同(补充协议)", "关联合同(代付合同)")
  1970. if req.ListParam == 0 {
  1971. row3Title = append(row3Title, "FICC销售", "权益销售", "FICC大套餐")
  1972. for i := range permissionList {
  1973. row3Title = append(row3Title, permissionList[i].PermissionName)
  1974. }
  1975. // 其他套餐
  1976. for i := range otherService {
  1977. row3Title = append(row3Title, otherService[i].Title)
  1978. }
  1979. // 定义二级套餐名称
  1980. for i := range row3Title {
  1981. row3TitleParent = append(row3TitleParent, row3Title[i])
  1982. }
  1983. // 权益三级套餐
  1984. for i := range raiOtherService {
  1985. row3Title = append(row3Title, raiOtherService[i].Title)
  1986. if raiOtherService[i].ParentTitle != "" {
  1987. row3TitleParent = append(row3TitleParent, raiOtherService[i].ParentTitle)
  1988. } else {
  1989. row3TitleParent = append(row3TitleParent, raiOtherService[i].Title)
  1990. }
  1991. }
  1992. } else if req.ListParam == 1 {
  1993. row3Title = append(row3Title, "FICC销售", "FICC大套餐")
  1994. for i := range permissionList {
  1995. row3Title = append(row3Title, permissionList[i].PermissionName)
  1996. }
  1997. // 其他套餐
  1998. for i := range otherService {
  1999. row3Title = append(row3Title, otherService[i].Title)
  2000. }
  2001. // 定义二级套餐名称
  2002. for i := range row3Title {
  2003. row3TitleParent = append(row3TitleParent, row3Title[i])
  2004. }
  2005. } else {
  2006. row3Title = append(row3Title, "权益销售")
  2007. // 权益三级套餐
  2008. for i := range raiOtherService {
  2009. row3Title = append(row3Title, raiOtherService[i].Title)
  2010. if raiOtherService[i].ParentTitle != "" {
  2011. row3TitleParent = append(row3TitleParent, raiOtherService[i].ParentTitle)
  2012. } else {
  2013. row3TitleParent = append(row3TitleParent, raiOtherService[i].Title)
  2014. }
  2015. }
  2016. }
  2017. row3Title = append(row3Title, "套餐备注", "开始时间", "到期时间", "合同金额", "金额单位")
  2018. if req.ListParam == 0 {
  2019. row3Title = append(row3Title, "FICC套餐总金额", "权益套餐总金额")
  2020. }
  2021. row3Title = append(row3Title, "约定付款时间", "签订日", "合同状态", "合同编号", "合规备注")
  2022. // 设置表头
  2023. for i := range row3Title {
  2024. v := titleRow3.AddCell()
  2025. v.SetString(row3Title[i])
  2026. v.SetStyle(style)
  2027. }
  2028. // 第二行表头-开票/收款(动态添加)
  2029. invoiceTitle := []string{"开票日", "开票金额", "套餐类型", "销售", "备注"}
  2030. for i := 0; i < maxInvoice; i++ {
  2031. n := i + 1
  2032. for ii := range invoiceTitle {
  2033. c := titleRow3.AddCell()
  2034. t := fmt.Sprintf("%s%d", invoiceTitle[ii], n)
  2035. c.SetString(t)
  2036. c.SetStyle(style)
  2037. row3Title = append(row3Title, t)
  2038. }
  2039. }
  2040. paymentTitle := []string{"到款日", "到款金额", "套餐类型", "销售", "备注"}
  2041. for i := 0; i < maxPayment; i++ {
  2042. n := i + 1
  2043. for ii := range paymentTitle {
  2044. c := titleRow3.AddCell()
  2045. t := fmt.Sprintf("%s%d", paymentTitle[ii], n)
  2046. c.SetString(t)
  2047. c.SetStyle(style)
  2048. row3Title = append(row3Title, t)
  2049. }
  2050. }
  2051. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  2052. row2NameKeyMap := make(map[string]int)
  2053. for i := range row3Title {
  2054. row2NameKeyMap[row3Title[i]] = i
  2055. }
  2056. newCompanyMap := map[int]string{2: "1", 1: "0"}
  2057. contractTMap := map[int]int{
  2058. fms.ContractTypeSelf: 0,
  2059. fms.ContractTypebehalf: 1,
  2060. }
  2061. contractSubTMap := map[int]int{
  2062. fms.NewContractTypeNew: 1,
  2063. fms.NewContractTypeRenew: 0,
  2064. fms.NewContractTypePlus: 2, // 代付合同
  2065. }
  2066. for _, v := range list {
  2067. k := -1 // 套餐匹配用
  2068. dataRow := sheet.AddRow()
  2069. dataRow.SetHeight(20)
  2070. dataRow.AddCell().SetString(v.CompanyName)
  2071. dataRow.AddCell().SetString(newCompanyMap[v.ContractType])
  2072. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.HasPayment]))
  2073. dataRow.AddCell().SetString(fmt.Sprint(contractSubTMap[v.ContractType]))
  2074. if v.HasPayment == 1 {
  2075. if v.HasInvoice == 1 {
  2076. dataRow.AddCell().SetString("1")
  2077. } else {
  2078. dataRow.AddCell().SetString("0")
  2079. }
  2080. } else {
  2081. dataRow.AddCell().SetString("")
  2082. }
  2083. dataRow.AddCell().SetString(v.ActualPayCompanies)
  2084. dataRow.AddCell().SetString(v.RelateContractMainCode)
  2085. dataRow.AddCell().SetString(v.RelateContractCode)
  2086. if req.ListParam == 0 {
  2087. dataRow.AddCell().SetString(v.SellerName)
  2088. dataRow.AddCell().SetString(v.RaiSellerName)
  2089. } else if req.ListParam == 1 {
  2090. dataRow.AddCell().SetString(v.SellerName)
  2091. } else {
  2092. dataRow.AddCell().SetString(v.RaiSellerName)
  2093. }
  2094. if req.ListParam != 0 {
  2095. k += 10
  2096. } else {
  2097. k += 11
  2098. }
  2099. // 大套餐
  2100. col4Name := row3Title[k]
  2101. svList := serviceMap[v.ContractRegisterId]
  2102. col4 := ""
  2103. if svList != nil && len(svList) > 0 {
  2104. for isv := range svList {
  2105. if svList[isv].Title == col4Name {
  2106. col4 = "是"
  2107. break
  2108. }
  2109. }
  2110. }
  2111. dataRow.AddCell().SetString(col4)
  2112. // 小套餐
  2113. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  2114. for i := 0; i < permissionLen; i++ {
  2115. k += 1
  2116. colName := row3Title[k]
  2117. chartPermissionId := permissionNameIdMap[colName]
  2118. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  2119. dataRow.AddCell().SetString("是")
  2120. } else {
  2121. dataRow.AddCell().SetString("")
  2122. }
  2123. }
  2124. // 除大小套餐外的其他套餐(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  2125. for i := 0; i < otherServiceLen; i++ {
  2126. k += 1
  2127. otherColName := row3Title[k]
  2128. otherCol := ""
  2129. if svList != nil && len(svList) > 0 {
  2130. for isv := range svList {
  2131. if svList[isv].Title == otherColName {
  2132. // 判断权益套餐权限时,需要同时判断父级name
  2133. if otherColName == "主观" || otherColName == "客观" {
  2134. if row3TitleParent[k] == svList[isv].ParentTitle {
  2135. otherCol = "是"
  2136. break
  2137. }
  2138. } else {
  2139. otherCol = "是"
  2140. break
  2141. }
  2142. }
  2143. }
  2144. }
  2145. dataRow.AddCell().SetString(otherCol)
  2146. }
  2147. // 其他信息
  2148. ficcAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductFicc]
  2149. raiAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductRai]
  2150. dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
  2151. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  2152. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  2153. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 合同金额
  2154. dataRow.AddCell().SetString(v.CurrencyUnit) // 货币单位
  2155. if ficcAmount != nil {
  2156. dataRow.AddCell().SetString(fmt.Sprint("¥", ficcAmount.ServiceAmount)) // FICC套餐总金额
  2157. if raiAmount == nil {
  2158. dataRow.AddCell().SetString("") // 权益套餐总金额
  2159. }
  2160. }
  2161. if raiAmount != nil {
  2162. if ficcAmount == nil {
  2163. dataRow.AddCell().SetString("") // 权益套餐总金额
  2164. }
  2165. dataRow.AddCell().SetString(fmt.Sprint("¥", raiAmount.ServiceAmount)) // FICC套餐总金额
  2166. }
  2167. if ficcAmount == nil && raiAmount == nil {
  2168. dataRow.AddCell().SetString("") // FICC套餐总金额
  2169. dataRow.AddCell().SetString("") // 权益套餐总金额
  2170. }
  2171. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  2172. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  2173. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  2174. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  2175. dataRow.AddCell().SetString(v.Remark) // 合规备注
  2176. // 开票/到款信息
  2177. ivList := invoiceMap[v.ContractRegisterId]
  2178. ivListLen := len(ivList)
  2179. for ia := 0; ia < maxInvoice; ia++ {
  2180. if ia < ivListLen {
  2181. if ivList != nil && ivList[ia] != nil {
  2182. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  2183. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].OriginAmount)) // 开票金额
  2184. dataRow.AddCell().SetString(serviceProductIdMap[ivList[ia].ServiceProductId]) // 套餐类型
  2185. dataRow.AddCell().SetString(ivList[ia].SellerName) // 销售名称
  2186. dataRow.AddCell().SetString(ivList[ia].Remark) // 开票备注
  2187. continue
  2188. }
  2189. }
  2190. // 这里要把不够的填充为空
  2191. dataRow.AddCell().SetString("")
  2192. dataRow.AddCell().SetString("")
  2193. dataRow.AddCell().SetString("")
  2194. dataRow.AddCell().SetString("")
  2195. dataRow.AddCell().SetString("")
  2196. }
  2197. pyList := paymentMap[v.ContractRegisterId]
  2198. pyListLen := len(pyList)
  2199. for ib := 0; ib < maxPayment; ib++ {
  2200. if ib < pyListLen {
  2201. if pyList != nil && pyList[ib] != nil {
  2202. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  2203. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].OriginAmount)) // 收款金额
  2204. dataRow.AddCell().SetString(serviceProductIdMap[pyList[ib].ServiceProductId]) // 套餐类型
  2205. dataRow.AddCell().SetString(pyList[ib].SellerName) // 销售名称
  2206. dataRow.AddCell().SetString(pyList[ib].Remark) // 收款备注
  2207. continue
  2208. }
  2209. }
  2210. // 这里要把不够的填充为空
  2211. dataRow.AddCell().SetString("")
  2212. dataRow.AddCell().SetString("")
  2213. dataRow.AddCell().SetString("")
  2214. dataRow.AddCell().SetString("")
  2215. }
  2216. }
  2217. // 输出文件
  2218. var buffer bytes.Buffer
  2219. _ = xlsxFile.Write(&buffer)
  2220. content := bytes.NewReader(buffer.Bytes())
  2221. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2222. fileName := sheetName + randStr + ".xlsx"
  2223. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2224. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2225. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2226. }
  2227. // InvoiceList
  2228. // @Title 开票/到款列表
  2229. // @Description 开票/到款列表
  2230. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  2231. // @Param Keyword query string false "查询关键字"
  2232. // @Param StartDate query string false "开始日期"
  2233. // @Param EndDate query string false "结束日期"
  2234. // @Param MinAmount query float64 false "开票金额区间-最小值"
  2235. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  2236. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  2237. // @Success 200 {object} fms.ContractInvoiceItem
  2238. // @router /contract/register/invoice_list [get]
  2239. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  2240. var req fms.ContractInvoiceListReq
  2241. if e := c.BindQuery(&req); e != nil {
  2242. err, ok := e.(validator.ValidationErrors)
  2243. if !ok {
  2244. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  2245. return
  2246. }
  2247. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  2248. return
  2249. }
  2250. pageSize := req.PageSize
  2251. pageIndex := req.Current
  2252. if pageSize <= 0 {
  2253. pageSize = utils.PageSize20
  2254. }
  2255. if pageIndex <= 0 {
  2256. pageIndex = 1
  2257. }
  2258. cond := ``
  2259. if req.InvoiceType == 1 {
  2260. cond = `invoice_type IN (1,3)`
  2261. } else {
  2262. cond = `invoice_type IN (2,4)`
  2263. }
  2264. pars := make([]interface{}, 0)
  2265. // 搜索
  2266. if req.Keyword != "" {
  2267. kw := fmt.Sprint("%", req.Keyword, "%")
  2268. //pars = append(pars, kw)
  2269. cond += ` AND (b.company_name LIKE ? OR a.contract_code LIKE ?)`
  2270. pars = append(pars, kw, kw)
  2271. }
  2272. if req.StartDate != "" && req.EndDate != "" {
  2273. st := fmt.Sprint(req.StartDate, " 00:00:00")
  2274. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  2275. cond += ` AND (a.invoice_time BETWEEN ? AND ?)`
  2276. pars = append(pars, st, ed)
  2277. }
  2278. if req.MinAmount > 0 {
  2279. cond += ` AND a.amount >= ?`
  2280. pars = append(pars, req.MinAmount)
  2281. }
  2282. if req.MaxAmount > 0 {
  2283. cond += ` AND a.amount <= ?`
  2284. pars = append(pars, req.MaxAmount)
  2285. }
  2286. // 套餐类型
  2287. if req.ServiceProductId > 0 {
  2288. cond += ` AND a.service_product_id = ?`
  2289. pars = append(pars, req.ServiceProductId)
  2290. }
  2291. // 销售
  2292. if req.SellerIds != "" {
  2293. sellerIds := strings.Split(req.SellerIds, ",")
  2294. cond += ` AND (a.seller_id in (?))`
  2295. pars = append(pars, sellerIds)
  2296. }
  2297. // 货币列表
  2298. currencyOB := new(fms.CurrencyUnit)
  2299. currencyCond := `enable = 1`
  2300. currencyPars := make([]interface{}, 0)
  2301. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  2302. if e != nil {
  2303. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  2304. return
  2305. }
  2306. unitMap := make(map[string]string)
  2307. currencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  2308. for i := range currencyList {
  2309. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  2310. currencyTotals = append(currencyTotals, &fms.InvoiceListCurrencyTotal{
  2311. Name: currencyList[i].Name,
  2312. UnitName: currencyList[i].UnitName,
  2313. Code: currencyList[i].Code,
  2314. FlagImg: currencyList[i].FlagImg,
  2315. })
  2316. }
  2317. page := new(base.Page)
  2318. page.SetPageSize(pageSize)
  2319. page.SetCurrent(pageIndex)
  2320. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  2321. if req.IsExport == 1 {
  2322. page.SetPageSize(10000)
  2323. page.SetCurrent(1)
  2324. }
  2325. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  2326. if e != nil {
  2327. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  2328. return
  2329. }
  2330. page.SetTotal(total)
  2331. contractRegisterIds := make([]int, 0)
  2332. contractStatusMap := make(map[int]int)
  2333. for i := range list {
  2334. list[i].UnitName = unitMap[list[i].CurrencyUnit]
  2335. contractRegisterIds = append(contractRegisterIds, list[i].ContractRegisterId)
  2336. }
  2337. if len(contractRegisterIds) > 0 {
  2338. contractRegisters, err := fms.GetContractInfoByRegisterIds(contractRegisterIds)
  2339. if err != nil {
  2340. resp.FailMsg("查询合同信息失败", "查询合同信息失败, Err: "+err.Error(), c)
  2341. return
  2342. }
  2343. for _, v := range contractRegisters {
  2344. contractStatusMap[v.ContractRegisterId] = v.ContractStatus
  2345. }
  2346. }
  2347. for i := range list {
  2348. list[i].ContractStatus = contractStatusMap[list[i].ContractRegisterId]
  2349. }
  2350. // 分币种合计金额
  2351. var amountTotal float64
  2352. sumList, e := fms.GetInvoiceListCurrencySum(cond, pars, "currency_unit")
  2353. if e != nil {
  2354. resp.FailMsg("获取失败", "获取开票/到款列表合计金额失败, Err: "+e.Error(), c)
  2355. return
  2356. }
  2357. sumMap := make(map[string]float64)
  2358. for i := range sumList {
  2359. amountTotal += sumList[i].AmountTotal
  2360. sumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  2361. }
  2362. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotal), 64)
  2363. for i := range currencyTotals {
  2364. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", sumMap[currencyTotals[i].Code]), 64)
  2365. currencyTotals[i].Amount = a
  2366. }
  2367. respData := &fms.InvoiceListRespData{
  2368. Page: page,
  2369. List: list,
  2370. AmountTotal: amountTotal,
  2371. CurrencyTotal: currencyTotals,
  2372. }
  2373. // 是否导出
  2374. if req.IsExport == 1 {
  2375. ExportInvoiceList(c, req, respData)
  2376. return
  2377. }
  2378. resp.OkData("获取成功", respData, c)
  2379. }
  2380. // ExportInvoiceList 导出开票/到款列表
  2381. func ExportInvoiceList(c *gin.Context, req fms.ContractInvoiceListReq, results *fms.InvoiceListRespData) {
  2382. list := make([]*fms.ContractInvoiceItem, 0)
  2383. if val, ok := results.List.([]*fms.ContractInvoiceItem); ok {
  2384. list = val
  2385. } else {
  2386. resp.Fail("列表数据有误", c)
  2387. return
  2388. }
  2389. if len(list) == 0 {
  2390. resp.Fail("列表数据为空", c)
  2391. return
  2392. }
  2393. listName := "开票"
  2394. if req.InvoiceType == fms.ContractInvoiceTypePay {
  2395. listName = "到款"
  2396. }
  2397. // 生成Excel文件
  2398. xlsxFile := xlsx.NewFile()
  2399. style := xlsx.NewStyle()
  2400. alignment := xlsx.Alignment{
  2401. Horizontal: "center",
  2402. Vertical: "center",
  2403. WrapText: true,
  2404. }
  2405. style.Alignment = alignment
  2406. style.ApplyAlignment = true
  2407. sheet, err := xlsxFile.AddSheet(fmt.Sprintf("%s列表", listName))
  2408. if err != nil {
  2409. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  2410. return
  2411. }
  2412. // 前两行显示合计金额, 第三行空出与列表数据隔一行
  2413. rowA := sheet.AddRow()
  2414. cellAA := rowA.AddCell()
  2415. rowBData := ""
  2416. if req.InvoiceType == 1 {
  2417. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.AmountTotal))
  2418. rowBData = "已开票金额:"
  2419. } else {
  2420. cellAA.SetString(fmt.Sprintf("已到款合计金额(换算后):%.2f(元)", results.AmountTotal))
  2421. rowBData = "已到款金额:"
  2422. }
  2423. for _, v := range results.CurrencyTotal {
  2424. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  2425. }
  2426. rowB := sheet.AddRow()
  2427. rowB.AddCell().SetString(rowBData)
  2428. sheet.AddRow()
  2429. // 列表数据表头
  2430. titles := []string{"客户名称", "合同编号", "套餐类型", fmt.Sprintf("%s金额", listName), "金额单位", "换算金额(元)",
  2431. fmt.Sprintf("%s日期", listName), "备注"}
  2432. titleRow := sheet.AddRow()
  2433. titleRow.SetHeight(40)
  2434. for i := range titles {
  2435. c := titleRow.AddCell()
  2436. c.SetString(titles[i])
  2437. c.SetStyle(style)
  2438. }
  2439. ServiceTemplateStrMap := map[int]string{
  2440. crm.CompanyProductFicc: "FICC套餐",
  2441. crm.CompanyProductRai: "权益套餐",
  2442. }
  2443. // 单元格赋值
  2444. for _, v := range list {
  2445. dataRow := sheet.AddRow()
  2446. dataRow.SetHeight(20)
  2447. dataRow.AddCell().SetString(v.CompanyName) // 客户名称
  2448. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  2449. dataRow.AddCell().SetString(ServiceTemplateStrMap[v.ServiceProductId]) // 套餐类型
  2450. dataRow.AddCell().SetString(fmt.Sprint(v.OriginAmount)) // 开票金额
  2451. dataRow.AddCell().SetString(v.UnitName) // 金额单位
  2452. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 换算金额(元)
  2453. dataRow.AddCell().SetString(v.InvoiceDate) // 开票日
  2454. dataRow.AddCell().SetString(v.Remark) // 备注
  2455. }
  2456. // 输出文件
  2457. var buffer bytes.Buffer
  2458. _ = xlsxFile.Write(&buffer)
  2459. content := bytes.NewReader(buffer.Bytes())
  2460. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2461. fileName := fmt.Sprintf("%s列表_%s.xlsx", listName, randStr)
  2462. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  2463. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  2464. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  2465. }
  2466. // Import
  2467. // @Title 合同登记-导入
  2468. // @Description 合同登记-导入
  2469. // @Success 200 string "操作成功"
  2470. // @router /contract/register/import [post]
  2471. func (rg *RegisterController) Import(c *gin.Context) {
  2472. h, err := c.FormFile("File")
  2473. if err != nil {
  2474. resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  2475. return
  2476. }
  2477. ext := path.Ext(h.Filename)
  2478. if ext != ".xlsx" && ext != ".xls" {
  2479. resp.Fail("请上传Excel文件", c)
  2480. return
  2481. }
  2482. claims, _ := c.Get("adminInfo")
  2483. adminInfo := claims.(*system.SysAdmin)
  2484. uploadDir := "static/xls"
  2485. err = os.MkdirAll(uploadDir, 766)
  2486. if err != nil {
  2487. resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  2488. return
  2489. }
  2490. uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  2491. err = c.SaveUploadedFile(h, uploadPath)
  2492. if err != nil {
  2493. resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  2494. return
  2495. }
  2496. defer func() {
  2497. _ = os.Remove(uploadPath)
  2498. }()
  2499. xlFile, err := xlsx.OpenFile(uploadPath)
  2500. if err != nil {
  2501. resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  2502. return
  2503. }
  2504. logList := make([]*fms.ContractRegisterLog, 0)
  2505. // 获取所有已登记,根据合同编号去重
  2506. contractCodeArr := make([]string, 0)
  2507. registerOB := new(fms.ContractRegister)
  2508. registerCond := ``
  2509. registerPars := make([]interface{}, 0)
  2510. registerList, e := registerOB.List(registerCond, registerPars)
  2511. if e != nil {
  2512. resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  2513. return
  2514. }
  2515. for i := range registerList {
  2516. contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  2517. }
  2518. // 获取所有销售Map
  2519. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  2520. if e != nil {
  2521. resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  2522. return
  2523. }
  2524. sellerMap := make(map[string]*crm.SellerAdminWithGroupTeam)
  2525. for i := range sellerList {
  2526. sellerMap[sellerList[i].SellerName] = sellerList[i]
  2527. }
  2528. // 获取品种权限Map
  2529. chartPermissionNameIdMap := make(map[string]int)
  2530. cpCond := `product_id = ?`
  2531. cpPars := make([]interface{}, 0)
  2532. cpPars = append(cpPars, crm.CompanyProductFicc)
  2533. cp := new(crm.ChartPermission)
  2534. permissionList, e := cp.List(cpCond, cpPars)
  2535. if e != nil {
  2536. resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  2537. return
  2538. }
  2539. for i := range permissionList {
  2540. chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  2541. }
  2542. // 获取所有套餐模板
  2543. serviceTempCond := ``
  2544. serviceTempPars := make([]interface{}, 0)
  2545. serviceTempOB := new(fms.ContractServiceTemplate)
  2546. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  2547. if e != nil {
  2548. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  2549. return
  2550. }
  2551. serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
  2552. serviceTempFullNameMap := make(map[string]*fms.ContractServiceTemplate)
  2553. serviceTempIdMap := make(map[int]*fms.ContractServiceTemplate)
  2554. for i := range serviceTempList {
  2555. serviceTempIdMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  2556. serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
  2557. }
  2558. for i := range serviceTempList {
  2559. fullName := serviceTempList[i].Title
  2560. if serviceTempList[i].Pid > 0 {
  2561. parentItem := serviceTempIdMap[serviceTempList[i].Pid]
  2562. fullName += "_" + parentItem.Title
  2563. if parentItem.Pid > 0 {
  2564. fullName += "_" + serviceTempIdMap[parentItem.Pid].Title
  2565. }
  2566. }
  2567. serviceTempFullNameMap[fullName] = serviceTempList[i]
  2568. }
  2569. //权益行业套餐名称
  2570. raiIndustryMap := map[int]string{
  2571. 43: "医药",
  2572. 44: "医药",
  2573. 45: "消费",
  2574. 46: "消费",
  2575. 47: "科技",
  2576. 48: "科技",
  2577. 49: "智造",
  2578. 50: "智造",
  2579. 51: "策略",
  2580. }
  2581. // 获取货币列表及汇率(汇率为导入日的汇率)
  2582. rateList, e := fmsService.GetTodayCurrencyRateList()
  2583. if e != nil {
  2584. resp.FailData("获取货币列表及汇率失败", "Err:"+e.Error(), c)
  2585. return
  2586. }
  2587. rateMap := make(map[string]float64)
  2588. for i := range rateList {
  2589. rateMap[rateList[i].Code] = rateList[i].RMBRate
  2590. }
  2591. titleMap := make(map[int]string)
  2592. newIds := make([]int, 0)
  2593. newCompanyArr := []string{"0", "1"}
  2594. newCompanyMap := map[string]int{"0": 1, "1": 0}
  2595. contractTypeArr := []string{"0", "1"}
  2596. contractTMap := map[string]int{
  2597. "0": fms.ContractTypeSelf,
  2598. "1": fms.ContractTypebehalf,
  2599. }
  2600. contractSubTypeArr := []string{"0", "1", "2"}
  2601. contractSubTMap := map[string]int{
  2602. "1": fms.NewContractTypeNew,
  2603. "0": fms.NewContractTypeRenew,
  2604. "2": fms.NewContractTypePlus,
  2605. }
  2606. // 更新登记状态
  2607. defer func() {
  2608. if len(newIds) > 0 {
  2609. go func() {
  2610. for i := range newIds {
  2611. fmsService.CheckContractRegisterAmount(newIds[i])
  2612. fmsService.SummaryInvoicePaymentByContractRegisterId(newIds[i])
  2613. }
  2614. }()
  2615. }
  2616. }()
  2617. invoiceMax := 3
  2618. checkDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local)
  2619. for _, sheet := range xlFile.Sheets {
  2620. // 遍历行读取
  2621. maxRow := sheet.MaxRow
  2622. fmt.Println("maxRow", maxRow)
  2623. var dayDiff float64
  2624. for i := 0; i < maxRow; i++ {
  2625. // 第三行开始读取表头
  2626. if i == 2 {
  2627. row := sheet.Row(i)
  2628. cells := row.Cells
  2629. for k, cell := range cells {
  2630. text := cell.String()
  2631. titleMap[k] = text
  2632. // 只检验前面部分表头, 后面很多动态列
  2633. if k == 0 {
  2634. if text != "客户名称" {
  2635. resp.Fail("【客户名称】列名称有误, 请参考模板导入", c)
  2636. return
  2637. }
  2638. continue
  2639. } else if k == 1 {
  2640. if !strings.Contains(text, "新客户") {
  2641. resp.Fail("【新客户】列名称有误, 请参考模板导入", c)
  2642. return
  2643. }
  2644. continue
  2645. } else if k == 2 {
  2646. if !strings.Contains(text, "合同类型") {
  2647. resp.Fail("【合同类型】列名称有误, 请参考模板导入", c)
  2648. return
  2649. }
  2650. continue
  2651. } else if k == 3 {
  2652. if !strings.Contains(text, "合同子类型") {
  2653. resp.Fail("【合同子类型】列名称有误, 请参考模板导入", c)
  2654. return
  2655. }
  2656. continue
  2657. } else if k == 4 {
  2658. if !strings.Contains(text, "合同所属方") {
  2659. resp.Fail("【合同所属方】列名称有误, 请参考模板导入", c)
  2660. return
  2661. }
  2662. continue
  2663. } else if k == 5 {
  2664. if text != "代付方" {
  2665. resp.Fail("【代付方】列名称有误, 请参考模板导入", c)
  2666. return
  2667. }
  2668. continue
  2669. } else if k == 6 {
  2670. if !strings.Contains(text, "关联主合同(补充协议)") {
  2671. resp.Fail("【关联主合同】列名称有误, 请参考模板导入", c)
  2672. return
  2673. }
  2674. continue
  2675. } else if k == 7 {
  2676. if !strings.Contains(text, "关联合同") {
  2677. resp.Fail("【关联合同】列名称有误, 请参考模板导入", c)
  2678. return
  2679. }
  2680. continue
  2681. } else if k == 8 {
  2682. if text != "FICC销售" {
  2683. resp.Fail("【FICC销售】列名称有误, 请参考模板导入", c)
  2684. return
  2685. }
  2686. continue
  2687. } else if k == 9 {
  2688. if text != "权益销售" {
  2689. resp.Fail("【权益销售】列名称有误, 请参考模板导入", c)
  2690. return
  2691. }
  2692. continue
  2693. } else if k == 10 {
  2694. if text != "FICC大套餐" {
  2695. resp.Fail("【FICC大套餐】列名称有误, 请参考模板导入", c)
  2696. return
  2697. }
  2698. continue
  2699. }
  2700. }
  2701. } else if i >= 3 {
  2702. // 数据行
  2703. row := sheet.Row(i)
  2704. cells := row.Cells
  2705. // 登记信息
  2706. rowRegister := new(fms.ContractRegister)
  2707. // 套餐
  2708. rowServices := make([]*fms.ContractService, 0)
  2709. // 套餐金额
  2710. rowServiceAmount := make([]*fms.ContractServiceAmount, 0)
  2711. // 开票/到款
  2712. rowInvoices := make([]*fms.ContractInvoice, 0)
  2713. for ir := 0; ir < invoiceMax; ir++ {
  2714. rowInvoices = append(rowInvoices, new(fms.ContractInvoice))
  2715. }
  2716. rowPayments := make([]*fms.ContractInvoice, 0)
  2717. for ir := 0; ir < invoiceMax; ir++ {
  2718. rowPayments = append(rowPayments, new(fms.ContractInvoice))
  2719. }
  2720. // 小套餐权限
  2721. rowChartPermissionIdArr := make([]string, 0)
  2722. productIds := make(map[int]struct{})
  2723. isSkip := false
  2724. for k, cell := range cells {
  2725. fmt.Println("k:", k)
  2726. fmt.Println("cell:", cell.Value)
  2727. v := utils.TrimStr(cell.String())
  2728. // 客户名称
  2729. if k == 0 {
  2730. //pool_474 客户名称保留空格
  2731. if cell.String() == "" {
  2732. resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
  2733. return
  2734. }
  2735. rowRegister.CompanyName = cell.String()
  2736. continue
  2737. }
  2738. // 是否新客户
  2739. if k == 1 {
  2740. if !utils.InArrayByStr(newCompanyArr, v) {
  2741. resp.Fail(fmt.Sprintf("第%d行新客户有误, 请按模板导入", i+1), c)
  2742. return
  2743. }
  2744. rowRegister.NewCompany = newCompanyMap[v]
  2745. continue
  2746. }
  2747. // 合同类型
  2748. if k == 2 {
  2749. if !utils.InArrayByStr(contractTypeArr, v) {
  2750. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  2751. return
  2752. }
  2753. rowRegister.HasPayment = contractTMap[v]
  2754. continue
  2755. }
  2756. if k == 3 {
  2757. if !utils.InArrayByStr(contractSubTypeArr, v) {
  2758. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  2759. return
  2760. }
  2761. rowRegister.ContractType = contractSubTMap[v]
  2762. if rowRegister.ContractType == 0 {
  2763. resp.Fail(fmt.Sprintf("第%d行合同子类型匹配有误, 请按模板导入", i+1), c)
  2764. return
  2765. }
  2766. continue
  2767. }
  2768. if k == 4 {
  2769. if rowRegister.HasPayment == 1 {
  2770. if v == "0" {
  2771. //所属方为实际使用方,不走开票到款流程
  2772. rowRegister.HasInvoice = 0
  2773. } else if v == "1" {
  2774. rowRegister.HasInvoice = 1
  2775. }
  2776. } else {
  2777. rowRegister.HasInvoice = 1
  2778. }
  2779. continue
  2780. }
  2781. if k == 5 {
  2782. rowRegister.ActualPayCompanies = v
  2783. continue
  2784. }
  2785. if k == 6 {
  2786. rowRegister.RelateContractMainCode = v
  2787. continue
  2788. }
  2789. if k == 7 {
  2790. rowRegister.RelateContractCode = v
  2791. continue
  2792. }
  2793. // FICC销售
  2794. if k == 8 {
  2795. if v != "" {
  2796. /*resp.Fail(fmt.Sprintf("第%d行销售名称不可为空, 请按模板导入", i+1), c)
  2797. return*/
  2798. sellerItem := sellerMap[v]
  2799. if sellerItem == nil {
  2800. resp.Fail(fmt.Sprintf("第%d行销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2801. return
  2802. }
  2803. rowRegister.SellerId = sellerItem.SellerId
  2804. rowRegister.SellerName = sellerItem.SellerName
  2805. }
  2806. continue
  2807. }
  2808. // 权益销售
  2809. if k == 9 {
  2810. if v == "" && rowRegister.SellerName == "" {
  2811. resp.Fail(fmt.Sprintf("第FICC销售名称和权益销售名称不可都为空, 请按模板导入", i+1), c)
  2812. return
  2813. }
  2814. sellerItem := sellerMap[v]
  2815. if sellerItem == nil {
  2816. resp.Fail(fmt.Sprintf("第%d行权益销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2817. return
  2818. }
  2819. rowRegister.RaiSellerId = sellerItem.SellerId
  2820. rowRegister.RaiSellerName = sellerItem.SellerName
  2821. continue
  2822. }
  2823. // FICC大套餐
  2824. if k == 10 {
  2825. if v == "是" {
  2826. tempItem := serviceTempNameMap[titleMap[k]]
  2827. if tempItem == nil {
  2828. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2829. return
  2830. }
  2831. cs := &fms.ContractService{
  2832. ProductId: crm.CompanyProductFicc,
  2833. ServiceTemplateId: tempItem.ServiceTemplateId,
  2834. Title: tempItem.Title,
  2835. Value: tempItem.Value,
  2836. TableValue: tempItem.TableValue,
  2837. ChartPermissionId: tempItem.ChartPermissionId,
  2838. }
  2839. cs.Set()
  2840. rowServices = append(rowServices, cs)
  2841. productIds[crm.CompanyProductFicc] = struct{}{}
  2842. }
  2843. continue
  2844. }
  2845. // FICC小套餐
  2846. if k >= 11 && k <= 31 {
  2847. // 小套餐权限
  2848. if v == "是" {
  2849. rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
  2850. productIds[crm.CompanyProductFicc] = struct{}{}
  2851. }
  2852. continue
  2853. }
  2854. // 其他类型套餐
  2855. if k >= 32 && k <= 38 {
  2856. if v == "是" {
  2857. tempItem := serviceTempNameMap[titleMap[k]]
  2858. if tempItem == nil {
  2859. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2860. return
  2861. }
  2862. cs := &fms.ContractService{
  2863. ProductId: crm.CompanyProductFicc,
  2864. ServiceTemplateId: tempItem.ServiceTemplateId,
  2865. Title: tempItem.Title,
  2866. Value: tempItem.Value,
  2867. TableValue: tempItem.TableValue,
  2868. ChartPermissionId: tempItem.ChartPermissionId,
  2869. }
  2870. cs.Set()
  2871. rowServices = append(rowServices, cs)
  2872. productIds[crm.CompanyProductFicc] = struct{}{}
  2873. }
  2874. continue
  2875. }
  2876. if k >= 39 && k <= 49 {
  2877. if v == "是" {
  2878. // 权益大套餐
  2879. if k <= 42 {
  2880. //新增
  2881. parentName := "权益大套餐"
  2882. tempItem := serviceTempNameMap[titleMap[k]]
  2883. if tempItem == nil {
  2884. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2885. return
  2886. }
  2887. cs := &fms.ContractService{
  2888. ProductId: crm.CompanyProductRai,
  2889. ServiceTemplateId: tempItem.ServiceTemplateId,
  2890. Title: tempItem.Title,
  2891. Value: tempItem.Value,
  2892. TableValue: tempItem.TableValue,
  2893. ChartPermissionId: tempItem.ChartPermissionId,
  2894. }
  2895. rowServices = append(rowServices, cs)
  2896. tempItem = serviceTempNameMap[parentName]
  2897. if tempItem == nil {
  2898. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2899. return
  2900. }
  2901. cs = &fms.ContractService{
  2902. ProductId: crm.CompanyProductRai,
  2903. ServiceTemplateId: tempItem.ServiceTemplateId,
  2904. Title: tempItem.Title,
  2905. Value: tempItem.Value,
  2906. TableValue: tempItem.TableValue,
  2907. ChartPermissionId: tempItem.ChartPermissionId,
  2908. }
  2909. rowServices = append(rowServices, cs)
  2910. } else {
  2911. rootName := "行业套餐"
  2912. // 新增三条套餐信息
  2913. parentName, _ := raiIndustryMap[k]
  2914. fmt.Println("raiIndustryMap:", raiIndustryMap)
  2915. fmt.Println("titleMap:", titleMap)
  2916. childName := titleMap[k]
  2917. fullName := childName + "_" + parentName + "_" + rootName
  2918. if fullName != "" {
  2919. //增加三级权限
  2920. tempItem := serviceTempFullNameMap[fullName]
  2921. fmt.Println("fullName:", fullName)
  2922. fmt.Println("serviceTempFullNameMap:", serviceTempFullNameMap)
  2923. if tempItem == nil {
  2924. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2925. return
  2926. }
  2927. cs := &fms.ContractService{
  2928. ProductId: crm.CompanyProductRai,
  2929. ServiceTemplateId: tempItem.ServiceTemplateId,
  2930. Title: tempItem.Title,
  2931. Value: tempItem.Value,
  2932. TableValue: tempItem.TableValue,
  2933. ChartPermissionId: tempItem.ChartPermissionId,
  2934. }
  2935. rowServices = append(rowServices, cs)
  2936. //增加二级权限
  2937. tempItem = serviceTempFullNameMap[parentName+"_"+rootName]
  2938. if tempItem == nil {
  2939. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2940. return
  2941. }
  2942. cs = &fms.ContractService{
  2943. ProductId: crm.CompanyProductRai,
  2944. ServiceTemplateId: tempItem.ServiceTemplateId,
  2945. Title: tempItem.Title,
  2946. Value: tempItem.Value,
  2947. TableValue: tempItem.TableValue,
  2948. ChartPermissionId: tempItem.ChartPermissionId,
  2949. }
  2950. rowServices = append(rowServices, cs)
  2951. //增加一级权限
  2952. tempItem = serviceTempFullNameMap[rootName]
  2953. if tempItem == nil {
  2954. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2955. return
  2956. }
  2957. cs = &fms.ContractService{
  2958. ProductId: crm.CompanyProductRai,
  2959. ServiceTemplateId: tempItem.ServiceTemplateId,
  2960. Title: tempItem.Title,
  2961. Value: tempItem.Value,
  2962. TableValue: tempItem.TableValue,
  2963. ChartPermissionId: tempItem.ChartPermissionId,
  2964. }
  2965. rowServices = append(rowServices, cs)
  2966. }
  2967. }
  2968. productIds[crm.CompanyProductRai] = struct{}{}
  2969. }
  2970. continue
  2971. }
  2972. // 权益研选等套餐
  2973. if k >= 50 && k <= 54 {
  2974. if v == "是" {
  2975. tempItem := serviceTempNameMap[titleMap[k]]
  2976. if tempItem == nil {
  2977. resp.Fail(fmt.Sprintf("第%d行%d列套餐名称不匹配, 请按模板导入", i+1, k+1), c)
  2978. return
  2979. }
  2980. cs := &fms.ContractService{
  2981. ProductId: crm.CompanyProductRai,
  2982. ServiceTemplateId: tempItem.ServiceTemplateId,
  2983. Title: tempItem.Title,
  2984. Value: tempItem.Value,
  2985. TableValue: tempItem.TableValue,
  2986. ChartPermissionId: tempItem.ChartPermissionId,
  2987. }
  2988. cs.Set()
  2989. rowServices = append(rowServices, cs)
  2990. productIds[crm.CompanyProductRai] = struct{}{}
  2991. }
  2992. continue
  2993. }
  2994. // 套餐备注
  2995. if k == 55 {
  2996. rowRegister.ServiceRemark = v
  2997. continue
  2998. }
  2999. // 开始时间/到期时间
  3000. if k == 58 {
  3001. // 转换失败可能是因为格式为Excel日期格式, 读取出来会是一串数字, 将其转换成日期字符串再处理
  3002. va := cell.Value
  3003. if va == "" {
  3004. resp.Fail(fmt.Sprintf("第%d行%d列开始时间不可为空, 请按模板导入", i+1, k+1), c)
  3005. return
  3006. }
  3007. startDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3008. if e != nil {
  3009. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3010. startDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3011. if e != nil {
  3012. resp.Fail(fmt.Sprintf("第%d行开始时间格式转换有误, 请按模板导入", i+1), c)
  3013. return
  3014. }
  3015. }
  3016. // 转换后的日期小于1900-01-01表示当前生成的日期是有问题的
  3017. if startDate.Before(checkDate) {
  3018. resp.Fail(fmt.Sprintf("第%d行开始时间格式有误, 请按模板导入", i+1), c)
  3019. return
  3020. }
  3021. rowRegister.StartDate = startDate
  3022. continue
  3023. }
  3024. if k == 59 {
  3025. va := cell.Value
  3026. if va == "" {
  3027. resp.Fail(fmt.Sprintf("第%d行到期时间不可为空, 请按模板导入", i+1), c)
  3028. return
  3029. }
  3030. endDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3031. if e != nil {
  3032. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3033. endDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3034. if e != nil {
  3035. resp.Fail(fmt.Sprintf("第%d行到期时间格式转换有误, 请按模板导入", i+1), c)
  3036. return
  3037. }
  3038. }
  3039. if endDate.Before(checkDate) {
  3040. resp.Fail(fmt.Sprintf("第%d行到期时间格式有误, 请按模板导入", i+1), c)
  3041. return
  3042. }
  3043. rowRegister.EndDate = endDate
  3044. continue
  3045. }
  3046. // 合同金额
  3047. if k == 60 {
  3048. amountStr := v
  3049. amount, e := strconv.ParseFloat(amountStr, 64)
  3050. if e != nil {
  3051. resp.Fail(fmt.Sprintf("第%d行合同金额有误, 请按模板导入", i+1), c)
  3052. return
  3053. }
  3054. rowRegister.ContractAmount = amount
  3055. continue
  3056. }
  3057. // 金额单位
  3058. if k == 61 {
  3059. rate := rateMap[v]
  3060. if rate <= 0 {
  3061. resp.Fail(fmt.Sprintf("第%d行金额单位有误, 请按模板导入", i+1), c)
  3062. return
  3063. }
  3064. rowRegister.CurrencyUnit = v
  3065. rowRegister.RMBRate = rate
  3066. continue
  3067. }
  3068. // FICC 套餐总金额
  3069. if k == 62 {
  3070. amountStr := v
  3071. amount, _ := strconv.ParseFloat(amountStr, 64)
  3072. if amount > 0 {
  3073. tmp := &fms.ContractServiceAmount{
  3074. ProductId: crm.CompanyProductFicc,
  3075. ServiceAmount: amount,
  3076. CurrencyUnit: rowRegister.CurrencyUnit,
  3077. TimeBase: base.TimeBase{},
  3078. }
  3079. rowServiceAmount = append(rowServiceAmount, tmp)
  3080. }
  3081. continue
  3082. }
  3083. // 权益套餐总金额
  3084. if k == 63 {
  3085. amountStr := v
  3086. amount, _ := strconv.ParseFloat(amountStr, 64)
  3087. if amount > 0 {
  3088. tmp := &fms.ContractServiceAmount{
  3089. ProductId: crm.CompanyProductRai,
  3090. ServiceAmount: amount,
  3091. CurrencyUnit: rowRegister.CurrencyUnit,
  3092. TimeBase: base.TimeBase{},
  3093. }
  3094. rowServiceAmount = append(rowServiceAmount, tmp)
  3095. }
  3096. continue
  3097. }
  3098. // 约定付款日期
  3099. if k == 64 {
  3100. rowRegister.AgreedPayTime = v
  3101. continue
  3102. }
  3103. // 签订日
  3104. if k == 65 {
  3105. va := cell.Value
  3106. if va == "" {
  3107. continue
  3108. }
  3109. signDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3110. if e != nil {
  3111. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3112. signDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3113. if e != nil {
  3114. resp.Fail(fmt.Sprintf("第%d行签订日格式转换有误, 请按模板导入", i+1), c)
  3115. return
  3116. }
  3117. }
  3118. if signDate.Before(checkDate) {
  3119. resp.Fail(fmt.Sprintf("第%d行签订日格式有误, 请按模板导入", i+1), c)
  3120. return
  3121. }
  3122. rowRegister.SignDate = signDate
  3123. continue
  3124. }
  3125. // 合同状态
  3126. if k == 66 {
  3127. rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
  3128. if rowRegister.ContractStatus == 0 {
  3129. resp.Fail(fmt.Sprintf("第%d行合同状态不匹配, 请按模板导入", i+1), c)
  3130. return
  3131. }
  3132. continue
  3133. }
  3134. // 合同编号
  3135. if k == 67 {
  3136. rowContractCode := v
  3137. if rowContractCode == "" {
  3138. resp.Fail(fmt.Sprintf("第%d行合同编号不可为空, 请按模板导入", i+1), c)
  3139. return
  3140. }
  3141. if utils.InArrayByStr(contractCodeArr, rowContractCode) {
  3142. // 此合同已登记, 跳过本行的读取
  3143. isSkip = true
  3144. break
  3145. }
  3146. rowRegister.ContractCode = rowContractCode
  3147. continue
  3148. }
  3149. // 合规备注
  3150. if k == 68 {
  3151. rowRegister.Remark = v
  3152. continue
  3153. }
  3154. // 开票列表
  3155. k2 := 68
  3156. for ir := 0; ir < invoiceMax; ir++ {
  3157. n := ir + 1
  3158. // 开票日
  3159. k2 += 1
  3160. if k == k2 {
  3161. if v != "" {
  3162. va := cell.Value
  3163. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3164. if e != nil {
  3165. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3166. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3167. if e != nil {
  3168. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式转换有误, 请按模板导入", i+1, n), c)
  3169. return
  3170. }
  3171. }
  3172. if invoiceDate.Before(checkDate) {
  3173. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式有误, 请按模板导入", i+1, n), c)
  3174. return
  3175. }
  3176. rowInvoices[ir].InvoiceDate = invoiceDate
  3177. rowInvoices[ir].ContractCode = rowRegister.ContractCode
  3178. rowInvoices[ir].InvoiceType = fms.ContractInvoiceTypeMake
  3179. }
  3180. continue
  3181. }
  3182. // 开票金额
  3183. k2 += 1
  3184. if k == k2 {
  3185. if v != "" {
  3186. amountStr := v
  3187. amount, e := strconv.ParseFloat(amountStr, 64)
  3188. if e != nil {
  3189. resp.Fail(fmt.Sprintf("第%d行开票金额%d有误, 请按模板导入", i+1, n), c)
  3190. return
  3191. }
  3192. if rowRegister.RMBRate <= 0 {
  3193. resp.Fail(fmt.Sprintf("第%d行开票金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  3194. return
  3195. }
  3196. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  3197. rowInvoices[ir].OriginAmount = amount
  3198. rowInvoices[ir].Amount = a
  3199. }
  3200. continue
  3201. }
  3202. // 开票套餐类型
  3203. k2 += 1
  3204. if k == k2 {
  3205. if v != "" {
  3206. if v == "FICC套餐" {
  3207. rowInvoices[ir].ServiceProductId = crm.CompanyProductFicc
  3208. } else if v == "权益套餐" {
  3209. rowInvoices[ir].ServiceProductId = crm.CompanyProductRai
  3210. } else {
  3211. resp.Fail(fmt.Sprintf("第%d行开票套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  3212. return
  3213. }
  3214. }
  3215. continue
  3216. }
  3217. // 开票销售
  3218. k2 += 1
  3219. if k == k2 {
  3220. if v != "" {
  3221. sellerItem := sellerMap[v]
  3222. if sellerItem == nil {
  3223. resp.Fail(fmt.Sprintf("第%d行开票销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  3224. return
  3225. }
  3226. rowInvoices[ir].SellerId = sellerItem.SellerId
  3227. rowInvoices[ir].SellerName = sellerItem.SellerName
  3228. rowInvoices[ir].SellerGroupId = sellerItem.GroupId
  3229. rowInvoices[ir].SellerGroupName = sellerItem.GroupName
  3230. rowInvoices[ir].SellerTeamId = sellerItem.TeamId
  3231. rowInvoices[ir].SellerTeamName = sellerItem.TeamName
  3232. }
  3233. continue
  3234. }
  3235. // 备注
  3236. k2 += 1
  3237. if k == k2 {
  3238. if v != "" {
  3239. rowInvoices[ir].Remark = v
  3240. }
  3241. continue
  3242. }
  3243. }
  3244. // 到款列表
  3245. for ir := 0; ir < invoiceMax; ir++ {
  3246. n := ir + 1
  3247. // 到款日
  3248. k2 += 1
  3249. if k == k2 {
  3250. if v != "" {
  3251. va := cell.Value
  3252. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  3253. if e != nil {
  3254. d := utils.ConvertToFormatDay(va, "2006/01/02")
  3255. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  3256. if e != nil {
  3257. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式转换有误, 请按模板导入", i+1, n), c)
  3258. return
  3259. }
  3260. }
  3261. if invoiceDate.Before(checkDate) {
  3262. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式有误, 请按模板导入", i+1, n), c)
  3263. return
  3264. }
  3265. rowPayments[ir].InvoiceDate = invoiceDate
  3266. rowPayments[ir].ContractCode = rowRegister.ContractCode
  3267. rowPayments[ir].InvoiceType = fms.ContractInvoiceTypePay
  3268. }
  3269. continue
  3270. }
  3271. // 到款金额
  3272. k2 += 1
  3273. if k == k2 {
  3274. if v != "" {
  3275. amountStr := v
  3276. amount, e := strconv.ParseFloat(amountStr, 64)
  3277. if e != nil {
  3278. resp.Fail(fmt.Sprintf("第%d行到款金额%d有误, 请按模板导入", i+1, n), c)
  3279. return
  3280. }
  3281. if rowRegister.RMBRate <= 0 {
  3282. resp.Fail(fmt.Sprintf("第%d行到款金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  3283. return
  3284. }
  3285. // 付款方式
  3286. dayDiff = rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
  3287. contractAmount := rowRegister.ContractAmount
  3288. payType := fmsService.CalculateContractPaymentType(amount, contractAmount, dayDiff)
  3289. rowPayments[ir].PayType = payType
  3290. rowPayments[ir].OriginAmount = amount
  3291. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  3292. rowPayments[ir].Amount = a
  3293. }
  3294. continue
  3295. }
  3296. // 到款套餐类型
  3297. k2 += 1
  3298. if k == k2 {
  3299. if v != "" {
  3300. if v == "FICC套餐" {
  3301. rowPayments[ir].ServiceProductId = crm.CompanyProductFicc
  3302. } else if v == "权益套餐" {
  3303. rowPayments[ir].ServiceProductId = crm.CompanyProductRai
  3304. } else {
  3305. resp.Fail(fmt.Sprintf("第%d行到款套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  3306. return
  3307. }
  3308. }
  3309. continue
  3310. }
  3311. // 到款销售
  3312. k2 += 1
  3313. if k == k2 {
  3314. if v != "" {
  3315. sellerItem := sellerMap[v]
  3316. if sellerItem == nil {
  3317. resp.Fail(fmt.Sprintf("第%d行到款销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  3318. return
  3319. }
  3320. rowPayments[ir].SellerId = sellerItem.SellerId
  3321. rowPayments[ir].SellerName = sellerItem.SellerName
  3322. rowPayments[ir].SellerGroupId = sellerItem.GroupId
  3323. rowPayments[ir].SellerGroupName = sellerItem.GroupName
  3324. rowPayments[ir].SellerTeamId = sellerItem.TeamId
  3325. rowPayments[ir].SellerTeamName = sellerItem.TeamName
  3326. }
  3327. continue
  3328. }
  3329. // 备注
  3330. k2 += 1
  3331. if k == k2 {
  3332. if v != "" {
  3333. rowPayments[ir].Remark = v
  3334. }
  3335. continue
  3336. }
  3337. }
  3338. }
  3339. if isSkip {
  3340. continue
  3341. }
  3342. // 小套餐
  3343. if len(rowChartPermissionIdArr) > 0 {
  3344. // 说明有小套餐
  3345. tempItem := serviceTempNameMap["FICC小套餐"]
  3346. if tempItem == nil {
  3347. resp.Fail(fmt.Sprintf("第%d行小套餐名称不匹配, 请按模板导入", i+1), c)
  3348. return
  3349. }
  3350. rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
  3351. cs := &fms.ContractService{
  3352. ProductId: crm.CompanyProductFicc,
  3353. ServiceTemplateId: tempItem.ServiceTemplateId,
  3354. Title: tempItem.Title,
  3355. Value: tempItem.Value,
  3356. TableValue: tempItem.TableValue,
  3357. ChartPermissionId: tempItem.ChartPermissionId,
  3358. ChartPermissionIds: rowChartPermissionIds,
  3359. }
  3360. cs.Set()
  3361. rowServices = append(rowServices, cs)
  3362. }
  3363. // 如果导入的最后一条合同编号为空并且合同编号之后的字段均为空
  3364. // excel这个包读行的时候不会再往后面没数据的地方读取, 所以此处需要重新判断一次
  3365. if rowRegister.ContractCode == "" {
  3366. resp.Fail(fmt.Sprintf("第%d行合同编号为空", i+1), c)
  3367. return
  3368. }
  3369. rowRegister.RegisterStatus = fms.ContractRegisterStatusIng
  3370. rowInvoiceList := make([]*fms.ContractInvoice, 0)
  3371. // 过滤信息不完整的开票到款
  3372. for l := range rowInvoices {
  3373. if rowInvoices[l].ContractCode != "" {
  3374. if rowInvoices[l].OriginAmount <= 0 || rowInvoices[l].SellerId == 0 {
  3375. resp.Fail(fmt.Sprintf("第%d行开票信息必填项不完整", i+1), c)
  3376. return
  3377. }
  3378. rowInvoiceList = append(rowInvoiceList, rowInvoices[l])
  3379. }
  3380. }
  3381. for l := range rowPayments {
  3382. if rowPayments[l].ContractCode != "" {
  3383. if rowPayments[l].OriginAmount <= 0 {
  3384. resp.Fail(fmt.Sprintf("第%d行到款信息必填项不完整", i+1), c)
  3385. return
  3386. }
  3387. rowInvoiceList = append(rowInvoiceList, rowPayments[l])
  3388. }
  3389. }
  3390. // 新增登记、套餐、开票到款信息
  3391. for proId, _ := range productIds {
  3392. rowRegister.ProductIds += strconv.Itoa(proId) + ","
  3393. }
  3394. rowRegister.ProductIds = strings.Trim(rowRegister.ProductIds, ",")
  3395. newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, rowInvoiceList, rowServiceAmount)
  3396. if e != nil {
  3397. resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
  3398. return
  3399. }
  3400. //处理重复公司名日期等重复的开票到款记录
  3401. sellerItemMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  3402. dupList, e := fms.GetDuplicateContractInvoiceDetailItemList(rowRegister.CompanyName, rowRegister.StartDate.Format(utils.FormatDate), rowRegister.EndDate.Format(utils.FormatDate))
  3403. if e != nil {
  3404. err = fmt.Errorf("获取开票到款列表失败, Err: %s", e.Error())
  3405. return
  3406. }
  3407. templateIds := make([]int, 0)
  3408. for _, detail := range rowServices {
  3409. templateIds = append(templateIds, detail.ServiceTemplateId)
  3410. }
  3411. sort.Ints(templateIds)
  3412. ids := make([]string, 0)
  3413. for _, id := range templateIds {
  3414. ids = append(ids, strconv.Itoa(id))
  3415. }
  3416. templateIdStr := strings.Join(ids, ",")
  3417. nDupList := make([]*fms.DupInvoice, 0)
  3418. for _, dup := range dupList {
  3419. if templateIdStr == dup.TemplateIds {
  3420. nDupList = append(nDupList, dup)
  3421. }
  3422. }
  3423. //先遍历一遍拿到开票销售信息
  3424. for _, ppItem := range dupList {
  3425. j := 0
  3426. if ppItem.ContractRegisterId != newId {
  3427. if ppItem.InvoiceType == 3 {
  3428. sellerItemMap[j] = &crm.SellerAdminWithGroupTeam{
  3429. SellerId: ppItem.SellerId,
  3430. SellerName: ppItem.SellerName,
  3431. GroupId: ppItem.SellerGroupId,
  3432. GroupName: ppItem.SellerGroupName,
  3433. TeamId: ppItem.SellerTeamId,
  3434. TeamName: ppItem.SellerTeamName,
  3435. }
  3436. }
  3437. j++
  3438. }
  3439. }
  3440. for _, ppItem := range dupList {
  3441. j := 0
  3442. if ppItem.ContractRegisterId != newId {
  3443. v := &fms.ContractInvoice{
  3444. ContractRegisterId: newId,
  3445. ContractCode: rowRegister.ContractCode,
  3446. Amount: ppItem.Amount,
  3447. OriginAmount: ppItem.OriginAmount,
  3448. CurrencyUnit: ppItem.CurrencyUnit,
  3449. InvoiceDate: ppItem.InvoiceDate,
  3450. SellerId: ppItem.SellerId,
  3451. SellerName: ppItem.SellerName,
  3452. SellerGroupId: ppItem.SellerGroupId,
  3453. SellerGroupName: ppItem.SellerGroupName,
  3454. SellerTeamId: ppItem.SellerTeamId,
  3455. SellerTeamName: ppItem.SellerTeamName,
  3456. AdminId: int(adminInfo.AdminId),
  3457. AdminName: adminInfo.RealName,
  3458. Remark: ppItem.Remark,
  3459. ServiceProductId: ppItem.ServiceProductId,
  3460. IsPrePay: 1,
  3461. StartDate: ppItem.StartDate,
  3462. EndDate: ppItem.EndDate,
  3463. }
  3464. if ppItem.InvoiceType == 3 {
  3465. v.InvoiceType = 1
  3466. } else if ppItem.InvoiceType == 4 {
  3467. v.InvoiceType = 2
  3468. if sellerItem, ok := sellerItemMap[j]; ok {
  3469. v.SellerId = sellerItem.SellerId
  3470. v.SellerName = sellerItem.SellerName
  3471. v.SellerGroupId = sellerItem.GroupId
  3472. v.SellerGroupName = sellerItem.GroupName
  3473. v.SellerTeamId = sellerItem.TeamId
  3474. v.SellerTeamName = sellerItem.TeamName
  3475. j++
  3476. }
  3477. }
  3478. v.Set()
  3479. // 到款登记-付款方式
  3480. v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, rowRegister.ContractAmount, dayDiff)
  3481. // 新增的记录
  3482. opData := ""
  3483. //opDataByte, e := json.Marshal(req)
  3484. if e != nil {
  3485. return
  3486. }
  3487. //opData = string(opDataByte)
  3488. opType := fms.ContractRegisterOpTypePrePay
  3489. if ppItem.InvoiceType == 3 {
  3490. opType = fms.ContractRegisterOpTypePreInvoice
  3491. }
  3492. newAmount := decimal.NewFromFloat(0).Round(2)
  3493. a := decimal.NewFromFloat(v.Amount).Round(2)
  3494. newAmount = newAmount.Add(a)
  3495. ia, _ := newAmount.Round(2).Float64()
  3496. logList = append(logList, &fms.ContractRegisterLog{
  3497. ContractRegisterId: newId,
  3498. AdminId: int(adminInfo.AdminId),
  3499. AdminName: adminInfo.RealName,
  3500. OpData: opData,
  3501. OpType: opType,
  3502. CreateTime: time.Now().Local(),
  3503. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  3504. })
  3505. if e := v.Create(); e != nil {
  3506. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  3507. return
  3508. }
  3509. //最后删除预到款记录
  3510. e = ppItem.Delete()
  3511. if e != nil {
  3512. resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
  3513. return
  3514. }
  3515. ppOB := new(fms.ContractPreRegister)
  3516. items, e := ppOB.FetchByRegisterId(ppItem.ContractRegisterId)
  3517. if e != nil {
  3518. if e == utils.ErrNoRow {
  3519. resp.Fail("预登记记录不存在或已被删除", c)
  3520. return
  3521. }
  3522. resp.FailMsg("获取预登记失败", "Err:"+e.Error(), c)
  3523. return
  3524. }
  3525. for _, item := range items {
  3526. e = item.Delete()
  3527. if e != nil {
  3528. resp.FailMsg("删除预登记失败", "Err:"+e.Error(), c)
  3529. return
  3530. }
  3531. }
  3532. }
  3533. }
  3534. // 自动分配套餐金额
  3535. go fmsService.CalculatePaymentServiceAmount(newId)
  3536. newIds = append(newIds, newId)
  3537. }
  3538. }
  3539. }
  3540. // 操作日志
  3541. go func() {
  3542. logOB := new(fms.ContractRegisterLog)
  3543. if e := logOB.AddInBatches(logList); e != nil {
  3544. return
  3545. }
  3546. }()
  3547. resp.Ok("操作成功", c)
  3548. }
  3549. // CurrencyList
  3550. // @Title 货币单位列表
  3551. // @Description 货币单位列表
  3552. // @Success 200 {object} fms.CurrencyUnitItem
  3553. // @router /contract/register/currency_list [get]
  3554. func (rg *RegisterController) CurrencyList(c *gin.Context) {
  3555. list, e := fmsService.GetTodayCurrencyRateList()
  3556. if e != nil {
  3557. resp.FailData("获取失败", "获取今日货币汇率列表失败, Err: "+e.Error(), c)
  3558. return
  3559. }
  3560. resp.OkData("获取成功", list, c)
  3561. }
  3562. // CheckContractName
  3563. // @Title 货币单位列表
  3564. // @Description 货币单位列表
  3565. // @Success 200 {object} fms.CheckContractNameResp
  3566. // @router /contract/register/check_contract_code [get]
  3567. func (rg *RegisterController) CheckContractName(c *gin.Context) {
  3568. var req fms.CheckContractNameReq
  3569. if e := c.BindQuery(&req); e != nil {
  3570. err, ok := e.(validator.ValidationErrors)
  3571. if !ok {
  3572. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  3573. return
  3574. }
  3575. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  3576. return
  3577. }
  3578. existCond := ""
  3579. existPars := make([]interface{}, 0)
  3580. if req.CompanyName != "" {
  3581. // 是否存在相同的合同名称的登记
  3582. existCond = ` company_name = ?`
  3583. existPars = append(existPars, req.CompanyName)
  3584. }
  3585. if req.StartDate != "" && req.EndDate != "" {
  3586. // 日期校验
  3587. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  3588. if e != nil {
  3589. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  3590. return
  3591. }
  3592. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  3593. if e != nil {
  3594. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  3595. return
  3596. }
  3597. if existCond != "" {
  3598. existCond += ` AND (start_date =? and end_date=?)`
  3599. } else {
  3600. existCond = ` start_date = ? and end_date=?`
  3601. }
  3602. existPars = append(existPars, startDate, endDate)
  3603. }
  3604. if req.SellerIds != "" {
  3605. admin := new(crm.Admin)
  3606. sellerIds := strings.Split(req.SellerIds, ",")
  3607. if len(sellerIds) > 2 {
  3608. resp.Fail("最多只能选择两个销售", c)
  3609. return
  3610. }
  3611. var pars []interface{}
  3612. cond := ` admin_id in (?) `
  3613. pars = append(pars, sellerIds)
  3614. sellers, e := admin.List(cond, pars)
  3615. if e != nil {
  3616. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  3617. return
  3618. }
  3619. var sellerId, raiSellerId int
  3620. for _, v := range sellers {
  3621. if v.DepartmentId == crm.SellerDepartmentId {
  3622. sellerId = v.AdminId
  3623. } else if v.DepartmentId == crm.RaiSellerDepartmentId {
  3624. raiSellerId = v.AdminId
  3625. }
  3626. }
  3627. existCond += ` AND (seller_id =? and rai_seller_id=?)`
  3628. existPars = append(existPars, sellerId, raiSellerId)
  3629. }
  3630. if existCond == "" {
  3631. resp.Fail("请输入合同名称或者合同有效期", c)
  3632. return
  3633. }
  3634. // 是否存在相同合同名称的登记
  3635. ob := new(fms.ContractRegister)
  3636. data := fms.CheckContractNameResp{
  3637. Exist: 0,
  3638. }
  3639. _, e := ob.FetchByCondition(existCond, existPars)
  3640. if e != nil {
  3641. if e == utils.ErrNoRow {
  3642. resp.OkData("查询成功", data, c)
  3643. return
  3644. }
  3645. resp.FailMsg("查询失败", "查询相同登记号失败, Err: "+e.Error(), c)
  3646. return
  3647. }
  3648. data.Exist = 1
  3649. resp.OkData("查询成功", data, c)
  3650. return
  3651. }
  3652. // CheckContract
  3653. // @Title 货币单位列表
  3654. // @Description 货币单位列表
  3655. // @Success 200 {object} fms.CheckContractNameResp
  3656. // @router /contract/register/check_contract_duplicate [post]
  3657. func (rg *RegisterController) CheckContractDuplicate(c *gin.Context) {
  3658. var req fms.CheckContractDuplicateReq
  3659. if e := c.ShouldBind(&req); e != nil {
  3660. err, ok := e.(validator.ValidationErrors)
  3661. if !ok {
  3662. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  3663. return
  3664. }
  3665. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  3666. return
  3667. }
  3668. existCond := ""
  3669. existPars := make([]interface{}, 0)
  3670. if req.CompanyName != "" {
  3671. // 是否存在相同的合同名称的登记
  3672. existCond = ` company_name = ?`
  3673. existPars = append(existPars, req.CompanyName)
  3674. }
  3675. if req.StartDate != "" && req.EndDate != "" {
  3676. // 日期校验
  3677. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  3678. if e != nil {
  3679. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  3680. return
  3681. }
  3682. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  3683. if e != nil {
  3684. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  3685. return
  3686. }
  3687. if existCond != "" {
  3688. existCond += ` AND (start_date =? and end_date=?)`
  3689. } else {
  3690. existCond = ` start_date = ? and end_date=?`
  3691. }
  3692. existPars = append(existPars, startDate, endDate)
  3693. }
  3694. if existCond == "" {
  3695. resp.Fail("请输入合同名称或者合同有效期", c)
  3696. return
  3697. }
  3698. data := fms.CheckContractDuplicateResp{
  3699. Exist: 0,
  3700. }
  3701. // 是否存在相同合同名称的登记
  3702. list, e := fms.CheckContractDuplicate(existCond, existPars)
  3703. if e != nil {
  3704. resp.FailMsg("操作失败", "查询重复合同失败, Err: "+e.Error(), c)
  3705. return
  3706. }
  3707. registerIds := make([]int, 0)
  3708. for i := range list {
  3709. registerIds = append(registerIds, list[i].ContractRegisterId)
  3710. }
  3711. idlist, e := fms.CheckContractServiceDuplicate(registerIds)
  3712. if e != nil {
  3713. resp.FailMsg("操作失败", "查询重复合同套餐失败, Err: "+e.Error(), c)
  3714. return
  3715. }
  3716. //校验套餐
  3717. if len(req.Services) > 0 {
  3718. serviceAmountMap := make(map[int]float64)
  3719. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  3720. if e != nil {
  3721. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  3722. return
  3723. }
  3724. templateIds := make([]int, 0)
  3725. for _, detail := range serviceList {
  3726. templateIds = append(templateIds, detail.ServiceTemplateId)
  3727. }
  3728. sort.Ints(templateIds)
  3729. ids := make([]string, 0)
  3730. for _, id := range templateIds {
  3731. ids = append(ids, strconv.Itoa(id))
  3732. }
  3733. templateIdStr := strings.Join(ids, ",")
  3734. for _, s := range idlist {
  3735. if templateIdStr == *s {
  3736. data.Exist = 1
  3737. }
  3738. }
  3739. }
  3740. resp.OkData("查询成功", data, c)
  3741. return
  3742. }