12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131 |
- package controller
- import (
- "bufio"
- "cold-logistics/app/admin/model"
- "cold-logistics/app/admin/service"
- "cold-logistics/app/admin/service/dto"
- "cold-logistics/common/actions"
- "cold-logistics/common/lib"
- "cold-logistics/common/nats/nats_server"
- "cold-logistics/conf"
- "errors"
- "fmt"
- "github.com/beego/beego/v2/core/logs"
- "github.com/boombuler/barcode"
- "github.com/boombuler/barcode/code128"
- "github.com/gin-gonic/gin"
- "github.com/gin-gonic/gin/binding"
- "github.com/golang/freetype/truetype"
- "github.com/jordan-wright/email"
- "github.com/ser163/png2j"
- "github.com/signintech/gopdf"
- "github.com/skip2/go-qrcode"
- "github.com/wcharczuk/go-chart/v2"
- "github.com/wcharczuk/go-chart/v2/drawing"
- "github.com/xuri/excelize/v2"
- "gogs.baozhida.cn/zoie/OAuth-core/api"
- "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth/user"
- _ "gogs.baozhida.cn/zoie/OAuth-core/pkg/response"
- "gonum.org/v1/plot"
- "gonum.org/v1/plot/plotter"
- "gonum.org/v1/plot/vg"
- "gonum.org/v1/plot/vg/draw"
- "image/color"
- "image/jpeg"
- "image/png"
- "log"
- "math"
- "net/smtp"
- "net/url"
- "os"
- "path"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- )
- type WaybillController struct {
- api.Api
- }
- // GetPage 获取运单列表
- // @Summary 获取运单列表
- // @Description 获取运单列表
- // @Tags 运单
- // @Param no query string false "运单号"
- // @Param pageSize query int false "页条数"
- // @Param page query int false "页码"
- // @Success 200 {object} response.Response{data=response.Page{list=[]model.Waybill}} "{"code": 200, "data": [...]}"
- // @Router /api/waybill [get]
- // @Security Bearer
- func (e WaybillController) GetPage(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillGetPageReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- list := make([]model.Waybill, 0)
- var count int64
- err = s.GetPage(&req, &list, &count, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
- }
- // Export 导出运单excel
- // @Summary 导出运单excel
- // @Description 导出运单excel
- // @Tags 运单
- // @Param no query string false "运单号"
- // @Param pageSize query int false "页条数"
- // @Param page query int false "页码"
- // @Success 200 {object} response.Response{data=response.Page{list=[]model.Waybill}} "{"code": 200, "data": [...]}"
- // @Router /api/waybill [get]
- // @Security Bearer
- func (e WaybillController) Export(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillGetPageReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- list := make([]model.Waybill, 0)
- var count int64
- req.PageSize = 9999
- err = s.GetPage(&req, &list, &count, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- f := excelize.NewFile() // 设置单元格的值
- // 这里设置表头ÒÒ
- f.SetCellValue("Sheet1", "A1", "序号")
- f.SetCellValue("Sheet1", "B1", "状态")
- f.SetCellValue("Sheet1", "C1", "寄件人名称")
- f.SetCellValue("Sheet1", "D1", "寄件人电话")
- f.SetCellValue("Sheet1", "E1", "寄件人地址")
- f.SetCellValue("Sheet1", "F1", "收件人名称")
- f.SetCellValue("Sheet1", "G1", "收件人电话")
- f.SetCellValue("Sheet1", "H1", "收件人地址")
- f.SetCellValue("Sheet1", "I1", "温度要求")
- f.SetCellValue("Sheet1", "J1", "配送要求")
- f.SetCellValue("Sheet1", "K1", "货物类型")
- f.SetCellValue("Sheet1", "L1", "运输备注")
- // 设置列宽
- f.SetColWidth("Sheet1", "A", "A", 6)
- f.SetColWidth("Sheet1", "B", "B", 8)
- f.SetColWidth("Sheet1", "C", "C", 14)
- f.SetColWidth("Sheet1", "D", "D", 14)
- f.SetColWidth("Sheet1", "E", "E", 30)
- f.SetColWidth("Sheet1", "F", "F", 14)
- f.SetColWidth("Sheet1", "G", "G", 14)
- f.SetColWidth("Sheet1", "H", "H", 30)
- f.SetColWidth("Sheet1", "I", "K", 15)
- f.SetColWidth("Sheet1", "L", "L", 15)
- line := 1
- // 循环写入数据
- for i, v := range list {
- line++
- f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), i+1)
- f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), model.WaybillStatusMap[v.Status])
- f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.SenderAddressName)
- f.SetCellValue("Sheet1", fmt.Sprintf("D%d", line), v.SenderAddressPhone)
- f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), v.SenderAddressDetails)
- f.SetCellValue("Sheet1", fmt.Sprintf("F%d", line), v.ConsigneeAddressName)
- f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), v.ConsigneeAddressPhone)
- f.SetCellValue("Sheet1", fmt.Sprintf("H%d", line), v.ConsigneeAddressDetails)
- f.SetCellValue("Sheet1", fmt.Sprintf("I%d", line), v.TemperatureInterval)
- f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), v.DeliveryCondition)
- f.SetCellValue("Sheet1", fmt.Sprintf("K%d", line), v.CargoType)
- f.SetCellValue("Sheet1", fmt.Sprintf("L%d", line), v.Remark)
- }
- timeStr := time.Now().Format("20060102150405")
- filePath := "ofile/" + "运单" + timeStr + ".xlsx"
- // 保存文件
- if err = f.SaveAs(filePath); err != nil {
- logs.Error("保存运单失败:", err)
- }
- defer func() {
- os.Remove(filePath)
- }()
- c.Header("Content-Type", "application/vnd.ms-excel;charset=utf8")
- // PathEscape 函数对中文做处理
- c.Header("Content-Disposition", "attachment; filename="+url.PathEscape("运单"+timeStr+".xlsx"))
- c.Header("Content-Transfer-Encoding", "binary")
- c.File(filePath)
- }
- // Home 首页统计
- // @Summary 首页统计
- // @Description 首页统计
- // @Tags 运单
- // @Param no query string false "运单号"
- // @Param pageSize query int false "页条数"
- // @Param page query int false "页码"
- // @Success 200 {object} response.Response{data=response.Page{list=[]model.Waybill}} "{"code": 200, "data": [...]}"
- // @Router /api/waybill [get]
- // @Security Bearer
- func (e WaybillController) Home(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillStatsReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- res := s.GetBasicsStats(&req, p)
- e.OK(res, "查询成功")
- }
- // GetAppletPage 获取运单列表
- // @Summary 获取运单列表
- // @Description 获取运单列表
- // @Tags 运单
- // @Param no query string false "运单号"
- // @Param pageSize query int false "页条数"
- // @Param page query int false "页码"
- // @Success 200 {object} response.Response{data=response.Page{list=[]model.Waybill}} "{"code": 200, "data": [...]}"
- // @Router /api/waybill [get]
- // @Security Bearer
- func (e WaybillController) GetAppletPage(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillGetAppletPageReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- list := make([]model.Waybill, 0)
- var count int64
- err = s.GetAppletPage(&req, &list, &count, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
- }
- // GetAppletCount 获取app运单统计数量
- // @Summary 获取app运单统计数量
- // @Description 获取app运单统计数量
- // @Tags 运单
- // @Param no query string false "运单号"
- // @Success 200 {object} response.Response{data=response.Page{list=[]model.Waybill}} "{"code": 200, "data": [...]}"
- // @Router /api/waybill/applet-count [get]
- // @Security Bearer
- func (e WaybillController) GetAppletCount(c *gin.Context) {
- s := service.Waybill{}
- userSvc := service.SysUser{}
- req := dto.WaybillGetAppletPageReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- MakeService(&userSvc.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- var userObj model.SysUser
- err = userSvc.Get(&dto.SysUserGetReq{Id: p.UserId}, nil, &userObj)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- list := make([]model.Waybill, 0)
- var count int64
- if userObj.UserType == "customer" {
- r := dto.WaybillGetCustomerPageReq{}
- r.PageSize = 9999
- r.CustomerId = p.UserId
- err = s.GetCustomerPage(&r, &list, &count, p)
- var statusCount = make(map[int]int)
- statusCount[0] = int(count)
- for _, waybill := range list {
- if _, ok := statusCount[waybill.Status]; ok {
- statusCount[waybill.Status] += 1
- } else {
- statusCount[waybill.Status] = 1
- }
- }
- e.OK(statusCount, "查询成功")
- return
- }
- err = s.GetAppletCount(&list, &count, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- var statusCount = make(map[int]int)
- statusCount[0] = int(count)
- for _, waybill := range list {
- if _, ok := statusCount[waybill.Status]; ok {
- statusCount[waybill.Status] += 1
- } else {
- statusCount[waybill.Status] = 1
- }
- }
- e.OK(statusCount, "查询成功")
- }
- // Get 通过id获取运单
- // @Summary 通过id获取运单
- // @Description 通过id获取运单
- // @Tags 运单
- // @Param id path string true "运单id"
- // @Success 200 {object} response.Response{data=model.Waybill} "{"code": 200, "data": [...]}"
- // @Router /api/waybill/{id} [get]
- // @Security Bearer
- func (e WaybillController) Get(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillGetReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, nil).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- var object model.Waybill
- p := actions.GetPermissionFromContext(c)
- //数据权限检查
- err = s.Get(&req, &object, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(object, "查询成功")
- }
- // Insert 添加运单
- // @Summary 添加运单
- // @Description 添加运单
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInsertReq true "data"
- // @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
- // @Router /api/waybill [post]
- // @Security Bearer
- func (e WaybillController) Insert(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillInsertReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- p := actions.GetPermissionFromContext(c)
- // 设置创建人
- req.SetCreateBy(user.GetUserId(c))
- req.SetDeptId(p.DeptId)
- err = s.Insert(&req)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.GetId(), "创建成功")
- }
- // AppletInsert 添加运单app
- // @Summary 添加运单app
- // @Description 添加运单app
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInsertReq true "data"
- // @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
- // @Router /api/waybill [post]
- // @Security Bearer
- func (e WaybillController) AppletInsert(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillInsertReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- p := actions.GetPermissionFromContext(c)
- err = s.AppletInsert(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.GetId(), "添加成功")
- }
- // Update 修改运单
- // @Summary 修改运单
- // @Description 修改运单
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillUpdateReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
- // @Router /api/waybill [put]
- // @Security Bearer
- func (e WaybillController) Update(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillUpdateReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- p := actions.GetPermissionFromContext(c)
- req.SetUpdateBy(user.GetUserId(c))
- err = s.Update(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.GetId(), "更新成功")
- }
- // Delivery 派单
- // @Summary 派单
- // @Description 派单
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillDeliveryReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
- // @Router /api/waybill [put]
- // @Security Bearer
- func (e WaybillController) Delivery(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillDeliveryReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- p := actions.GetPermissionFromContext(c)
- req.SetUpdateBy(user.GetUserId(c))
- err = s.Delivery(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.GetId(), "派单成功")
- }
- // Delete 删除运单
- // @Summary 删除运单
- // @Description 删除运单
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillDeleteReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
- // @Router /api/waybill [delete]
- // @Security Bearer
- func (e WaybillController) Delete(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillDeleteReq{}
- userSvc := service.SysUser{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON, nil).
- MakeService(&s.Service).
- MakeService(&userSvc.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- err = s.Remove(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.GetId(), "删除成功")
- }
- // WarehouseIn 入库
- // @Summary 入库
- // @Description 入库
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInOutReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
- // @Router /api/waybill/warehouse-in [post]
- // @Security Bearer
- func (e WaybillController) WarehouseIn(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillInOutReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON, nil).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- err = s.WarehouseIn(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.WaybillNoList, "入库成功")
- }
- // WarehouseOut 出库
- // @Summary 出库
- // @Description 出库
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInOutReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
- // @Router /api/waybill/warehouse-out [post]
- // @Security Bearer
- func (e WaybillController) WarehouseOut(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillInOutReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON, nil).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- err = s.WarehouseOut(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.WaybillNoList, "出库成功")
- }
- // CarIn 上车
- // @Summary 上车
- // @Description 上车
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInOutReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
- // @Router /api/waybill/car-in [post]
- // @Security Bearer
- func (e WaybillController) CarIn(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillInOutReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON, nil).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- err = s.CarIn(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.WaybillNoList, "装车成功")
- }
- // CarOut 下车
- // @Summary 下车
- // @Description 下车
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInOutReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
- // @Router /api/waybill/car-out [post]
- // @Security Bearer
- func (e WaybillController) CarOut(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillInOutReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON, nil).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- err = s.CarOut(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.WaybillNoList, "下车成功")
- }
- // CoolerBoxIn 装箱
- // @Summary 装箱
- // @Description 装箱
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInOutReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
- // @Router /api/waybill/cooler-box-in [post]
- // @Security Bearer
- func (e WaybillController) CoolerBoxIn(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillCoolerBoxInReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON, nil).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- err = s.CoolerBoxIn(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.WaybillNoList, "装箱成功")
- }
- // Receipt 签收
- // @Summary 签收
- // @Description 签收
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInOutReq true "body"
- // @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
- // @Router /api/waybill/car-out [post]
- // @Security Bearer
- func (e WaybillController) Receipt(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillReceiptReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON, nil).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- err = s.Receipt(&req, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.WaybillNo, "签收成功")
- }
- // GetCustomerPage 获取客户运单列表
- // @Summary 获取客户运单列表
- // @Description 获取客户运单列表
- // @Tags 运单
- // @Param no query string false "运单号"
- // @Param pageSize query int false "页条数"
- // @Param page query int false "页码"
- // @Success 200 {object} response.Response{data=response.Page{list=[]model.Waybill}} "{"code": 200, "data": [...]}"
- // @Router /api/waybill/customer [get]
- // @Security Bearer
- func (e WaybillController) GetCustomerPage(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillGetCustomerPageReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- list := make([]model.Waybill, 0)
- var count int64
- req.CustomerId = p.UserId
- err = s.GetCustomerPage(&req, &list, &count, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
- }
- func (e WaybillController) CustomerExport(c *gin.Context) {
- s := service.Waybill{}
- req := dto.WaybillGetCustomerPageReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //数据权限检查
- p := actions.GetPermissionFromContext(c)
- list := make([]model.Waybill, 0)
- var count int64
- req.CustomerId = p.UserId
- req.PageSize = 9999
- err = s.GetCustomerPage(&req, &list, &count, p)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- f := excelize.NewFile() // 设置单元格的值
- // 这里设置表头ÒÒ
- f.SetCellValue("Sheet1", "A1", "序号")
- f.SetCellValue("Sheet1", "B1", "状态")
- f.SetCellValue("Sheet1", "C1", "寄件人名称")
- f.SetCellValue("Sheet1", "D1", "寄件人电话")
- f.SetCellValue("Sheet1", "E1", "寄件人地址")
- f.SetCellValue("Sheet1", "F1", "收件人名称")
- f.SetCellValue("Sheet1", "G1", "收件人电话")
- f.SetCellValue("Sheet1", "H1", "收件人地址")
- f.SetCellValue("Sheet1", "I1", "温度要求")
- f.SetCellValue("Sheet1", "J1", "配送要求")
- f.SetCellValue("Sheet1", "K1", "货物类型")
- f.SetCellValue("Sheet1", "L1", "运输备注")
- // 设置列宽
- f.SetColWidth("Sheet1", "A", "A", 6)
- f.SetColWidth("Sheet1", "B", "B", 8)
- f.SetColWidth("Sheet1", "C", "C", 14)
- f.SetColWidth("Sheet1", "D", "D", 14)
- f.SetColWidth("Sheet1", "E", "E", 30)
- f.SetColWidth("Sheet1", "F", "F", 14)
- f.SetColWidth("Sheet1", "G", "G", 14)
- f.SetColWidth("Sheet1", "H", "H", 30)
- f.SetColWidth("Sheet1", "I", "K", 15)
- f.SetColWidth("Sheet1", "L", "L", 15)
- line := 1
- // 循环写入数据
- for i, v := range list {
- line++
- f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), i+1)
- f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), model.GetCustomerWaybillStatus(v.Status))
- f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.SenderAddressName)
- f.SetCellValue("Sheet1", fmt.Sprintf("D%d", line), v.SenderAddressPhone)
- f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), v.SenderAddressDetails)
- f.SetCellValue("Sheet1", fmt.Sprintf("F%d", line), v.ConsigneeAddressName)
- f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), v.ConsigneeAddressPhone)
- f.SetCellValue("Sheet1", fmt.Sprintf("H%d", line), v.ConsigneeAddressDetails)
- f.SetCellValue("Sheet1", fmt.Sprintf("I%d", line), v.TemperatureInterval)
- f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), v.DeliveryCondition)
- f.SetCellValue("Sheet1", fmt.Sprintf("K%d", line), v.CargoType)
- f.SetCellValue("Sheet1", fmt.Sprintf("L%d", line), v.Remark)
- }
- timeStr := time.Now().Format("20060102150405")
- filePath := "ofile/" + "运单" + timeStr + ".xlsx"
- defer func() {
- os.Remove(filePath)
- }()
- // 保存文件
- if err = f.SaveAs(filePath); err != nil {
- logs.Error("保存运单失败:", err)
- }
- c.Header("Content-Type", "application/vnd.ms-excel;charset=utf8")
- // PathEscape 函数对中文做处理
- c.Header("Content-Disposition", "attachment; filename="+url.PathEscape("运单"+timeStr+".xlsx"))
- c.Header("Content-Transfer-Encoding", "binary")
- c.File(filePath)
- }
- // CustomerInsert 客户添加运单
- // @Summary 客户添加运单
- // @Description 客户添加运单
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInsertReq true "data"
- // @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
- // @Router /api/waybill/customer [post]
- // @Security Bearer
- func (e WaybillController) CustomerInsert(c *gin.Context) {
- s := service.Waybill{}
- userSvc := service.SysUser{}
- req := dto.WaybillInsertReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON).
- MakeService(&s.Service).
- MakeService(&userSvc.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- p := actions.GetPermissionFromContext(c)
- var userObj model.SysUser
- err = userSvc.Get(&dto.SysUserGetReq{Id: p.UserId}, nil, &userObj)
- if err != nil {
- e.Error(500, err, "获取用户信息失败")
- return
- }
- if p.DeptId == 0 && req.DeptId == 0 {
- e.Error(500, err, "请先选择运输公司")
- return
- }
- // 设置创建人
- req.SetCreateBy(user.GetUserId(c))
- req.CustomerId = p.UserId
- req.CustomerName = userObj.NickName
- if p.DeptId > 0 {
- req.SetDeptId(p.DeptId)
- }
- err = s.Insert(&req)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- e.OK(req.GetId(), "创建成功")
- }
- // Import 导入运单
- // @Summary 导入运单
- // @Description 导入运单
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInsertReq true "data"
- // @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
- // @Router /api/waybill/import [post]
- // @Security Bearer
- func (e WaybillController) Import(c *gin.Context) {
- s := service.Waybill{}
- userSvc := service.SysUser{}
- req := dto.WaybillImportReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Form).
- MakeService(&s.Service).
- MakeService(&userSvc.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- //读取第一fileName的文件
- fileHeader, err := c.FormFile("file")
- if err != nil {
- err = errors.New("文件格式错误" + err.Error())
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- if fileHeader.Size > 1024*1024*2 {
- err = errors.New("文件大小超过2M")
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- file, err := fileHeader.Open()
- if err != nil {
- err = errors.New("文件格式错误" + err.Error())
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- defer file.Close()
- xlsx, err := excelize.OpenReader(bufio.NewReader(file))
- if err != nil {
- err = errors.New("文件格式错误" + err.Error())
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- p := actions.GetPermissionFromContext(c)
- if p.DeptId == 0 {
- e.Error(500, err, "获取用户信息失败")
- return
- }
- var userObj model.SysUser
- err = userSvc.Get(&dto.SysUserGetReq{Id: p.UserId}, nil, &userObj)
- if err != nil {
- e.Error(500, err, "获取用户信息失败")
- return
- }
- var customerId int
- //customerName := req.CustomerName
- if userObj.UserType == model.UserTypeCustomer {
- customerId = userObj.Id
- //customerName = userObj.NickName
- }
- rows, _ := xlsx.GetRows("Sheet1")
- for indexRow, row := range rows {
- if indexRow == 0 {
- continue
- }
- if len(row) < 12 {
- for i := 0; i < 12-len(row); i++ {
- row = append(row, "")
- }
- }
- for i, colCell := range row {
- fmt.Println(i, ":", colCell)
- }
- quantity, _ := strconv.Atoi(row[10])
- obj := dto.WaybillInsertReq{
- Status: 1,
- SenderAddressName: row[0],
- SenderAddressPhone: row[1],
- SenderAddressDetails: row[2],
- CustomerName: row[3],
- ConsigneeAddressName: row[4],
- ConsigneeAddressPhone: row[5],
- ConsigneeAddressDetails: row[6],
- TemperatureInterval: row[7],
- DeliveryCondition: row[8],
- CargoType: row[9],
- Quantity: quantity,
- Remark: row[11],
- CustomerId: customerId,
- }
- obj.SetDeptId(p.DeptId)
- obj.SetCreateBy(user.GetUserId(c))
- err = s.Insert(&obj)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- }
- e.OK(len(rows)-1, "导入成功")
- }
- // ExportTemplate 导出运单模板
- // @Summary 导出运单模板
- // @Description 导出运单模板
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInsertReq true "data"
- // @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
- // @Router /api/waybill/export-template [post]
- // @Security Bearer
- func (e WaybillController) ExportTemplate(c *gin.Context) {
- s := service.Waybill{}
- err := e.MakeContext(c).
- MakeOrm().
- MakeService(&s.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- filePath := "./ofile/运单导入模板.xlsx"
- //打开文件
- fileTmp, errByOpenFile := os.Open(filePath)
- defer fileTmp.Close()
- //获取文件的名称
- fileName := path.Base(filePath)
- if errByOpenFile != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- c.Header("Content-Type", "application/vnd.ms-excel;charset=utf8")
- // PathEscape 函数对中文做处理
- c.Header("Content-Disposition", "attachment; filename="+url.PathEscape(fileName))
- c.Header("Content-Transfer-Encoding", "binary")
- c.File(filePath)
- }
- // TemperaturePDF 导出温度记录
- // @Summary 导出温度记录
- // @Description 导出温度记录
- // @Tags 运单
- // @Accept application/json
- // @Product application/json
- // @Param data body dto.WaybillInsertReq true "data"
- // @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
- // @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
- // @Router /api/waybill/temperature-pdf [post]
- // @Security Bearer
- func (e WaybillController) TemperaturePDF1(c *gin.Context) {
- s := service.Waybill{}
- companySvc := service.Company{}
- req := dto.WaybillGetByWaybillPdfReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- MakeService(&companySvc.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- var waybill model.Waybill
- var company model.SysDept
- //err = s.GetByWaybillNo(&req, &waybill, p)
- err = s.GetByWaybillNo(&req, &waybill, nil)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- err = companySvc.Get(&dto.CompanyGetReq{Id: waybill.DeptId}, &company)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- DeviceSensor_data, waybillPDF, err := s.GetAllData(&dto.WaybillGetByWaybillNoReq{WaybillNo: req.WaybillNo})
- // 最高温度、最低温度、最高湿度、最低湿度
- var maxTemp, minTemp, maxHumidity, minHumidity float32
- // 最高温度时间、最低温度时间、最高湿度时间、最低湿度时间
- var maxTempTime, minTempTime, maxHumidityTime, minHumidityTime string
- // 总温度 总湿度
- var totalTemp, totalHumidity float32
- // 平均温度 平均湿度
- var avgTemp, avgHumidity float32
- // 温度阈值,湿度阈值
- var tempThreshold, humidityThreshold string
- // 记录开始时间,记录结束时间
- var s_time, e_time string
- var lastTime string
- var isFirst, isSecond = true, false
- var first_column, second_column []nats_server.DeviceData_R
- if len(DeviceSensor_data) > 0 {
- tempThreshold = fmt.Sprintf("%.1f-%.1f", DeviceSensor_data[0].T_tl, DeviceSensor_data[0].T_tu)
- humidityThreshold = fmt.Sprintf("%.1f-%.1f", DeviceSensor_data[0].T_rhl, DeviceSensor_data[0].T_rhu)
- s_time = DeviceSensor_data[0].T_time
- e_time = DeviceSensor_data[len(DeviceSensor_data)-1].T_time
- // 最高温度及时刻
- maxTemp = DeviceSensor_data[0].T_t
- maxTempTime = DeviceSensor_data[0].T_time
- // 最低温度及时刻
- minTemp = DeviceSensor_data[0].T_t
- minTempTime = DeviceSensor_data[0].T_time
- // 最高湿度及时刻
- maxHumidity = DeviceSensor_data[0].T_rh
- maxHumidityTime = DeviceSensor_data[0].T_time
- // 获取最低湿度及时刻
- minHumidity = DeviceSensor_data[0].T_rh
- minHumidityTime = DeviceSensor_data[0].T_time
- for i := 0; i < len(DeviceSensor_data); i++ {
- data := DeviceSensor_data[i]
- if data.T_t > maxTemp {
- maxTemp = data.T_t
- maxTempTime = data.T_time
- }
- if data.T_t < minTemp {
- minTemp = data.T_t
- minTempTime = data.T_time
- }
- totalTemp += data.T_t
- if data.T_rh > maxHumidity {
- maxHumidity = data.T_rh
- maxHumidityTime = data.T_time
- }
- if data.T_rh < minHumidity {
- minHumidity = data.T_rh
- minHumidityTime = data.T_time
- }
- totalHumidity += data.T_rh
- }
- var sn string
- for _, w := range waybillPDF {
- for _, data := range w.Data {
- if len(lastTime) > 0 {
- if lastTime != data.T_time && isFirst == true {
- isFirst = false
- isSecond = true
- } else if lastTime != data.T_time && isSecond == true {
- isFirst = true
- isSecond = false
- }
- }
- if len(sn) > 0 && sn != data.T_sn && len(first_column)%2 == 1 {
- isFirst, isSecond = isSecond, isFirst
- }
- if isFirst {
- first_column = append(first_column, data)
- lastTime = data.T_time
- sn = data.T_sn
- }
- if isSecond {
- second_column = append(second_column, data)
- lastTime = data.T_time
- sn = data.T_sn
- }
- }
- }
- // 平均温度
- avgTemp = totalTemp / float32(len(DeviceSensor_data))
- // 平均湿度
- avgHumidity = totalHumidity / float32(len(DeviceSensor_data))
- }
- // -------------------获取最高温湿度、温蒂温湿度、平均温湿度结束
- pdf := &gopdf.GoPdf{}
- pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
- err = pdf.AddTTFFont("wts", "static/fonts/MiSans-Medium.ttf")
- if err != nil {
- return
- }
- err = pdf.SetFont("wts", "", 20)
- if err != nil {
- return
- }
- pdf.SetGrayFill(0.5)
- pdf.SetMargins(0, 20, 0, 20)
- pdf.AddPage()
- if len(company.Logo) > 0 {
- imgH, errImg := lib.GetImage(company.Logo)
- if errImg != nil {
- err = errors.New("获取图片失败")
- e.Error(500, err, err.Error())
- return
- }
- imgWidth := float64(imgH.Bounds().Dx())
- imgHeight := float64(imgH.Bounds().Dy())
- W := 50.
- H := (imgHeight * W) / imgWidth
- if strings.Contains(company.Logo, ".png") {
- err = pdf.ImageFrom(imgH, 10, 5, &gopdf.Rect{W: W, H: H})
- if err != nil {
- err = errors.New("写入图片失败")
- e.Error(500, err, err.Error())
- return
- }
- } else {
- fileName := "./ofile/" + path.Base(company.Logo)
- f, _ := os.Create(fileName)
- defer f.Close()
- defer func() {
- os.Remove(fileName)
- }()
- jpeg.Encode(f, imgH, &jpeg.Options{100})
- err = pdf.Image(fileName, (595-W)/2, (840-H)/2, &gopdf.Rect{W: W, H: H})
- if err != nil {
- err = errors.New("写入图片失败")
- e.Error(500, err, err.Error())
- return
- }
- }
- }
- title := "运单" + req.WaybillNo + "温度记录"
- if req.HumidityShow {
- title = "运单" + req.WaybillNo + "温湿度记录"
- }
- var y float64 = 70
- textw, _ := pdf.MeasureTextWidth(title)
- pdf.SetX((595 / 2) - (textw / 2))
- pdf.SetY(y)
- pdf.Text(title)
- y += 30
- pdf.SetFont("wts", "", 16)
- pdf.SetXY(10, y)
- pdf.Text("记录概要信息")
- // 线
- y += 10
- pdf.SetLineWidth(0.5)
- pdf.SetStrokeColor(169, 169, 169)
- pdf.Line(10, y, 585, y)
- y += 20
- pdf.SetFont("wts", "", 10)
- pdf.SetXY(10, y)
- pdf.Text(fmt.Sprintf("记录开始时间:%s", s_time))
- pdf.SetXY(240, y)
- pdf.Text(fmt.Sprintf("记录结束时间:%s", e_time))
- sTime, _ := lib.TimeStrToTime(s_time)
- eTime, _ := lib.TimeStrToTime(e_time)
- pdf.SetXY(470, y)
- minutes := int(eTime.Sub(sTime).Minutes())
- hours := minutes / 60
- remainingMinutes := minutes % 60
- pdf.Text(fmt.Sprintf("记录总时间:%dh%dmin", hours, remainingMinutes))
- // -------------最高温/湿度 最低温/湿度 平均温/湿度
- y += 15
- pdf.SetXY(10, y)
- pdf.Text(fmt.Sprintf("最高温度:%.1f℃,%s", lib.RoundToDecimal(float64(maxTemp), 1), maxTempTime))
- pdf.SetXY(240, y)
- pdf.Text(fmt.Sprintf("最低温度:%.1f℃,%s", lib.RoundToDecimal(float64(minTemp), 1), minTempTime))
- pdf.SetXY(470, y)
- pdf.Text(fmt.Sprintf("平均温度:%.1f℃", lib.RoundToDecimal(float64(avgTemp), 1)))
- if req.HumidityShow {
- y += 15
- pdf.SetXY(10, y)
- pdf.Text(fmt.Sprintf("最高湿度:%.1f%%RH,%s", lib.RoundToDecimal(float64(maxHumidity), 1), maxHumidityTime))
- pdf.SetXY(240, y)
- pdf.Text(fmt.Sprintf("最低湿度:%.1f%%RH,%s", lib.RoundToDecimal(float64(minHumidity), 1), minHumidityTime))
- pdf.SetXY(470, y)
- pdf.Text(fmt.Sprintf("平均湿度:%.1f%%RH", lib.RoundToDecimal(float64(avgHumidity), 1)))
- }
- // -------------温/湿度阈值
- y += 15
- pdf.SetXY(10, y)
- pdf.Text(fmt.Sprintf("温度阈值:%s℃", tempThreshold))
- if req.HumidityShow {
- pdf.SetXY(240, y)
- pdf.Text(fmt.Sprintf("湿度阈值:%s%%", humidityThreshold))
- }
- //-------------发货单位,收货单位,备注
- y += 15
- pdf.SetXY(10, y)
- T_forwarding_unit_temp := []rune(waybill.SenderAddressName)
- if len(T_forwarding_unit_temp) > 17 {
- pdf.Text(fmt.Sprintf("发货人:%s", string(T_forwarding_unit_temp[0:17])))
- pdf.SetXY(60, y+15)
- pdf.Text(fmt.Sprintf("%s", string(T_forwarding_unit_temp[17:])))
- } else {
- pdf.Text(fmt.Sprintf("发货人:%s", string(T_forwarding_unit_temp)))
- }
- pdf.SetXY(240, y)
- T_consignee_unit_temp := []rune(waybill.ConsigneeAddressName)
- if len(T_consignee_unit_temp) > 17 {
- pdf.Text(fmt.Sprintf("收货人:%s", string(T_consignee_unit_temp[0:17])))
- pdf.SetXY(290, y+15)
- pdf.Text(fmt.Sprintf("%s", string(T_consignee_unit_temp[17:])))
- } else {
- pdf.Text(fmt.Sprintf("收货人:%s", string(T_consignee_unit_temp)))
- }
- // 承运方
- y += 15
- pdf.SetXY(10, y)
- company_name := []rune(waybill.Dept.Name)
- pdf.Text(fmt.Sprintf("承运方:%s", string(company_name)))
- y += 15
- pdf.SetXY(10, y)
- T_remark_temp := []rune(waybill.Remark)
- if len(waybill.Remark) > 35 {
- pdf.Text(fmt.Sprintf("备注:%s", string(T_remark_temp[0:35])))
- pdf.SetXY(10, y+15)
- pdf.Text(fmt.Sprintf("%s", string(T_remark_temp[35:])))
- } else {
- pdf.Text(fmt.Sprintf("备注: %s", string(T_remark_temp)))
- }
- y += 15
- //pdf.SetFont("wts", "", 16)
- //pdf.SetXY(10, y)
- //pdf.Text("记录曲线信息")
- //// 线
- //y += 10
- //pdf.SetLineWidth(0.5)
- //pdf.SetStrokeColor(169, 169, 169)
- //pdf.Line(10, y, 585, y)
- //y += 1
- //
- //var tempFilepath string
- //tempFilepath, err = DeviceDataTemperatureJPG2(s_time, e_time, waybillPDF)
- //if err == nil {
- // imgH, _ := gopdf.ImageHolderByPath(tempFilepath)
- // pdf.ImageByHolder(imgH, 10, y, &gopdf.Rect{W: 575, H: 315})
- // y += 315
- //}
- //
- //var humidityFilepath string
- //if req.HumidityShow {
- // humidityFilepath, err = DeviceDataHumidityJPG2(s_time, e_time, waybillPDF)
- // if err == nil {
- // imgH, _ := gopdf.ImageHolderByPath(humidityFilepath)
- // pdf.ImageByHolder(imgH, 10, y, &gopdf.Rect{W: 575, H: 315})
- // y += 315
- // }
- //}
- if y > 841.89 {
- // 图片结束直接分页
- pdf.AddPage()
- y = 20
- }
- y += 20
- pdf.SetFont("wts", "", 16)
- pdf.SetXY(10, y)
- pdf.Text("记录数据信息")
- // 线
- y += 10
- pdf.SetLineWidth(0.5)
- pdf.SetStrokeColor(169, 169, 169)
- pdf.Line(10, y, 585, y)
- y += 10
- pdf.SetFont("wts", "", 10)
- var x float64 = 10
- var w float64 = 112
- lib.RectFillColor(pdf, "时间", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 101
- lib.RectFillColor(pdf, "名称", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- if req.HumidityShow {
- x = x + w
- w = 37
- lib.RectFillColor(pdf, "温度℃", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, "湿度%", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- } else {
- x = x + w
- w = 37 * 2
- lib.RectFillColor(pdf, "温度℃", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- }
- x = x + w
- w = 112
- lib.RectFillColor(pdf, "时间", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 101
- lib.RectFillColor(pdf, "名称", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- if req.HumidityShow {
- x = x + w
- w = 37
- lib.RectFillColor(pdf, "温度℃", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, "湿度%", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- } else {
- x = x + w
- w = 37 * 2
- lib.RectFillColor(pdf, "温度℃", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- }
- y += 20
- var textH float64 = 25 // if text height is 25px.
- for i, v := range first_column {
- pdf.SetNewY(y, textH)
- y = pdf.GetY()
- x, w = 10, 112
- lib.RectFillColor(pdf, v.T_time, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 101
- lib.RectFillColor(pdf, v.T_name, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- // 显示温湿度
- if req.HumidityShow {
- x = x + w
- w = 37
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", v.T_t), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", v.T_rh), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- } else {
- x = x + w
- w = 37 * 2
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", v.T_t), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- }
- if i < len(second_column) {
- x = x + w
- w = 112
- lib.RectFillColor(pdf, second_column[i].T_time, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 101
- lib.RectFillColor(pdf, second_column[i].T_name, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- if req.HumidityShow {
- x = x + w
- w = 37
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", second_column[i].T_t), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", second_column[i].T_rh), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- } else {
- x = x + w
- w = 37 * 2
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", second_column[i].T_t), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- }
- }
- y += 20
- }
- if len(second_column) > len(first_column) {
- for i := len(first_column); i < len(second_column); i++ {
- pdf.SetNewY(y, textH)
- y = pdf.GetY()
- x, w = 297, 112
- lib.RectFillColor(pdf, second_column[i].T_time, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 101
- lib.RectFillColor(pdf, second_column[i].T_name, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- if req.HumidityShow {
- x = x + w
- w = 37
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", second_column[i].T_t), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", second_column[i].T_rh), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- } else {
- x = x + w
- w = 37 * 2
- lib.RectFillColor(pdf, fmt.Sprintf(" %.1f ", second_column[i].T_t), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- }
- y += 20
- }
- }
- filename := "运单" + req.WaybillNo + "温湿度记录" + time.Now().Format("20060102150405") + ".pdf"
- filePath := "ofile/" + filename
- err = pdf.WritePdf(filePath)
- if err != nil {
- return
- }
- defer func() {
- //os.Remove(tempFilepath)
- //os.Remove(humidityFilepath)
- os.Remove(filePath)
- }()
- c.Header("Content-Disposition", "attachment; filename="+url.PathEscape(filename))
- c.Header("Content-Transfer-Encoding", "binary")
- c.File(filePath)
- }
- func (e WaybillController) TemperaturePDF(c *gin.Context) {
- s := service.Waybill{}
- companySvc := service.Company{}
- req := dto.WaybillGetByWaybillPdfReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- MakeService(&companySvc.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- var waybill model.Waybill
- err = s.GetByWaybillNo(&req, &waybill, nil)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- var company model.SysDept
- err = companySvc.Get(&dto.CompanyGetReq{Id: waybill.DeptId}, &company)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- filename, filePath, err := PDF(s, waybill, company, req.HumidityShow)
- defer func() {
- os.Remove(filePath)
- }()
- c.Header("Content-Disposition", "attachment; filename="+url.PathEscape(filename))
- c.Header("Content-Transfer-Encoding", "binary")
- c.File(filePath)
- }
- func PDF(s service.Waybill, waybill model.Waybill, company model.SysDept, humidityShow bool) (filename, filePath string, err error) {
- DeviceSensor_data, Pdf_data, waybillPDF, err := s.GetTwoDeviceSensorData(&dto.WaybillGetByWaybillNoReq{WaybillNo: waybill.WaybillNo})
- // 最高温度、最低温度、最高湿度、最低湿度
- var maxTemp, minTemp, maxHumidity, minHumidity float32
- // 最高温度时间、最低温度时间、最高湿度时间、最低湿度时间
- var maxTempTime, minTempTime, maxHumidityTime, minHumidityTime string
- // 总温度 总湿度
- var totalTemp, totalHumidity float32
- // 平均温度 平均湿度
- var avgTemp, avgHumidity float32
- // 温度阈值,湿度阈值
- var tempThreshold, humidityThreshold string
- // 记录开始时间,记录结束时间
- var s_time, e_time string
- if len(DeviceSensor_data) > 0 {
- tempThreshold = fmt.Sprintf("%.1f-%.1f", DeviceSensor_data[0].T_tl, DeviceSensor_data[0].T_tu)
- humidityThreshold = fmt.Sprintf("%.1f-%.1f", DeviceSensor_data[0].T_rhl, DeviceSensor_data[0].T_rhu)
- s_time = DeviceSensor_data[0].T_time
- e_time = DeviceSensor_data[len(DeviceSensor_data)-1].T_time
- // 最高温度及时刻
- maxTemp = DeviceSensor_data[0].T_t
- maxTempTime = DeviceSensor_data[0].T_time
- // 最低温度及时刻
- minTemp = DeviceSensor_data[0].T_t
- minTempTime = DeviceSensor_data[0].T_time
- // 最高湿度及时刻
- maxHumidity = DeviceSensor_data[0].T_rh
- maxHumidityTime = DeviceSensor_data[0].T_time
- // 获取最低湿度及时刻
- minHumidity = DeviceSensor_data[0].T_rh
- minHumidityTime = DeviceSensor_data[0].T_time
- for i := 0; i < len(DeviceSensor_data); i++ {
- data := DeviceSensor_data[i]
- if data.T_t > maxTemp {
- maxTemp = data.T_t
- maxTempTime = data.T_time
- }
- if data.T_t < minTemp {
- minTemp = data.T_t
- minTempTime = data.T_time
- }
- totalTemp += data.T_t
- if data.T_rh > maxHumidity {
- maxHumidity = data.T_rh
- maxHumidityTime = data.T_time
- }
- if data.T_rh < minHumidity {
- minHumidity = data.T_rh
- minHumidityTime = data.T_time
- }
- totalHumidity += data.T_rh
- }
- // 平均温度
- avgTemp = totalTemp / float32(len(DeviceSensor_data))
- // 平均湿度
- avgHumidity = totalHumidity / float32(len(DeviceSensor_data))
- }
- // -------------------获取最高温湿度、温蒂温湿度、平均温湿度结束
- pdf := &gopdf.GoPdf{}
- pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
- err = pdf.AddTTFFont("wts", "static/fonts/MiSans-Medium.ttf")
- if err != nil {
- return
- }
- err = pdf.SetFont("wts", "", 20)
- if err != nil {
- return
- }
- pdf.SetGrayFill(0.5)
- pdf.SetMargins(0, 20, 0, 20)
- pdf.AddPage()
- if len(company.Logo) > 0 {
- imgH, errImg := lib.GetImage(company.Logo)
- if errImg != nil {
- err = errors.New("获取图片失败")
- return
- }
- imgWidth := float64(imgH.Bounds().Dx())
- imgHeight := float64(imgH.Bounds().Dy())
- H := 60.
- W := (imgWidth * H) / imgHeight
- if strings.Contains(company.Logo, ".png") {
- err = pdf.ImageFrom(imgH, 10, 0, &gopdf.Rect{W: W, H: H})
- if err != nil {
- err = errors.New("写入图片失败")
- return
- }
- } else {
- fileName := "./ofile/" + time.Now().Format("20060102150405") + ".png"
- f, _ := os.Create(fileName)
- defer f.Close()
- defer func() {
- os.Remove(fileName)
- }()
- png.Encode(f, imgH)
- err = pdf.Image(fileName, 10, 0, &gopdf.Rect{W: W, H: H})
- if err != nil {
- if err.Error() == "16-bit depth not supported" {
- fileName2 := "./ofile/" + time.Now().Format("20060102150405") + ".png"
- f2, _ := os.Create(fileName2)
- defer f.Close()
- defer func() {
- os.Remove(fileName2)
- }()
- jpeg.Encode(f2, imgH, &jpeg.Options{100})
- err = pdf.Image(fileName2, 10, 0, &gopdf.Rect{W: W, H: H})
- }
- if err != nil {
- err = errors.New("写入图片失败")
- return
- }
- }
- }
- }
- title := "运单" + waybill.WaybillNo + "温度记录"
- if humidityShow {
- title = "运单" + waybill.WaybillNo + "温湿度记录"
- }
- var y float64 = 70
- textw, _ := pdf.MeasureTextWidth(title)
- pdf.SetX((595 / 2) - (textw / 2))
- pdf.SetY(y)
- pdf.Text(title)
- y += 30
- pdf.SetFont("wts", "", 16)
- pdf.SetXY(10, y)
- pdf.Text("记录概要信息")
- // 线
- y += 10
- pdf.SetLineWidth(0.5)
- pdf.SetStrokeColor(169, 169, 169)
- pdf.Line(10, y, 585, y)
- y += 20
- pdf.SetFont("wts", "", 10)
- pdf.SetXY(10, y)
- pdf.Text(fmt.Sprintf("记录开始时间:%s", s_time))
- pdf.SetXY(240, y)
- pdf.Text(fmt.Sprintf("记录结束时间:%s", e_time))
- sTime, _ := lib.TimeStrToTime(s_time)
- eTime, _ := lib.TimeStrToTime(e_time)
- pdf.SetXY(470, y)
- minutes := int(eTime.Sub(sTime).Minutes())
- hours := minutes / 60
- remainingMinutes := minutes % 60
- pdf.Text(fmt.Sprintf("记录总时间:%dh%dmin", hours, remainingMinutes))
- // -------------最高温/湿度 最低温/湿度 平均温/湿度
- y += 15
- pdf.SetXY(10, y)
- pdf.Text(fmt.Sprintf("最高温度:%.1f℃,%s", lib.RoundToDecimal(float64(maxTemp), 1), maxTempTime))
- pdf.SetXY(240, y)
- pdf.Text(fmt.Sprintf("最低温度:%.1f℃,%s", lib.RoundToDecimal(float64(minTemp), 1), minTempTime))
- pdf.SetXY(470, y)
- pdf.Text(fmt.Sprintf("平均温度:%.1f℃", lib.RoundToDecimal(float64(avgTemp), 1)))
- if humidityShow {
- y += 15
- pdf.SetXY(10, y)
- pdf.Text(fmt.Sprintf("最高湿度:%.1f%%RH,%s", lib.RoundToDecimal(float64(maxHumidity), 1), maxHumidityTime))
- pdf.SetXY(240, y)
- pdf.Text(fmt.Sprintf("最低湿度:%.1f%%RH,%s", lib.RoundToDecimal(float64(minHumidity), 1), minHumidityTime))
- pdf.SetXY(470, y)
- pdf.Text(fmt.Sprintf("平均湿度:%.1f%%RH", lib.RoundToDecimal(float64(avgHumidity), 1)))
- }
- // -------------温/湿度阈值
- y += 15
- pdf.SetXY(10, y)
- pdf.Text(fmt.Sprintf("温度阈值:%s℃", tempThreshold))
- if humidityShow {
- pdf.SetXY(240, y)
- pdf.Text(fmt.Sprintf("温度阈值:%s%%", humidityThreshold))
- }
- //-------------发货单位,收货单位,备注
- y += 15
- pdf.SetXY(10, y)
- T_forwarding_unit_temp := []rune(waybill.SenderAddressName)
- if len(T_forwarding_unit_temp) > 17 {
- pdf.Text(fmt.Sprintf("发货人:%s", string(T_forwarding_unit_temp[0:17])))
- pdf.SetXY(60, y+15)
- pdf.Text(fmt.Sprintf("%s", string(T_forwarding_unit_temp[17:])))
- } else {
- pdf.Text(fmt.Sprintf("发货人:%s", string(T_forwarding_unit_temp)))
- }
- pdf.SetXY(240, y)
- T_consignee_unit_temp := []rune(waybill.ConsigneeAddressName)
- if len(T_consignee_unit_temp) > 17 {
- pdf.Text(fmt.Sprintf("收货人:%s", string(T_consignee_unit_temp[0:17])))
- pdf.SetXY(290, y+15)
- pdf.Text(fmt.Sprintf("%s", string(T_consignee_unit_temp[17:])))
- } else {
- pdf.Text(fmt.Sprintf("收货人:%s", string(T_consignee_unit_temp)))
- }
- // 承运方
- y += 15
- pdf.SetXY(10, y)
- company_name := []rune(waybill.Dept.Name)
- pdf.Text(fmt.Sprintf("承运方:%s", string(company_name)))
- y += 15
- pdf.SetXY(10, y)
- T_remark_temp := []rune(waybill.Remark)
- if len(waybill.Remark) > 35 {
- pdf.Text(fmt.Sprintf("备注:%s", string(T_remark_temp[0:35])))
- pdf.SetXY(10, y+15)
- pdf.Text(fmt.Sprintf("%s", string(T_remark_temp[35:])))
- } else {
- pdf.Text(fmt.Sprintf("备注: %s", string(T_remark_temp)))
- }
- y += 35
- pdf.SetFont("wts", "", 16)
- pdf.SetXY(10, y)
- pdf.Text("记录曲线信息")
- // 线
- y += 10
- pdf.SetLineWidth(0.5)
- pdf.SetStrokeColor(169, 169, 169)
- pdf.Line(10, y, 585, y)
- y += 1
- var tempFilepath string
- tempFilepath, err = DeviceDataTemperatureJPG3(s_time, e_time, waybillPDF)
- if err == nil {
- imgH, _ := gopdf.ImageHolderByPath(tempFilepath)
- pdf.ImageByHolder(imgH, 10, y, &gopdf.Rect{W: 575, H: 315})
- y += 315
- }
- //var humidityFilepath string
- //if req.HumidityShow {
- // humidityFilepath, err = DeviceDataHumidityJPG2(s_time, e_time, waybillPDF)
- // if err == nil {
- // imgH, _ := gopdf.ImageHolderByPath(humidityFilepath)
- // pdf.ImageByHolder(imgH, 10, y, &gopdf.Rect{W: 575, H: 315})
- // y += 315
- // }
- //}
- if y > 841.89 {
- // 图片结束直接分页
- pdf.AddPage()
- y = 20
- }
- y += 20
- pdf.SetFont("wts", "", 16)
- pdf.SetXY(10, y)
- pdf.Text("记录数据信息")
- // 线
- y += 10
- pdf.SetLineWidth(0.5)
- pdf.SetStrokeColor(169, 169, 169)
- pdf.Line(10, y, 585, y)
- y += 10
- pdf.SetFont("wts", "", 10)
- var x float64 = 19
- var w float64 = 112
- lib.RectFillColor(pdf, "时间", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, "T1", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- lib.RectFillColor(pdf, "T2", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 112
- lib.RectFillColor(pdf, "时间", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, "T1", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- lib.RectFillColor(pdf, "T2", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 112
- lib.RectFillColor(pdf, "时间", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, "T1", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- lib.RectFillColor(pdf, "T2", 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- for i, v := range Pdf_data {
- if i%3 == 0 {
- y += 20
- var textH float64 = 25 // if text height is 25px.
- pdf.SetNewY(y, textH)
- y = pdf.GetY()
- x, w = 19, 112
- lib.RectFillColor(pdf, v.T_time, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, lib.Float32_to_string(&v.T_id1), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- lib.RectFillColor(pdf, lib.Float32_to_string(&v.T_id2), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- }
- if i%3 == 1 {
- x = x + w
- w = 112
- lib.RectFillColor(pdf, v.T_time, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, lib.Float32_to_string(&v.T_id1), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- lib.RectFillColor(pdf, lib.Float32_to_string(&v.T_id2), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- }
- if i%3 == 2 {
- x = x + w
- w = 112
- lib.RectFillColor(pdf, v.T_time, 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- w = 37
- lib.RectFillColor(pdf, lib.Float32_to_string(&v.T_id1), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- x = x + w
- lib.RectFillColor(pdf, lib.Float32_to_string(&v.T_id2), 12, x, y, w, 20, 255, 255, 255, lib.AlignCenter, lib.ValignMiddle)
- }
- }
- filename = "运单" + waybill.WaybillNo + "温度记录" + time.Now().Format("20060102150405") + ".pdf"
- filePath = "ofile/" + filename
- err = pdf.WritePdf(filePath)
- if err != nil {
- return
- }
- defer func() {
- os.Remove(tempFilepath)
- }()
- return filename, filePath, nil
- }
- // WaybillPDF 导出运单pdf
- // @Summary 导出运单pdf
- // @Description 导出运单pdf
- // @Tags 运单
- // @Param no query string false "运单号"
- // @Param pageSize query int false "页条数"
- // @Param page query int false "页码"
- // @Success 200 {object} response.Response{data=response.Page{list=[]model.Waybill}} "{"code": 200, "data": [...]}"
- // @Router /api/waybill [get]
- // @Security Bearer
- func (e WaybillController) WaybillPDF(c *gin.Context) {
- s := service.Waybill{}
- companySvc := service.Company{}
- req := dto.WaybillGetByWaybillPdfReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.Query).
- MakeService(&s.Service).
- MakeService(&companySvc.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- var waybill model.Waybill
- var company model.SysDept
- //err = s.GetByWaybillNo(&req, &waybill, p)
- err = s.GetByWaybillNo(&req, &waybill, nil)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- err = companySvc.Get(&dto.CompanyGetReq{Id: waybill.DeptId}, &company)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- // -------------------生成运单条码
- // 运单条码
- cs, _ := code128.Encode(waybill.WaybillNo)
- // 创建一个要输出数据的文件
- imgPath := "ofile/img/" + waybill.WaybillNo + ".png"
- file, _ := os.Create(imgPath)
- defer file.Close()
- // 设置图片像素大小
- barCode, _ := barcode.Scale(cs, 205, 50)
- // 将code128的条形码编码为png图片
- png.Encode(file, barCode)
- imgPath2 := "ofile/img/" + waybill.WaybillNo + ".jpg"
- png2j.Con2jpg(imgPath, imgPath2)
- qrcode, err := qrcode.Encode(fmt.Sprintf("%s/WaybillInquiry?waybillNo=%s", conf.ExtConfig.Service.Domain, waybill.WaybillNo),
- qrcode.Medium, 70)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- qrCodeImgH, err := gopdf.ImageHolderByBytes(qrcode)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- pdf := &gopdf.GoPdf{}
- pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 283.46, H: 283.46}}) //595.28, 841.89 = A4
- //pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: 595.28, H: 841.89}}) //595.28, 841.89 = A4
- err = pdf.AddTTFFont("wts", "static/fonts/MiSans-Medium.ttf")
- if err != nil {
- return
- }
- pdf.SetGrayFill(0.5)
- pdf.SetMargins(0, 10, 0, 10)
- for i := 0; i < waybill.Quantity; i++ {
- pdf.AddPage()
- var y float64 = 20
- pdf.SetFont("wts", "", 10)
- //y += 12
- pdf.SetXY(250, 20)
- pdf.SetFont("wts", "", 13)
- if waybill.Quantity > 1 {
- pdf.Text(fmt.Sprintf("%d/%d", i+1, waybill.Quantity))
- }
- pdf.SetFont("wts", "", 10)
- y += 10
- pdf.Image(imgPath2, 20, y, &gopdf.Rect{W: 240, H: 30})
- y += 43
- textw, _ := pdf.MeasureTextWidth(waybill.WaybillNo)
- pdf.SetX((283.46 / 2) - (textw / 2))
- pdf.SetY(y)
- pdf.Text(waybill.WaybillNo)
- if len(company.Logo) > 0 {
- imgH, errImg := lib.GetImage(company.Logo)
- if errImg != nil {
- err = errors.New("获取图片失败")
- e.Error(500, err, err.Error())
- return
- }
- imgWidth := float64(imgH.Bounds().Dx())
- imgHeight := float64(imgH.Bounds().Dy())
- H := 30.
- W := (imgWidth * H) / imgHeight
- if strings.Contains(company.Logo, ".png") {
- err = pdf.ImageFrom(imgH, 10, 0, &gopdf.Rect{W: W, H: H})
- if err != nil {
- err = errors.New("写入图片失败")
- e.Error(500, err, err.Error())
- return
- }
- } else {
- fileName := "./ofile/" + time.Now().Format("20060102150405") + ".png"
- f, _ := os.Create(fileName)
- defer f.Close()
- defer func() {
- os.Remove(fileName)
- }()
- png.Encode(f, imgH)
- err = pdf.Image(fileName, 10, 0, &gopdf.Rect{W: W, H: H})
- if err != nil {
- if err.Error() == "16-bit depth not supported" {
- fileName2 := "./ofile/" + time.Now().Format("20060102150405") + ".png"
- f2, _ := os.Create(fileName2)
- defer f.Close()
- defer func() {
- os.Remove(fileName2)
- }()
- jpeg.Encode(f2, imgH, &jpeg.Options{100})
- err = pdf.Image(fileName2, 10, 0, &gopdf.Rect{W: W, H: H})
- }
- if err != nil {
- err = errors.New("写入图片失败")
- e.Error(500, err, err.Error())
- return
- }
- }
- }
- } else {
- title := "#" + company.Name
- pdf.SetXY(10, 20)
- pdf.Text(title)
- }
- // 线
- y += 6
- pdf.SetLineWidth(0.5)
- pdf.SetLineType("dotted")
- pdf.Line(10, y, 273, y)
- y += 28
- pdf.SetFont("wts", "", 18)
- pdf.SetXY(12, y+3)
- pdf.Text("收")
- pdf.SetFont("wts", "", 10)
- y -= 5
- pdf.SetXY(40, y)
- pdf.Text(fmt.Sprintf("%s %s", lib.MaskStr(waybill.ConsigneeAddressName), lib.MaskPhoneNumber(waybill.ConsigneeAddressPhone)))
- y += 15
- pdf.SetXY(40, y)
- pdf.Text(waybill.ConsigneeAddressDetails)
- // 线
- y += 8
- pdf.SetLineWidth(0.5)
- pdf.SetLineType("dotted")
- pdf.Line(10, y, 273, y)
- y += 22
- pdf.SetFont("wts", "", 13)
- pdf.SetXY(14, y+3)
- pdf.Text("寄")
- pdf.SetFont("wts", "", 10)
- y -= 5
- pdf.SetXY(40, y)
- pdf.Text(fmt.Sprintf("%s %s", lib.MaskStr(waybill.SenderAddressName), lib.MaskPhoneNumber(waybill.SenderAddressPhone)))
- y += 15
- pdf.SetXY(40, y)
- pdf.Text(waybill.SenderAddressDetails)
- // 线
- y += 10
- pdf.SetLineWidth(0.5)
- //pdf.SetLineType("dashed")
- pdf.SetLineType("dotted")
- pdf.Line(10, y, 273, y)
- y += 12
- pdf.SetXY(10, y)
- pdf.SetFont("wts", "", 8)
- pdf.Text("下单时间:" + waybill.OrderTime.String())
- // 线
- y += 6
- pdf.SetLineWidth(0.5)
- pdf.SetLineType("dotted")
- pdf.Line(10, y, 273, y)
- pdf.SetFont("wts", "", 10)
- y += 20
- pdf.SetXY(10, y)
- pdf.Text("备注:")
- pdf.SetFont("wts", "", 8)
- y += 15
- pdf.SetXY(30, y)
- pdf.Text("货物类型:" + waybill.CargoType)
- y += 15
- pdf.SetXY(30, y)
- pdf.Text("温度要求:" + waybill.TemperatureInterval)
- y += 15
- pdf.SetXY(30, y)
- pdf.Text("配送要求:" + waybill.DeliveryCondition)
- x := 170.
- //pdf.Image(qrcodeImgPath2, x, y-55, &gopdf.Rect{W: 70, H: 70})
- pdf.ImageByHolder(qrCodeImgH, x, y-63, &gopdf.Rect{W: 70, H: 70})
- pdf.SetFont("wts", "", 8)
- y += 10
- textw, _ = pdf.MeasureTextWidth("扫码查询")
- pdf.SetX(x + 35 - (textw / 2))
- pdf.SetY(y)
- pdf.Text("扫码查询")
- y += 10
- textw, _ = pdf.MeasureTextWidth("物流温湿度信息")
- pdf.SetX(x + 35 - (textw / 2))
- pdf.SetY(y)
- pdf.Text("物流温湿度信息")
- }
- filename := "运单" + req.WaybillNo + ".pdf"
- filePath := "ofile/" + filename
- err = pdf.WritePdf(filePath)
- if err != nil {
- return
- }
- defer func() {
- os.Remove(filePath)
- os.Remove(imgPath)
- os.Remove(imgPath2)
- }()
- c.Header("Content-Disposition", "attachment; filename="+url.PathEscape(filename))
- c.Header("Content-Transfer-Encoding", "binary")
- c.File(filePath)
- }
- // SendMail 发送邮件
- // @Summary 通过id获取运单
- // @Description 通过id获取运单
- // @Tags 运单
- // @Param id path string true "运单id"
- // @Success 200 {object} response.Response{data=model.Waybill} "{"code": 200, "data": [...]}"
- // @Router /api/waybill/{id} [get]
- // @Security Bearer
- func (e WaybillController) SendMail(c *gin.Context) {
- s := service.Waybill{}
- companySvc := service.Company{}
- req := dto.WaybillSendMailPdfReq{}
- err := e.MakeContext(c).
- MakeOrm().
- Bind(&req, binding.JSON, nil).
- MakeService(&s.Service).
- MakeService(&companySvc.Service).
- Errors
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- var waybill model.Waybill
- err = s.GetByWaybillNo(&dto.WaybillGetByWaybillPdfReq{WaybillNo: req.WaybillNo, HumidityShow: req.HumidityShow}, &waybill, nil)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- var company model.SysDept
- err = companySvc.Get(&dto.CompanyGetReq{Id: waybill.DeptId}, &company)
- if err != nil {
- e.Error(500, err, err.Error())
- return
- }
- _, filePath, err := PDF(s, waybill, company, req.HumidityShow)
- defer func() {
- os.Remove(filePath)
- }()
- em := email.NewEmail()
- em.From = "冷链物流运输 <bzdcold@163.com>"
- em.To = req.To
- em.Subject = fmt.Sprintf("【冷链物流运输】运单%s温湿度记录", waybill.WaybillNo)
- em.Text = []byte(fmt.Sprintf("运单%s温湿度记录", waybill.WaybillNo))
- // 主要就是在这个位置添加了附件,注意:这里AttachFile是Email结构体的方法而不是字段,所以不是用等于而是括号
- em.AttachFile(filePath)
- err = em.Send("smtp.163.com:25", smtp.PlainAuth("", "bzdcold@163.com", "ZIZXBCDKVTMPJMVX", "smtp.163.com"))
- if err != nil {
- e.Logger.Error(err)
- e.Error(500, err, err.Error())
- return
- }
- e.OK(nil, "发送成功")
- }
- // 获取温度图片
- func DeviceDataTemperatureJPG(startTime, endTime string, waybillPDF []service.WaybillPDF) (string, error) {
- if len(waybillPDF) == 0 {
- return "", errors.New("暂无数据可生成图片")
- }
- // 创建一个新的绘图
- p := plot.New()
- // 设置绘图标题和标签
- p.Title.Text = "temperature"
- //p.Legend.ThumbnailWidth = 20
- deviceSensorList := []nats_server.DeviceSensor_R{}
- dataList := []nats_server.DeviceData_R{}
- for _, w := range waybillPDF {
- deviceSensorList = append(deviceSensorList, w.DeviceSensorList...)
- dataList = append(dataList, w.Data...)
- }
- TemperatureMin := deviceSensorList[0].T_DeviceSensorParameter.T_Tlower
- TemperatureMax := deviceSensorList[0].T_DeviceSensorParameter.T_Tupper
- var ymin, ymax float32
- for i, r := range dataList {
- if i == 0 {
- ymin = r.T_t
- ymax = r.T_t
- }
- if ymin > r.T_t {
- ymin = r.T_t
- }
- if ymax < r.T_t {
- ymax = r.T_t
- }
- }
- var chData = make(chan int, 10)
- var jobGroup sync.WaitGroup
- // 创建温度线
- for i := 0; i < len(deviceSensorList); i++ {
- chData <- 1
- jobGroup.Add(1)
- go func(index int) {
- defer func() {
- <-chData // 完成时chan取出1个
- jobGroup.Done() // 完成时将等待组值减1
- }()
- sn, id := deviceSensorList[index].T_sn, deviceSensorList[index].T_id
- r_maps := []nats_server.DeviceData_R{}
- for _, data := range dataList {
- if data.T_sn == sn && data.T_id == id {
- r_maps = append(r_maps, data)
- }
- }
- fmt.Println(r_maps)
- if len(r_maps) == 0 {
- return
- }
- sort.Slice(r_maps, func(i, j int) bool {
- return r_maps[i].T_time < r_maps[j].T_time
- })
- pts := make(plotter.XYs, len(r_maps))
- for j, d := range r_maps {
- t, _ := lib.TimeStrToTime(d.T_time)
- pts[j].X = float64(t.Unix())
- pts[j].Y = float64(d.T_t)
- }
- line, err := plotter.NewLine(pts)
- if err != nil {
- return
- }
- line.Color = randomColor(index)
- p.Add(line)
- }(i)
- }
- jobGroup.Wait()
- st, _ := lib.TimeStrToTime(startTime)
- et, _ := lib.TimeStrToTime(endTime)
- xmin, xmax := float64(st.Unix()), float64(et.Unix())
- // 添加最高,最低标准线 用红色虚线标识
- p.Add(horizontalLine(xmin, xmax, float64(TemperatureMin)))
- p.Add(horizontalLine(xmin, xmax, float64(TemperatureMax)))
- if ymax < TemperatureMax {
- ymax = TemperatureMax
- }
- if ymin > 0 {
- ymin = 0
- }
- p.Y.Min, p.Y.Max = float64(ymin), float64(ymax)
- p.X.Min, p.X.Max = xmin, xmax
- p.Y.Tick.Marker = commaTicks{}
- p.X.Tick.Marker = timeTicks{}
- p.X.Tick.Label.Rotation = math.Pi / 5
- p.X.Tick.Label.YAlign = draw.YCenter
- p.X.Tick.Label.XAlign = draw.XRight
- filepath := "ofile/" + "temperature" + deviceSensorList[0].T_sn + ".jpg"
- // 保存文件
- if err := p.Save(10*vg.Inch, 4*vg.Inch, filepath); err != nil {
- logs.Error(lib.FuncName(), "生成图片失败", err)
- return "", err
- }
- return filepath, nil
- }
- func DeviceDataTemperatureJPG2(startTime, endTime string, waybillPDF []service.WaybillPDF) (string, error) {
- if len(waybillPDF) == 0 {
- return "", errors.New("暂无数据可生成图片")
- }
- deviceSensorList := []nats_server.DeviceSensor_R{}
- dataList := []nats_server.DeviceData_R{}
- for _, w := range waybillPDF {
- deviceSensorList = append(deviceSensorList, w.DeviceSensorList...)
- dataList = append(dataList, w.Data...)
- }
- TemperatureMin := deviceSensorList[0].T_DeviceSensorParameter.T_Tlower
- TemperatureMax := deviceSensorList[0].T_DeviceSensorParameter.T_Tupper
- var ymin, ymax float32
- for i, r := range dataList {
- if i == 0 {
- ymin = r.T_t
- ymax = r.T_t
- }
- if ymin > r.T_t {
- ymin = r.T_t
- }
- if ymax < r.T_t {
- ymax = r.T_t
- }
- }
- series := make([]chart.Series, 0)
- var chData = make(chan int, 10)
- var jobGroup sync.WaitGroup
- // 创建温度线
- for i := 0; i < len(deviceSensorList); i++ {
- chData <- 1
- jobGroup.Add(1)
- go func(index int) {
- defer func() {
- <-chData // 完成时chan取出1个
- jobGroup.Done() // 完成时将等待组值减1
- }()
- sn, id := deviceSensorList[index].T_sn, deviceSensorList[index].T_id
- r_maps := []nats_server.DeviceData_R{}
- for _, data := range dataList {
- if data.T_sn == sn && data.T_id == id {
- r_maps = append(r_maps, data)
- }
- }
- fmt.Println(r_maps)
- if len(r_maps) == 0 {
- return
- }
- sort.Slice(r_maps, func(i, j int) bool {
- return r_maps[i].T_time < r_maps[j].T_time
- })
- xValues := make([]time.Time, len(r_maps))
- yValues := make([]float64, len(r_maps))
- for j := 0; j < len(r_maps); j++ {
- t, _ := lib.TimeStrToTime(r_maps[j].T_time)
- xValues[j] = t
- yValues[j] = float64(r_maps[j].T_t)
- }
- series = append(series, chart.TimeSeries{
- Name: fmt.Sprintf("%s-%d", sn, id),
- XValues: xValues,
- YValues: yValues,
- })
- }(i)
- }
- jobGroup.Wait()
- if ymax < TemperatureMax {
- ymax = TemperatureMax
- }
- if ymin > 0 {
- ymin = 0
- }
- if ymin > TemperatureMin {
- ymin = TemperatureMin
- }
- st, _ := lib.TimeStrToTime(startTime)
- et, _ := lib.TimeStrToTime(endTime)
- series = append(series, chart.TimeSeries{
- Style: chart.Style{
- StrokeColor: drawing.ColorRed,
- StrokeDashArray: []float64{5.0, 5.0},
- },
- XValues: []time.Time{st, et},
- YValues: []float64{float64(TemperatureMin), float64(TemperatureMin)},
- })
- series = append(series, chart.TimeSeries{
- Style: chart.Style{
- StrokeColor: drawing.ColorRed,
- StrokeDashArray: []float64{5.0, 5.0},
- },
- XValues: []time.Time{st, et},
- YValues: []float64{float64(TemperatureMax), float64(TemperatureMax)},
- })
- font := getZWFont()
- graph := chart.Chart{
- Title: "温度记录",
- TitleStyle: chart.Style{
- FontSize: 15,
- },
- Background: chart.Style{
- Padding: chart.Box{
- Top: 20,
- },
- },
- Font: font,
- XAxis: chart.XAxis{
- Name: "时间",
- ValueFormatter: chart.TimeValueFormatterWithFormat("2006-01-02 15:04"),
- },
- YAxis: chart.YAxis{
- Name: "温度",
- Range: &chart.ContinuousRange{
- Min: float64(ymin),
- Max: float64(ymax + 2),
- },
- },
- Series: series,
- }
- //graph.Elements = []chart.Renderable{
- // chart.Legend(&graph),
- //}
- filepath := "ofile/" + "temperature" + deviceSensorList[0].T_sn + ".jpg"
- f, _ := os.Create(filepath)
- defer f.Close()
- graph.Render(chart.PNG, f)
- return filepath, nil
- }
- func DeviceDataTemperatureJPG3(startTime, endTime string, waybillPDF []service.WaybillPDF) (string, error) {
- if len(waybillPDF) == 0 {
- return "", errors.New("暂无数据可生成图片")
- }
- deviceSensorList := []nats_server.DeviceSensor_R{}
- dataList := []nats_server.DeviceData_R{}
- deviceDataPdfList := []service.DeviceDataPdf{}
- for _, w := range waybillPDF {
- deviceSensorList = append(deviceSensorList, w.DeviceSensorList...)
- dataList = append(dataList, w.Data...)
- deviceDataPdfList = append(deviceDataPdfList, w.DeviceDataPdf...)
- }
- TemperatureMin := deviceSensorList[0].T_DeviceSensorParameter.T_Tlower
- TemperatureMax := deviceSensorList[0].T_DeviceSensorParameter.T_Tupper
- var ymin, ymax float32
- for i, r := range dataList {
- if i == 0 {
- ymin = r.T_t
- ymax = r.T_t
- }
- if ymin > r.T_t {
- ymin = r.T_t
- }
- if ymax < r.T_t {
- ymax = r.T_t
- }
- }
- sort.Slice(deviceDataPdfList, func(i, j int) bool {
- return deviceDataPdfList[i].T_time < deviceDataPdfList[j].T_time
- })
- series := make([]chart.Series, 0)
- // 创建温度线
- xValues := make([]time.Time, len(deviceDataPdfList))
- yValues1 := make([]float64, len(deviceDataPdfList))
- yValues2 := make([]float64, len(deviceDataPdfList))
- for i := 0; i < len(deviceDataPdfList); i++ {
- t, _ := lib.TimeStrToTime(deviceDataPdfList[i].T_time)
- xValues[i] = t
- yValues1[i] = float64(deviceDataPdfList[i].T_id1)
- yValues2[i] = float64(deviceDataPdfList[i].T_id2)
- }
- series = append(series, chart.TimeSeries{
- Name: "T1",
- XValues: xValues,
- YValues: yValues1,
- })
- series = append(series, chart.TimeSeries{
- Name: "T2",
- XValues: xValues,
- YValues: yValues2,
- })
- if ymax < TemperatureMax {
- ymax = TemperatureMax
- }
- if ymin > 0 {
- ymin = 0
- }
- if ymin > TemperatureMin {
- ymin = TemperatureMin
- }
- st, _ := lib.TimeStrToTime(startTime)
- et, _ := lib.TimeStrToTime(endTime)
- series = append(series, chart.TimeSeries{
- Style: chart.Style{
- StrokeColor: drawing.ColorRed,
- StrokeDashArray: []float64{5.0, 5.0},
- },
- XValues: []time.Time{st, et},
- YValues: []float64{float64(TemperatureMin), float64(TemperatureMin)},
- })
- series = append(series, chart.TimeSeries{
- Style: chart.Style{
- StrokeColor: drawing.ColorRed,
- StrokeDashArray: []float64{5.0, 5.0},
- },
- XValues: []time.Time{st, et},
- YValues: []float64{float64(TemperatureMax), float64(TemperatureMax)},
- })
- font := getZWFont()
- graph := chart.Chart{
- Title: "温度记录",
- TitleStyle: chart.Style{
- FontSize: 14,
- },
- Background: chart.Style{
- Padding: chart.Box{
- Top: 20,
- },
- },
- Font: font,
- XAxis: chart.XAxis{
- Name: "时间",
- ValueFormatter: chart.TimeValueFormatterWithFormat("2006-01-02 15:04"),
- },
- YAxis: chart.YAxis{
- Name: "温度",
- Range: &chart.ContinuousRange{
- Min: float64(ymin),
- Max: float64(ymax + 2),
- },
- },
- Series: series,
- }
- //graph.Elements = []chart.Renderable{
- // chart.Legend(&graph),
- //}
- filepath := "ofile/" + "temperature" + deviceSensorList[0].T_sn + ".jpg"
- f, _ := os.Create(filepath)
- defer f.Close()
- graph.Render(chart.PNG, f)
- return filepath, nil
- }
- // 获取湿度图片
- func DeviceDataHumidityJPG(startTime, endTime string, waybillPDF []service.WaybillPDF) (string, error) {
- if len(waybillPDF) == 0 {
- return "", errors.New("暂无数据可生成图片")
- }
- // 创建一个新的绘图
- p := plot.New()
- // 设置绘图标题和标签
- p.Title.Text = "humidity"
- deviceSensorList := []nats_server.DeviceSensor_R{}
- dataList := []nats_server.DeviceData_R{}
- for _, w := range waybillPDF {
- deviceSensorList = append(deviceSensorList, w.DeviceSensorList...)
- dataList = append(dataList, w.Data...)
- }
- humidityMin := deviceSensorList[0].T_DeviceSensorParameter.T_RHlower
- humidityMax := deviceSensorList[0].T_DeviceSensorParameter.T_RHupper
- var ymin, ymax float32
- for i, r := range dataList {
- if i == 0 {
- ymin = r.T_rh
- ymax = r.T_rh
- }
- if ymin > r.T_rh {
- ymin = r.T_rh
- }
- if ymax < r.T_rh {
- ymax = r.T_rh
- }
- }
- var chData = make(chan int, 10)
- var jobGroup sync.WaitGroup
- // 创建温度线
- for i := 0; i < len(deviceSensorList); i++ {
- chData <- 1
- jobGroup.Add(1)
- go func(index int) {
- defer func() {
- <-chData // 完成时chan取出1个
- jobGroup.Done() // 完成时将等待组值减1
- }()
- sn, id := deviceSensorList[index].T_sn, deviceSensorList[index].T_id
- r_maps := []nats_server.DeviceData_R{}
- for _, data := range dataList {
- if data.T_sn == sn && data.T_id == id {
- r_maps = append(r_maps, data)
- }
- }
- if len(r_maps) == 0 {
- return
- }
- sort.Slice(r_maps, func(i, j int) bool {
- return r_maps[i].T_time < r_maps[j].T_time
- })
- pts := make(plotter.XYs, len(r_maps))
- for j, d := range r_maps {
- t, _ := lib.TimeStrToTime(d.T_time)
- pts[j].X = float64(t.Unix())
- pts[j].Y = float64(d.T_rh)
- }
- line, err := plotter.NewLine(pts)
- if err != nil {
- return
- }
- line.Color = randomColor(index)
- p.Add(line)
- }(i)
- }
- jobGroup.Wait()
- st, _ := lib.TimeStrToTime(startTime)
- et, _ := lib.TimeStrToTime(endTime)
- xmin, xmax := float64(st.Unix()), float64(et.Unix())
- // 添加最高,最低标准线 用红色虚线标识
- p.Add(horizontalLine(xmin, xmax, float64(humidityMin)))
- p.Add(horizontalLine(xmin, xmax, float64(humidityMax)))
- if ymax < humidityMax {
- ymax = humidityMax
- }
- if ymin > 0 {
- ymin = 0
- }
- p.Y.Min, p.Y.Max = float64(ymin), float64(ymax)
- p.X.Min, p.X.Max = xmin, xmax
- p.Y.Tick.Marker = commaTicks{}
- //p.X.Tick.Marker = plot.TimeTicks{Format: "2006-01-02 15:04:05"}
- p.X.Tick.Marker = timeTicks{}
- p.X.Tick.Label.Rotation = math.Pi / 5
- p.X.Tick.Label.YAlign = draw.YCenter
- p.X.Tick.Label.XAlign = draw.XRight
- filepath := "ofile/" + "humidity" + deviceSensorList[0].T_sn + ".jpg"
- // 保存文件
- if err := p.Save(10*vg.Inch, 4*vg.Inch, filepath); err != nil {
- logs.Error(lib.FuncName(), "生成图片失败", err)
- return "", err
- }
- return filepath, nil
- }
- func DeviceDataHumidityJPG2(startTime, endTime string, waybillPDF []service.WaybillPDF) (string, error) {
- if len(waybillPDF) == 0 {
- return "", errors.New("暂无数据可生成图片")
- }
- deviceSensorList := []nats_server.DeviceSensor_R{}
- dataList := []nats_server.DeviceData_R{}
- for _, w := range waybillPDF {
- deviceSensorList = append(deviceSensorList, w.DeviceSensorList...)
- dataList = append(dataList, w.Data...)
- }
- humidityMin := deviceSensorList[0].T_DeviceSensorParameter.T_RHlower
- humidityMax := deviceSensorList[0].T_DeviceSensorParameter.T_RHupper
- var ymin, ymax float32
- for i, r := range dataList {
- if i == 0 {
- ymin = r.T_t
- ymax = r.T_t
- }
- if ymin > r.T_t {
- ymin = r.T_t
- }
- if ymax < r.T_t {
- ymax = r.T_t
- }
- }
- series := make([]chart.Series, 0)
- var chData = make(chan int, 10)
- var jobGroup sync.WaitGroup
- // 创建温度线
- for i := 0; i < len(deviceSensorList); i++ {
- chData <- 1
- jobGroup.Add(1)
- go func(index int) {
- defer func() {
- <-chData // 完成时chan取出1个
- jobGroup.Done() // 完成时将等待组值减1
- }()
- sn, id := deviceSensorList[index].T_sn, deviceSensorList[index].T_id
- r_maps := []nats_server.DeviceData_R{}
- for _, data := range dataList {
- if data.T_sn == sn && data.T_id == id {
- r_maps = append(r_maps, data)
- }
- }
- if len(r_maps) == 0 {
- return
- }
- sort.Slice(r_maps, func(i, j int) bool {
- return r_maps[i].T_time < r_maps[j].T_time
- })
- xValues := make([]time.Time, len(r_maps))
- yValues := make([]float64, len(r_maps))
- for j := 0; j < len(r_maps); j++ {
- t, _ := lib.TimeStrToTime(r_maps[j].T_time)
- xValues[j] = t
- yValues[j] = float64(r_maps[j].T_rh)
- }
- series = append(series, chart.TimeSeries{
- Name: fmt.Sprintf("%s-%d", sn, id),
- XValues: xValues,
- YValues: yValues,
- })
- }(i)
- }
- jobGroup.Wait()
- if ymax < humidityMax {
- ymax = humidityMax
- }
- if ymin > 0 {
- ymin = 0
- }
- if ymin > humidityMin {
- ymin = humidityMin
- }
- st, _ := lib.TimeStrToTime(startTime)
- et, _ := lib.TimeStrToTime(endTime)
- series = append(series, chart.TimeSeries{
- Style: chart.Style{
- StrokeColor: drawing.ColorRed,
- StrokeDashArray: []float64{5.0, 5.0},
- },
- XValues: []time.Time{st, et},
- YValues: []float64{float64(humidityMin), float64(humidityMin)},
- })
- series = append(series, chart.TimeSeries{
- Style: chart.Style{
- StrokeColor: drawing.ColorRed,
- StrokeDashArray: []float64{5.0, 5.0},
- },
- XValues: []time.Time{st, et},
- YValues: []float64{float64(humidityMax), float64(humidityMax)},
- })
- font := getZWFont()
- graph := chart.Chart{
- Title: "湿度记录",
- TitleStyle: chart.Style{
- FontSize: 15,
- },
- Background: chart.Style{
- Padding: chart.Box{
- Top: 20,
- },
- },
- Font: font,
- XAxis: chart.XAxis{
- Name: "时间",
- ValueFormatter: chart.TimeValueFormatterWithFormat("2006-01-02 15:04"),
- },
- YAxis: chart.YAxis{
- Name: "湿度",
- Range: &chart.ContinuousRange{
- Min: float64(ymin),
- Max: float64(ymax + 2),
- },
- },
- Series: series,
- }
- //graph.Elements = []chart.Renderable{
- // chart.Legend(&graph),
- //}
- filepath := "ofile/" + "humidity" + deviceSensorList[0].T_sn + ".jpg"
- f, _ := os.Create(filepath)
- defer f.Close()
- graph.Render(chart.PNG, f)
- return filepath, nil
- }
- func DeviceDataHumidityJPG3(startTime, endTime string, waybillPDF []service.WaybillPDF) (string, error) {
- if len(waybillPDF) == 0 {
- return "", errors.New("暂无数据可生成图片")
- }
- deviceSensorList := []nats_server.DeviceSensor_R{}
- dataList := []nats_server.DeviceData_R{}
- deviceDataPdfList := []service.DeviceDataPdf{}
- for _, w := range waybillPDF {
- deviceSensorList = append(deviceSensorList, w.DeviceSensorList...)
- dataList = append(dataList, w.Data...)
- deviceDataPdfList = append(deviceDataPdfList, w.DeviceDataPdf...)
- }
- TemperatureMin := deviceSensorList[0].T_DeviceSensorParameter.T_Tlower
- TemperatureMax := deviceSensorList[0].T_DeviceSensorParameter.T_Tupper
- var ymin, ymax float32
- for i, r := range dataList {
- if i == 0 {
- ymin = r.T_rh
- ymax = r.T_rh
- }
- if ymin > r.T_rh {
- ymin = r.T_rh
- }
- if ymax < r.T_rh {
- ymax = r.T_rh
- }
- }
- series := make([]chart.Series, 0)
- // 创建温度线
- xValues1 := make([]time.Time, len(deviceDataPdfList))
- yValues1 := make([]float64, len(deviceDataPdfList))
- xValues2 := make([]time.Time, len(deviceDataPdfList))
- yValues2 := make([]float64, len(deviceDataPdfList))
- for i := 0; i < len(deviceDataPdfList); i++ {
- t, _ := lib.TimeStrToTime(deviceDataPdfList[i].T_time)
- xValues1[i] = t
- yValues1[i] = float64(deviceDataPdfList[i].T_id1)
- xValues2[i] = t
- yValues2[i] = float64(deviceDataPdfList[i].T_id2)
- }
- series = append(series, chart.TimeSeries{
- Name: "T1",
- XValues: xValues1,
- YValues: yValues1,
- })
- series = append(series, chart.TimeSeries{
- Name: "T2",
- XValues: xValues2,
- YValues: yValues2,
- })
- if ymax < TemperatureMax {
- ymax = TemperatureMax
- }
- if ymin > 0 {
- ymin = 0
- }
- if ymin > TemperatureMin {
- ymin = TemperatureMin
- }
- st, _ := lib.TimeStrToTime(startTime)
- et, _ := lib.TimeStrToTime(endTime)
- series = append(series, chart.TimeSeries{
- Style: chart.Style{
- StrokeColor: drawing.ColorRed,
- StrokeDashArray: []float64{5.0, 5.0},
- },
- XValues: []time.Time{st, et},
- YValues: []float64{float64(TemperatureMin), float64(TemperatureMin)},
- })
- series = append(series, chart.TimeSeries{
- Style: chart.Style{
- StrokeColor: drawing.ColorRed,
- StrokeDashArray: []float64{5.0, 5.0},
- },
- XValues: []time.Time{st, et},
- YValues: []float64{float64(TemperatureMax), float64(TemperatureMax)},
- })
- font := getZWFont()
- graph := chart.Chart{
- Title: "温度记录",
- TitleStyle: chart.Style{
- FontSize: 15,
- },
- Background: chart.Style{
- Padding: chart.Box{
- Top: 20,
- },
- },
- Font: font,
- XAxis: chart.XAxis{
- Name: "时间",
- ValueFormatter: chart.TimeValueFormatterWithFormat("2006-01-02 15:04"),
- },
- YAxis: chart.YAxis{
- Name: "温度",
- Range: &chart.ContinuousRange{
- Min: float64(ymin),
- Max: float64(ymax + 2),
- },
- },
- Series: series,
- }
- //graph.Elements = []chart.Renderable{
- // chart.Legend(&graph),
- //}
- filepath := "ofile/" + "temperature" + deviceSensorList[0].T_sn + ".jpg"
- f, _ := os.Create(filepath)
- defer f.Close()
- graph.Render(chart.PNG, f)
- return filepath, nil
- }
- func horizontalLine(xmin, xmax, y float64) *plotter.Line {
- pts := make(plotter.XYs, 2)
- pts[0].X = xmin
- pts[0].Y = y
- pts[1].X = xmax
- pts[1].Y = y
- line, err := plotter.NewLine(pts)
- if err != nil {
- panic(err)
- }
- line.LineStyle.Dashes = []vg.Length{vg.Points(8), vg.Points(5), vg.Points(1), vg.Points(5)}
- line.Color = color.RGBA{R: 255, A: 255}
- return line
- }
- type timeTicks struct{}
- func (timeTicks) Ticks(min, max float64) []plot.Tick {
- tks := plot.TimeTicks{}.Ticks(min, max)
- for i, t := range tks {
- //if t.Label == "" { // Skip minor ticks, they are fine.
- // continue
- //}
- tks[i].Label = time.Unix(int64(t.Value), 0).Format("2006-01-02 15:04:05")
- }
- return tks
- }
- type commaTicks struct{}
- // Ticks computes the default tick marks, but inserts commas
- // into the labels for the major tick marks.
- func (commaTicks) Ticks(min, max float64) []plot.Tick {
- tks := plot.DefaultTicks{}.Ticks(min, max)
- for i, t := range tks {
- //if t.Label == "" { // Skip minor ticks, they are fine.
- // continue
- //}
- tks[i].Label = fmt.Sprintf("%.0f", t.Value)
- }
- return tks
- }
- // 生成随机颜色的辅助函数
- func randomColor(i int) color.RGBA {
- var colors []color.RGBA
- colors = append(colors,
- color.RGBA{R: 52, G: 152, B: 219, A: 255},
- color.RGBA{R: 230, G: 126, B: 34, A: 255},
- color.RGBA{R: 142, G: 68, B: 173, A: 255},
- color.RGBA{R: 211, G: 84, B: 0, A: 255},
- color.RGBA{R: 231, G: 76, B: 60, A: 255},
- color.RGBA{R: 26, G: 188, B: 156, A: 255},
- color.RGBA{R: 243, G: 156, B: 18, A: 255},
- color.RGBA{R: 22, G: 160, B: 133, A: 255},
- color.RGBA{R: 46, G: 204, B: 113, A: 255},
- color.RGBA{R: 39, G: 174, B: 96, A: 255},
- color.RGBA{R: 41, G: 128, B: 185, A: 255},
- color.RGBA{R: 155, G: 89, B: 182, A: 255},
- color.RGBA{R: 192, G: 57, B: 43, A: 255},
- color.RGBA{R: 241, G: 196, B: 15, A: 255},
- )
- return colors[i%len(colors)]
- }
- func randomColor2(i int) drawing.Color {
- var colors []drawing.Color
- colors = append(colors,
- drawing.Color{R: 52, G: 152, B: 219, A: 255},
- drawing.Color{R: 230, G: 126, B: 34, A: 255},
- drawing.Color{R: 142, G: 68, B: 173, A: 255},
- drawing.Color{R: 211, G: 84, B: 0, A: 255},
- drawing.Color{R: 231, G: 76, B: 60, A: 255},
- drawing.Color{R: 26, G: 188, B: 156, A: 255},
- drawing.Color{R: 243, G: 156, B: 18, A: 255},
- drawing.Color{R: 22, G: 160, B: 133, A: 255},
- drawing.Color{R: 46, G: 204, B: 113, A: 255},
- drawing.Color{R: 39, G: 174, B: 96, A: 255},
- drawing.Color{R: 41, G: 128, B: 185, A: 255},
- drawing.Color{R: 155, G: 89, B: 182, A: 255},
- drawing.Color{R: 192, G: 57, B: 43, A: 255},
- drawing.Color{R: 241, G: 196, B: 15, A: 255},
- )
- return colors[i%len(colors)]
- }
- // getZWFont 加载字体
- func getZWFont() *truetype.Font {
- fontFile := "./static/fonts/MiSans-Medium.ttf"
- fontBytes, err := os.ReadFile(fontFile)
- if err != nil {
- log.Println(err)
- return nil
- }
- font, err := truetype.Parse(fontBytes)
- if err != nil {
- log.Println(err)
- return nil
- }
- return font
- }
|