register.go 128 KB

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