register.go 125 KB

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