package controllers import ( "XT_New/common" "XT_New/enums" "XT_New/invoice" "XT_New/models" "XT_New/models/bwfapiao" "XT_New/service" "XT_New/service/fapiao" "XT_New/utils" "bytes" "crypto/md5" "crypto/sha1" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "github.com/astaxie/beego" "github.com/shopspring/decimal" "io/ioutil" "math" "net/http" "sort" "strconv" "strings" "time" ) func FaPiaoApiRegistRouters() { beego.Router("/api/bwfapiao/sms/code", &FapiaoApiController{}, "get:GetLoginUploadCode") beego.Router("/api/bwfapiao/sms/login", &FapiaoApiController{}, "get:Login") beego.Router("/api/bwfapiao/qrcode/get", &FapiaoApiController{}, "get:GetQRCode") //beego.Router("/api/bwfapiao/blue", &FapiaoApiController{}, "get:OpenFaPiao") //beego.Router("/api/bwfapiao/red", &FapiaoApiController{}, "get:RedFaPiao") beego.Router("/api/order/fapiao/list", &FapiaoApiController{}, "get:GetOrderFaPiaoList") beego.Router("/api/fapiao/list", &FapiaoApiController{}, "get:GetFaPiaoList") beego.Router("/api/newfapiao/get", &HisApiController{}, "get:GetNewFaPiaoData") beego.Router("/api/fapiao/query", &FapiaoApiController{}, "get:QueryFaPiao") //百望云 //beego.Router("/api/bwfapiao/login", &FapiaoApiController{}, "get:GetBwFaPiaoLogin") //beego.Router("/api/bwfapiao/qrcode", &FapiaoApiController{}, "get:GetBwFaPiaoQRCode") beego.Router("/api/bwfapiao/blue", &FapiaoApiController{}, "get:BwOpenBlueFaPiao") beego.Router("/api/bwfapiao/query", &FapiaoApiController{}, "get:QueryBwFaPiao") beego.Router("/api/bwfapiao/red", &FapiaoApiController{}, "get:BwOpenRedFaPiao") } func signTopRequestTwo(params map[string]string, secret string, body map[string]interface{}) (string, error) { // 第一步:检查参数是否已经排序 keys := make([]string, 0, len(params)) for k := range params { keys = append(keys, k) } sort.Strings(keys) // 第二步:把所有参数名和参数值串在一起 var query strings.Builder query.WriteString(secret) // 拼接 secret for _, k := range keys { v := params[k] if v != "" { query.WriteString(k) query.WriteString(v) } } // 将 body 序列化为 JSON bodyBytes, err := json.Marshal(body) if err != nil { return "", errors.New("failed to serialize request body: " + err.Error()) } bodyString := string(bytes.TrimSpace(bodyBytes)) // 去掉多余的空格和换行 query.WriteString(bodyString) // 拼接 body query.WriteString(secret) // 再次拼接 secret // 第三步:使用 MD5 计算哈希 md5Hash := md5.New() md5Hash.Write([]byte(query.String())) hashBytes := md5Hash.Sum(nil) // 第四步:将结果转成大写十六进制字符串 sign := strings.ToUpper(hex.EncodeToString(hashBytes)) return sign, nil } func (c *FapiaoApiController) BwOpenBlueFaPiao() { //判断是否处于登录状态 //开蓝票逻辑 order_ids := c.GetString("order_ids") admin_user_id, _ := c.GetInt64("admin_user_id") ids := strings.Split(order_ids, ",") orders, _ := service.GetFaPiaoOrderByIDS(ids) var MedfeeSumamt float64 = 0 //治疗费用 var PsnCashPay float64 = 0 //治疗费用 var FundPaySumamt float64 = 0 //治疗费用 var HifmiPay float64 = 0 //治疗费用 var MafPay float64 = 0 //治疗费用 var HifpPay float64 = 0 //治疗费用 var AcctPay float64 = 0 //治疗费用 var details []models.HisOrderInfo var numbers []string decimal.DivisionPrecision = 2 var remark string for _, oss := range orders { MedfeeSumamt, _ = decimal.NewFromFloat(MedfeeSumamt).Add(decimal.NewFromFloat(oss.MedfeeSumamt)).Float64() PsnCashPay, _ = decimal.NewFromFloat(PsnCashPay).Add(decimal.NewFromFloat(oss.PsnCashPay)).Float64() FundPaySumamt, _ = decimal.NewFromFloat(FundPaySumamt).Add(decimal.NewFromFloat(oss.FundPaySumamt)).Float64() HifmiPay, _ = decimal.NewFromFloat(HifmiPay).Add(decimal.NewFromFloat(oss.HifmiPay)).Float64() MafPay, _ = decimal.NewFromFloat(MafPay).Add(decimal.NewFromFloat(oss.MafPay)).Float64() HifpPay, _ = decimal.NewFromFloat(HifpPay).Add(decimal.NewFromFloat(oss.HifpPay)).Float64() AcctPay, _ = decimal.NewFromFloat(AcctPay).Add(decimal.NewFromFloat(oss.AcctPay)).Float64() numbers = append(numbers, oss.Number) } if MedfeeSumamt > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "医疗总费用: " + MedfeeSumamt_str } else { remark = remark + " 医疗总费用:" + MedfeeSumamt_str } } if FundPaySumamt > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", FundPaySumamt) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "基金支付总金额: " + MedfeeSumamt_str } else { remark = remark + " 基金支付总金额:" + MedfeeSumamt_str } } if PsnCashPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", PsnCashPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "个人现金支付: " + MedfeeSumamt_str } else { remark = remark + " 个人现金支付:" + MedfeeSumamt_str } } if HifmiPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", HifmiPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "大病基金支付: " + MedfeeSumamt_str } else { remark = remark + " 大病基金支付:" + MedfeeSumamt_str } } if AcctPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", AcctPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "个账支付: " + MedfeeSumamt_str } else { remark = remark + " 个账支付:" + MedfeeSumamt_str } } if HifpPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", HifpPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "基本统筹基金支付: " + MedfeeSumamt_str } else { remark = remark + " 基本统筹基金支付:" + MedfeeSumamt_str } } if MafPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", MafPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "医疗救助基金支付: " + MedfeeSumamt_str } else { remark = remark + " 医疗救助基金支付:" + MedfeeSumamt_str } } details, _ = service.GetFaPiaoOrderInfoByNumbers(numbers) role, _ := service.GetAdminUserRole(admin_user_id, c.GetAdminUserInfo().CurrentOrgId) role.UserName = "" type CostType struct { name string price float64 } var cts []CostType var ct CostType var bedCostTotal float64 = 0 //床位总费 var operationCostTotal float64 = 0 //手术费 var otherCostTotal float64 = 0 //其他费用 var materialCostTotal float64 = 0 //材料费 var westernMedicineCostTotal float64 = 0 //西药费 var chineseTraditionalMedicineCostTotal float64 = 0 //中成药 var checkCostTotal float64 = 0 //检查费 var laboratoryCostTotal float64 = 0 //化验费 var treatCostTotal float64 = 0 //治疗费用 var huliCostTotal float64 = 0 //治疗费用 var zhencaCostTotal float64 = 0 //治疗费用 for _, item := range details { if item.MedChrgitmType == "01" { //床位费 bedCostTotal, _ = decimal.NewFromFloat(bedCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "07" { //护理费 huliCostTotal, _ = decimal.NewFromFloat(huliCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if c.GetAdminUserInfo().CurrentOrgId == 10188 || c.GetAdminUserInfo().CurrentOrgId == 10217 { if item.MedChrgitmType == "03" { //检查费 laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } } else { if item.MedChrgitmType == "03" { //检查费 checkCostTotal, _ = decimal.NewFromFloat(checkCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } } if item.MedChrgitmType == "04" { //化验费 laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "05" || item.MedChrgitmType == "1402" || item.MedChrgitmType == "1403" { //治疗费 treatCostTotal, _ = decimal.NewFromFloat(treatCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "06" { //手术费 operationCostTotal, _ = decimal.NewFromFloat(operationCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "08" { //材料费 materialCostTotal, _ = decimal.NewFromFloat(materialCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "09" { //西药费 westernMedicineCostTotal, _ = decimal.NewFromFloat(westernMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "11" { //中成费 chineseTraditionalMedicineCostTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "14" || item.MedChrgitmType == "0" || item.MedChrgitmType == "12" { //其他费 otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "02" { //诊察 zhencaCostTotal, _ = decimal.NewFromFloat(zhencaCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } } if bedCostTotal > 0 { ct.name = "床位费" ct.price = bedCostTotal cts = append(cts, ct) } if operationCostTotal > 0 { ct.name = "手术费" ct.price = operationCostTotal cts = append(cts, ct) } if otherCostTotal > 0 { ct.name = "其他费" ct.price = otherCostTotal cts = append(cts, ct) } if materialCostTotal > 0 { ct.name = "材料费" ct.price = materialCostTotal cts = append(cts, ct) } if westernMedicineCostTotal > 0 { ct.name = "西药费" ct.price = westernMedicineCostTotal cts = append(cts, ct) } if chineseTraditionalMedicineCostTotal > 0 { ct.name = "中成药费" ct.price = chineseTraditionalMedicineCostTotal cts = append(cts, ct) } if checkCostTotal > 0 { ct.name = "检查费" ct.price = checkCostTotal cts = append(cts, ct) } if laboratoryCostTotal > 0 { ct.name = "化验费" ct.price = laboratoryCostTotal cts = append(cts, ct) } if treatCostTotal > 0 { ct.name = "治疗费" ct.price = treatCostTotal cts = append(cts, ct) } if huliCostTotal > 0 { ct.name = "护理费" ct.price = huliCostTotal cts = append(cts, ct) } if zhencaCostTotal > 0 { ct.name = "诊察费" ct.price = zhencaCostTotal cts = append(cts, ct) } //org_config, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId) var config2 models.FapiaoConfig config2, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) number := strconv.FormatInt(time.Now().Unix(), 10) + "_" + strconv.FormatInt(orders[0].UserOrgId, 10) + "_" + strconv.FormatInt(orders[0].PatientId, 10) amountWithoutTax, _, taxAmount, _ := CalculatePriceDetails(MedfeeSumamt, 1, 0.00) patient, _ := service.GetXTPatientInfo(c.GetAdminUserInfo().CurrentOrgId, orders[0].PatientId) orders[0].PsnName = patient.Name requestBody2 := map[string]interface{}{ "taxNo": config2.TerminalCode, "taxUserName": "", "invoiceTerminalCode": "", "isSplit": "", "orgCode": "", "taxDiskNo": "", "formatGenerate": "", "formatPushType": "", "completionCustom": "", "isAsync": "", "isReturnRedInfo": "", } //var subData map[string]interface{} subData := make(map[string]interface{}) subData["invoiceTypeCode"] = "02" subData["paperInvoiceFlag"] = "" subData["paperInvoiceTypeCode"] = "" subData["paperInvoiceTypeCode"] = "" subData["invoiceType"] = "0" subData["invoiceSpecialMark"] = "00" subData["isConfirmIssue"] = "" subData["confirmIssue"] = "" subData["taxationMethod"] = "" subData["taxationLabel"] = "" subData["reducedTaxCode"] = "" subData["invoiceListMark"] = "" subData["priceTaxMark"] = "" subData["serialNo"] = number // todo subData["orderNo"] = "" //todo subData["buyerTaxNo"] = "" //todo subData["buyerName"] = orders[0].PsnName + "(个人)" subData["buyerAddressPhone"] = "" subData["buyerBankAccount"] = "" subData["drawer"] = "" subData["checker"] = "" subData["payee"] = "" subData["invoiceTotalPrice"] = MedfeeSumamt subData["invoiceTotalTax"] = taxAmount subData["invoiceTotalPriceTax"] = amountWithoutTax subData["remarks"] = remark subData["redInfoNo"] = "" subData["originalInvoiceCode"] = "" subData["originalInvoiceNo"] = "" subData["deductibleAmount"] = "" subData["sellerAddressPhone"] = "" subData["sellerBankAccount"] = "" //var subDetails []map[string]interface{} subDetails := make([]map[string]interface{}, 0) for index, item := range cts { subDetailData := make(map[string]interface{}) amountWithoutTax_two, _, taxAmount_tow, _ := CalculatePriceDetails(item.price, 1, 0.00) subDetailData["goodsLineNo"] = index + 1 subDetailData["originalInvoiceDetailNo"] = "" subDetailData["invoiceLineNature"] = "0" subDetailData["goodsCode"] = "3070202000000000000" subDetailData["goodsBarCode"] = "" subDetailData["goodsPersonalCode"] = "" subDetailData["goodsName"] = item.name subDetailData["goodsSpecification"] = "" subDetailData["goodsUnit"] = "" subDetailData["goodsQuantity"] = "1" subDetailData["goodsPrice"] = amountWithoutTax_two subDetailData["goodsTotalPrice"] = amountWithoutTax_two subDetailData["goodsTotalTax"] = taxAmount_tow subDetailData["goodsTaxRate"] = "0" subDetailData["vatSpecialManagement"] = "" subDetailData["freeTaxMark"] = "3" subDetailData["preferentialMarkFlag"] = "" subDetailData["goodsDiscountAmount"] = "0" subDetails = append(subDetails, subDetailData) } subData["invoiceDetailsList"] = subDetails requestBody2["data"] = subData status, reason, response, request_log, response_log := OpenBWBlue(requestBody2) if status == 0 { //失败 c.ServeSuccessJSON(map[string]interface{}{ "status": -10, "msg": reason, }) } else { //成功 var fapiaos models.HisFaPiaoOrder fapiaos.InvoiceId = response.Response.Success[0].SerialNo fapiaos.OrderSn = response.Response.Success[0].SerialNo fapiaos.OrderIds = order_ids fapiaos.UserOrgId = c.GetAdminUserInfo().CurrentOrgId fapiaos.Status = 1 // 解析日期字符串的布局(对应输入的格式) layout := "20060102150405" // 将字符串解析为时间对象 t, _ := time.Parse(layout, response.Response.Success[0].InvoiceDate) // 将时间对象格式化为所需的输出格式 output := t.Format("2006-01-02 15:04:05") fapiaos.TicketDate = output fapiaos.PatientId = orders[0].PatientId fapiaos.Ctime = time.Now().Unix() fapiaos.Mtime = time.Now().Unix() fapiaos.Creator = role.UserName fapiaos.MedfeeSumamt = MedfeeSumamt fapiaos.FundPaySumamt = FundPaySumamt fapiaos.PsnCashPay = PsnCashPay fapiaos.TicketSn = response.Response.Success[0].InvoiceNo fapiaos.AmountWithTax = fmt.Sprintf("%.2f", response.Response.Success[0].InvoiceTotalPrice) fapiaos.AmountWithoutTax = fmt.Sprintf("%.2f", response.Response.Success[0].InvoiceTotalPrice) fapiaos.FapiaoStatus = "2" fapiaos.TaxAmount = fmt.Sprintf("%.2f", response.Response.Success[0].InvoiceTotalTax) fapiaos.IsRedWashed = "0" fapiaos.PdfUrl = response.Response.Success[0].EInvoiceUrl fapiaos.OfdUrl = "" fapiaos.XmlUrl = "" fapiaos.OfdUrl = "" fapiaos.XmlUrl = "" fapiaos.BlueRequestInfo = request_log fapiaos.BlueResponseInfo = response_log err := service.SaveFaPiaoOrder(&fapiaos) err = service.UpdateFaPiaoSN(response.Response.Success[0].SerialNo, ids) //同步发票号码 err = service.UpdateFaPiaoNumber(response.Response.Success[0].InvoiceNo, ids) //同步发票号码 fmt.Println(err) status2, msg, result := BWBanShi(config2, response.Response.Success[0].InvoiceNo) if status2 == 0 { c.ServeSuccessJSON(map[string]interface{}{ "msg": msg, }) return } else { fapiaos.PdfUrl = result.Response.UrlMap.PdfUrl fapiaos.OfdUrl = result.Response.UrlMap.OfdUrl fapiaos.XmlUrl = result.Response.UrlMap.XmlUrl err := service.SaveFaPiaoOrder(&fapiaos) if err == nil { c.ServeSuccessJSON(map[string]interface{}{ "msg": "成功", }) return } else { c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong) return } } } } func (c *FapiaoApiController) BwOpenRedFaPiao() { id, _ := c.GetInt64("id") admin_user_id, _ := c.GetInt64("admin_user_id") fapiao_config, _ := service.GetFaPiaoOrderById(id) role, _ := service.GetAdminUserRole(admin_user_id, c.GetAdminUserInfo().CurrentOrgId) var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) status, reason, resp, request_log, resp_log := OpenBWRed(config, fapiao_config) if status == 1 { fapiao_config.IsRedWashed = "1" fapiao_config.Status = 0 fapiao_config.RedInvoiceId = resp[0].RedInvoiceNo fapiao_config.RedInvoiceUUID = resp[0].RedConfirmUUID fapiao_config.RedInvoiceCreator = role.UserName fapiao_config.RedRequestInfo = request_log fapiao_config.RedResponseInfo = resp_log service.SaveFaPiaoOrder(&fapiao_config) //将结算表的发票号码清空 service.UpdateFaPiaoNumberByNumber(fapiao_config.TicketSn) c.ServeSuccessJSON(map[string]interface{}{ "msg": "红冲成功", }) } else { c.ServeSuccessJSON(map[string]interface{}{ "msg": reason, }) } } func (c *FapiaoApiController) QueryBwFaPiao() { id, _ := c.GetInt64("id") oc, _ := service.GetFaPiaoOrderById(id) var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) QueryBWInvoiceInfoTwo(config, oc) } // 百望云发票开票 func OpenBWBlue(requestBody2 map[string]interface{}) (int64, string, bwfapiao.InvoiceIssueResponse, string, string) { // 解析 JSON 响应 var result bwfapiao.InvoiceIssueResponse fmt.Println(requestBody2) redisClient := service.RedisClient() defer redisClient.Close() fapiao_access_token, _ := redisClient.Get("fapiao_access_token").Result() fmt.Println(fapiao_access_token) // 示例数据 params := map[string]string{ "method": "baiwang.output.invoice.issue", "version": "6.0", "appKey": "10059482", "format": "json", "timestamp": strconv.FormatInt(time.Now().Unix(), 10), "token": fapiao_access_token, "type": "sync", } secret := "bb481e0c-9895-44d8-b184-6b9707a60ec7" reques_log, _ := json.Marshal(requestBody2) // 生成签名 sign, err := signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return 0, err.Error(), result, string(reques_log), "" } params["sign"] = sign if len(fapiao_access_token) > 0 { //token 存在则进行签名处理 // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return 0, err.Error(), result, string(reques_log), response } err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return 0, err2.Error(), result, string(reques_log), response } // 判断接口是否成功调用 if result.Success { return 1, "开具成功", result, string(reques_log), response } else { fmt.Println(result.ErrorResponse.Message) fmt.Println(result.ErrorResponse.SubMessage) return 0, result.ErrorResponse.Message + "\n" + result.ErrorResponse.SubMessage, result, string(reques_log), response } } else { //token 不存在,则进行获取token的操作 fmt.Println("token 不存在") tokenResp, _ := GetAccessToken("https://openapi.baiwang.com/router/rest", "b033l65qAA", "cc73223bd14a4064bb0fe9ba642da58f", "10059482", "bb481e0c-9895-44d8-b184-6b9707a60ec7", "admin_ffzyx16zmybx4", "") fmt.Println(tokenResp) if len(tokenResp.Response.AccessToken) > 0 { //token请求成功,则将token和有效时间存储进redis, redisClient.Set("fapiao_access_token", tokenResp.Response.AccessToken, time.Duration(tokenResp.Response.ExpiresIn)*time.Second) params["token"] = tokenResp.Response.AccessToken // 生成签名 sign, err = signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return 0, err.Error(), result, string(reques_log), "" } params["sign"] = sign // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return 0, err.Error(), result, string(reques_log), response } err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return 0, err2.Error(), result, string(reques_log), response } // 判断接口是否成功调用 if result.Success { return 1, "开具成功", result, string(reques_log), response } else { fmt.Println(result.ErrorResponse.Message) fmt.Println(result.ErrorResponse.SubMessage) return 0, result.ErrorResponse.Message + "\n" + result.ErrorResponse.SubMessage, result, string(reques_log), response } } else { return 0, "获取token失败", result, string(reques_log), "" } } } // 百望云发票全电红字确认单申请 func OpenBWRed(config models.FapiaoConfig, orders models.HisFaPiaoOrder) (int64, string, []bwfapiao.RedAddInvoiceData, string, string) { var result bwfapiao.RedAddResponse redisClient := service.RedisClient() defer redisClient.Close() patient, _ := service.GetPatientByID(orders.UserOrgId, orders.PatientId) fapiao_access_token, _ := redisClient.Get("fapiao_access_token").Result() // 示例数据 params := map[string]string{ "method": "baiwang.output.redinvoice.add", "version": "6.0", "appKey": "10059482", "format": "json", "timestamp": strconv.FormatInt(time.Now().Unix(), 10), "token": fapiao_access_token, "type": "sync", } secret := "bb481e0c-9895-44d8-b184-6b9707a60ec7" _, _, taxAmount, _ := CalculatePriceDetails(orders.MedfeeSumamt, 1, 0.00) number := strconv.FormatInt(time.Now().Unix(), 10) requestBody2 := map[string]interface{}{ "taxNo": config.TerminalCode, "orgCode": "", "taxUserName": "", "drawer": "", "redConfirmSerialNo": number, "entryIdentity": "01", "sellerTaxNo": config.TerminalCode, "sellerTaxName": "广州从化意达血液透析有限责任公司", "deliverFlag": "", "buyerEmail": "", "buyerPhone": "", "buyerTaxNo": "", "buyerTaxName": patient.Name + "(个人)", //todo //购买方名称 "redInvoiceIsPaper": "", "originInvoiceIsPaper": "N", "originalInvoiceNo": orders.TicketSn, "originalPaperInvoiceCode": "", "originalPaperInvoiceNo": "", "originInvoiceDate": orders.TicketDate, //todo 蓝字发票开票日期 yyyy-MM-dd HH:mm:ss "originInvoiceTotalPrice": orders.MedfeeSumamt, //todo 蓝字发票合计金额 "originInvoiceTotalTax": taxAmount, //todo 蓝字发票合计税额 "originInvoiceType": "02", //todo 蓝字发票票种代码 01:增值税专用发票 02:普通发票 03:机动车统一销售发票 04:二手车统一销售发票 "originInvoiceSetCode": "", "autoIssueSwitch": "", "invoiceTotalPrice": -orders.MedfeeSumamt, //todo 红字冲销金额 "invoiceTotalTax": taxAmount, //todo 红字冲销税额 "redInvoiceLabel": "01", //todo "invoiceSource": "2", "priceTaxMark": "0", } ids := strings.Split(orders.OrderIds, ",") order, _ := service.GetFaPiaoOrderByIDS(ids) var MedfeeSumamt float64 = 0 //治疗费用 var PsnCashPay float64 = 0 //治疗费用 var FundPaySumamt float64 = 0 //治疗费用 var HifmiPay float64 = 0 //治疗费用 var MafPay float64 = 0 //治疗费用 var HifpPay float64 = 0 //治疗费用 var AcctPay float64 = 0 //治疗费用 var details []models.HisOrderInfo var numbers []string decimal.DivisionPrecision = 2 var remark string for _, oss := range order { MedfeeSumamt, _ = decimal.NewFromFloat(MedfeeSumamt).Add(decimal.NewFromFloat(oss.MedfeeSumamt)).Float64() PsnCashPay, _ = decimal.NewFromFloat(PsnCashPay).Add(decimal.NewFromFloat(oss.PsnCashPay)).Float64() FundPaySumamt, _ = decimal.NewFromFloat(FundPaySumamt).Add(decimal.NewFromFloat(oss.FundPaySumamt)).Float64() HifmiPay, _ = decimal.NewFromFloat(HifmiPay).Add(decimal.NewFromFloat(oss.HifmiPay)).Float64() MafPay, _ = decimal.NewFromFloat(MafPay).Add(decimal.NewFromFloat(oss.MafPay)).Float64() HifpPay, _ = decimal.NewFromFloat(HifpPay).Add(decimal.NewFromFloat(oss.HifpPay)).Float64() AcctPay, _ = decimal.NewFromFloat(AcctPay).Add(decimal.NewFromFloat(oss.AcctPay)).Float64() numbers = append(numbers, oss.Number) } if MedfeeSumamt > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "医疗总费用: " + MedfeeSumamt_str } else { remark = remark + " 医疗总费用:" + MedfeeSumamt_str } } if FundPaySumamt > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", FundPaySumamt) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "基金支付总金额: " + MedfeeSumamt_str } else { remark = remark + " 基金支付总金额:" + MedfeeSumamt_str } } if PsnCashPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", PsnCashPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "个人现金支付: " + MedfeeSumamt_str } else { remark = remark + " 个人现金支付:" + MedfeeSumamt_str } } if HifmiPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", HifmiPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "大病基金支付: " + MedfeeSumamt_str } else { remark = remark + " 大病基金支付:" + MedfeeSumamt_str } } if AcctPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", AcctPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "个账支付: " + MedfeeSumamt_str } else { remark = remark + " 个账支付:" + MedfeeSumamt_str } } if HifpPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", HifpPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "基本统筹基金支付: " + MedfeeSumamt_str } else { remark = remark + " 基本统筹基金支付:" + MedfeeSumamt_str } } if MafPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", MafPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "医疗救助基金支付: " + MedfeeSumamt_str } else { remark = remark + " 医疗救助基金支付:" + MedfeeSumamt_str } } details, _ = service.GetFaPiaoOrderInfoByNumbers(numbers) type CostType struct { name string price float64 } var cts []CostType var ct CostType var bedCostTotal float64 = 0 //床位总费 var operationCostTotal float64 = 0 //手术费 var otherCostTotal float64 = 0 //其他费用 var materialCostTotal float64 = 0 //材料费 var westernMedicineCostTotal float64 = 0 //西药费 var chineseTraditionalMedicineCostTotal float64 = 0 //中成药 var checkCostTotal float64 = 0 //检查费 var laboratoryCostTotal float64 = 0 //化验费 var treatCostTotal float64 = 0 //治疗费用 var huliCostTotal float64 = 0 //治疗费用 var zhencaCostTotal float64 = 0 //治疗费用 for _, item := range details { if item.MedChrgitmType == "01" { //床位费 bedCostTotal, _ = decimal.NewFromFloat(bedCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "07" { //护理费 huliCostTotal, _ = decimal.NewFromFloat(huliCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "03" { //检查费 checkCostTotal, _ = decimal.NewFromFloat(checkCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "04" { //化验费 laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "05" || item.MedChrgitmType == "1402" || item.MedChrgitmType == "1403" { //治疗费 treatCostTotal, _ = decimal.NewFromFloat(treatCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "06" { //手术费 operationCostTotal, _ = decimal.NewFromFloat(operationCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "08" { //材料费 materialCostTotal, _ = decimal.NewFromFloat(materialCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "09" { //西药费 westernMedicineCostTotal, _ = decimal.NewFromFloat(westernMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "11" { //中成费 chineseTraditionalMedicineCostTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "14" || item.MedChrgitmType == "0" || item.MedChrgitmType == "12" { //其他费 otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "02" { //诊察 zhencaCostTotal, _ = decimal.NewFromFloat(zhencaCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } } if bedCostTotal > 0 { ct.name = "床位费" ct.price = bedCostTotal cts = append(cts, ct) } if operationCostTotal > 0 { ct.name = "手术费" ct.price = operationCostTotal cts = append(cts, ct) } if otherCostTotal > 0 { ct.name = "其他费" ct.price = otherCostTotal cts = append(cts, ct) } if materialCostTotal > 0 { ct.name = "材料费" ct.price = materialCostTotal cts = append(cts, ct) } if westernMedicineCostTotal > 0 { ct.name = "西药费" ct.price = westernMedicineCostTotal cts = append(cts, ct) } if chineseTraditionalMedicineCostTotal > 0 { ct.name = "中成药费" ct.price = chineseTraditionalMedicineCostTotal cts = append(cts, ct) } if checkCostTotal > 0 { ct.name = "检查费" ct.price = checkCostTotal cts = append(cts, ct) } if laboratoryCostTotal > 0 { ct.name = "化验费" ct.price = laboratoryCostTotal cts = append(cts, ct) } if treatCostTotal > 0 { ct.name = "治疗费" ct.price = treatCostTotal cts = append(cts, ct) } if huliCostTotal > 0 { ct.name = "护理费" ct.price = huliCostTotal cts = append(cts, ct) } if zhencaCostTotal > 0 { ct.name = "诊察费" ct.price = zhencaCostTotal cts = append(cts, ct) } subDetails := make([]map[string]interface{}, 0) for index, item := range cts { _, _, taxAmount_tow, _ := CalculatePriceDetails(item.price, 1, 0.00) subDetailData := make(map[string]interface{}) subDetailData["originalInvoiceDetailNo"] = index + 1 subDetailData["goodsLineNo"] = index + 1 subDetailData["invoiceLineNature"] = "" subDetailData["goodsCode"] = "3070202000000000000" subDetailData["goodsName"] = item.name subDetailData["goodsSimpleName"] = "" subDetailData["projectName"] = item.name subDetailData["goodsSpecification"] = "" subDetailData["goodsUnit"] = "" subDetailData["goodsQuantity"] = "" subDetailData["goodsPrice"] = -item.price subDetailData["goodsTaxRate"] = "0" subDetailData["goodsTotalPrice"] = -item.price subDetailData["goodsTotalTax"] = taxAmount_tow subDetailData["goodsPriceTax"] = -item.price subDetailData["goodsTotalPriceTax"] = -item.price subDetails = append(subDetails, subDetailData) } requestBody2["redConfirmDetailReqEntityList"] = subDetails request, _ := json.Marshal(requestBody2) // 生成签名 sign, err := signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return 0, err.Error(), result.Response, string(request), "" } params["sign"] = sign if len(fapiao_access_token) > 0 { //token 存在则进行签名处理 // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return 0, err.Error(), result.Response, string(request), "" } // 解析 JSON 响应 var result bwfapiao.RedAddResponse err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return 0, err.Error(), result.Response, string(request), response } // 判断接口是否成功调用 if result.Success { return 1, "红冲成功", result.Response, string(request), response } else { return 0, result.ErrorResponse.Message + "\n" + result.ErrorResponse.SubMessage, result.Response, string(request), response } } else { //token 不存在,则进行获取token的操作 tokenResp, _ := GetAccessToken("https://openapi.baiwang.com/router/rest", "b033l65qAA", "cc73223bd14a4064bb0fe9ba642da58f", "10059482", "bb481e0c-9895-44d8-b184-6b9707a60ec7", "admin_ffzyx16zmybx4", "") if len(tokenResp.Response.AccessToken) > 0 { //token请求成功,则将token和有效时间存储进redis, redisClient.Set("fapiao_access_token", tokenResp.Response.AccessToken, time.Duration(tokenResp.Response.ExpiresIn)*time.Second) params["token"] = tokenResp.Response.AccessToken // 生成签名 sign, err = signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return 0, err.Error(), result.Response, string(request), "" } params["sign"] = sign // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return 0, err.Error(), result.Response, string(request), "" } // 解析 JSON 响应 err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return 0, err.Error(), result.Response, string(request), "" } // 判断接口是否成功调用 if result.Success { return 1, "红冲成功", result.Response, string(request), response } else { return 0, result.ErrorResponse.Message + "\n" + result.ErrorResponse.SubMessage, result.Response, string(request), response } } else { //获取token失败 return 0, "获取token失败", result.Response, string(request), "" } } } func BWBanShi(config models.FapiaoConfig, invoiceNo string) (int64, string, bwfapiao.BanShiResponse) { var result bwfapiao.BanShiResponse redisClient := service.RedisClient() defer redisClient.Close() fapiao_access_token, _ := redisClient.Get("fapiao_access_token").Result() // 示例数据 params := map[string]string{ "method": "baiwang.output.format.create", "version": "6.0", "appKey": "10059482", "format": "json", "timestamp": strconv.FormatInt(time.Now().Unix(), 10), "token": fapiao_access_token, "type": "sync", } secret := "bb481e0c-9895-44d8-b184-6b9707a60ec7" data := make(map[string]interface{}) data["pushType"] = "" data["invoiceIssueMode"] = "1" data["invoiceCode"] = "" data["invoiceNo"] = invoiceNo data["einvoiceNo"] = invoiceNo data["serialNo"] = "" data["phone"] = "" data["email"] = "" data["emailCarbonCopy"] = "" requestBody2 := map[string]interface{}{ "taxNo": config.TerminalCode, "data": data, } // 生成签名 sign, err := signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return 0, err.Error(), result } params["sign"] = sign if len(fapiao_access_token) > 0 { //token 存在则进行签名处理 // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return 0, err.Error(), result } // 解析 JSON 响应 err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return 0, err2.Error(), result } // 判断接口是否成功调用 if result.Success { return 1, "", result } else { return 0, "", result } } else { //token 不存在,则进行获取token的操作 tokenResp, _ := GetAccessToken("https://openapi.baiwang.com/router/rest", "b033l65qAA", "cc73223bd14a4064bb0fe9ba642da58f", "10059482", "bb481e0c-9895-44d8-b184-6b9707a60ec7", "admin_ffzyx16zmybx4", "") if len(tokenResp.Response.AccessToken) > 0 { //token请求成功,则将token和有效时间存储进redis, redisClient.Set("fapiao_access_token", tokenResp.Response.AccessToken, time.Duration(tokenResp.Response.ExpiresIn)*time.Second) params["token"] = tokenResp.Response.AccessToken // 生成签名 sign, err = signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return 0, err.Error(), result } params["sign"] = sign // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return 0, err.Error(), result } // 解析 JSON 响应 var result bwfapiao.BanShiResponse err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return 0, err2.Error(), result } // 判断接口是否成功调用 if result.Success { return 1, "", result } else { return 0, result.ErrorResponse.Message + "\n" + result.ErrorResponse.SubMessage, result } } else { //获取token失败 return 0, "获取token失败", result } } } // 百望云发票红字确认单操作 func BWRedOperate(config models.FapiaoConfig, uuid string, no string) (int64, string) { redisClient := service.RedisClient() defer redisClient.Close() fapiao_access_token, _ := redisClient.Get("fapiao_access_token").Result() // 示例数据 params := map[string]string{ "method": "baiwang.output.redinvoice.operate", "version": "6.0", "appKey": "10059482", "format": "json", "timestamp": strconv.FormatInt(time.Now().Unix(), 10), "token": fapiao_access_token, "type": "sync", } secret := "bb481e0c-9895-44d8-b184-6b9707a60ec7" requestBody2 := map[string]interface{}{ "taxNo": config.TerminalCode, "taxUserName": "", "sellerTaxNo": config.TerminalCode, "redConfirmUuid": uuid, "redConfirmNo": no, "confirmType": "01", } // 生成签名 sign, err := signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return 0, err.Error() } params["sign"] = sign if len(fapiao_access_token) > 0 { //token 存在则进行签名处理 // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return 0, err.Error() } // 解析 JSON 响应 var result bwfapiao.RedOperaResponse err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return 0, err2.Error() } // 判断接口是否成功调用 if result.Success { return 1, "" } else { return 0, "" } } else { //token 不存在,则进行获取token的操作 tokenResp, _ := GetAccessToken("https://openapi.baiwang.com/router/rest", "b033l65qAA", "cc73223bd14a4064bb0fe9ba642da58f", "10059482", "bb481e0c-9895-44d8-b184-6b9707a60ec7", "admin_ffzyx16zmybx4", "") if len(tokenResp.Response.AccessToken) > 0 { //token请求成功,则将token和有效时间存储进redis, redisClient.Set("fapiao_access_token", tokenResp.Response.AccessToken, time.Duration(tokenResp.Response.ExpiresIn)*time.Second) params["token"] = tokenResp.Response.AccessToken // 生成签名 sign, err = signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return 0, err.Error() } params["sign"] = sign // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return 0, err.Error() } // 解析 JSON 响应 var result bwfapiao.RedOperaResponse err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return 0, err2.Error() } // 判断接口是否成功调用 if result.Success { return 1, "" } else { return 0, result.ErrorResponse.Message + "\n" + result.ErrorResponse.SubMessage } } else { //获取token失败 return 0, "获取token失败" } } } // 百望云发票查询开票信息版本 func QueryBWInvoiceInfoTwo(config models.FapiaoConfig, orders models.HisFaPiaoOrder) { redisClient := service.RedisClient() defer redisClient.Close() fapiao_access_token, _ := redisClient.Get("fapiao_access_token").Result() // 示例数据 params := map[string]string{ "method": "baiwang.output.einvoice.query", "version": "6.0", "appKey": "10059482", "format": "json", "timestamp": strconv.FormatInt(time.Now().Unix(), 10), "token": fapiao_access_token, "type": "sync", } secret := "bb481e0c-9895-44d8-b184-6b9707a60ec7" requestBody2 := map[string]interface{}{ "taxNo": config.TerminalCode, "queryAll": false, } subData := make(map[string]interface{}) subData["queryAll"] = "true" subData["serialNo"] = orders.OrderSn subData["invoiceCode"] = "" subData["invoiceNo"] = orders.TicketSn subData["invoiceTypeCode"] = "" subData["invoiceTerminalCode"] = "" subData["sourceMark"] = "" subData["invoiceSpecialMark"] = "" subData["buyerTaxNo"] = "" subData["buyerName"] = "" subData["printStatus"] = "" subData["invoiceStatus"] = "00" subData["invoiceType"] = "" subData["invoiceStartDate"] = "" subData["expressNo"] = "" subData["expressNo"] = "" subData["contractNo"] = "" subData["orderNo"] = "" requestBody2["data"] = subData // 生成签名 sign, err := signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return } params["sign"] = sign if len(fapiao_access_token) > 0 { //token 存在则进行签名处理 // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return } // 解析 JSON 响应 var result bwfapiao.UnifiedLoginResponse err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return } // 判断接口是否成功调用 if result.Success { } else { } } else { //token 不存在,则进行获取token的操作 tokenResp, _ := GetAccessToken("https://openapi.baiwang.com/router/rest", "b033l65qAA", "cc73223bd14a4064bb0fe9ba642da58f", "10059482", "bb481e0c-9895-44d8-b184-6b9707a60ec7", "admin_ffzyx16zmybx4", "") if len(tokenResp.Response.AccessToken) > 0 { //token请求成功,则将token和有效时间存储进redis, redisClient.Set("fapiao_access_token", tokenResp.Response.AccessToken, time.Duration(tokenResp.Response.ExpiresIn)*time.Second) params["token"] = tokenResp.Response.AccessToken // 生成签名 sign, err = signTopRequestTwo(params, secret, requestBody2) if err != nil { fmt.Println("Error:", err) return } params["sign"] = sign // 调用 API response, err := callApiTwo("https://openapi.baiwang.com/router/rest", params, requestBody2) if err != nil { fmt.Println("接口调用失败:", err) return } // 解析 JSON 响应 var result bwfapiao.UnifiedLoginResponse err2 := json.Unmarshal([]byte(response), &result) if err2 != nil { fmt.Println("解析响应失败:", err2) return } // 判断接口是否成功调用 if result.Success { } else { } } else { //获取token失败 } } } func callApiTwo(url string, params map[string]string, body map[string]interface{}) (string, error) { // 拼接 URL 查询参数 queryParams := make([]string, 0, len(params)) for k, v := range params { queryParams = append(queryParams, fmt.Sprintf("%s=%s", k, v)) } fullUrl := fmt.Sprintf("%s?%s", url, strings.Join(queryParams, "&")) // 序列化请求体 bodyBytes, err := json.Marshal(body) if err != nil { return "", errors.New("请求体序列化失败: " + err.Error()) } // 创建 HTTP 请求 req, err := http.NewRequest("POST", fullUrl, bytes.NewBuffer(bodyBytes)) if err != nil { return "", errors.New("创建请求失败: " + err.Error()) } req.Header.Set("Content-Type", "application/json") // 发送请求 client := &http.Client{} resp, err := client.Do(req) if err != nil { return "", errors.New("发送请求失败: " + err.Error()) } defer resp.Body.Close() // 读取响应 respBytes, err := ioutil.ReadAll(resp.Body) if err != nil { return "", errors.New("读取响应失败: " + err.Error()) } fmt.Println(string(respBytes)) saveLog(string(respBytes), string(bodyBytes), "开票日志", "开票日志", "百望云") return string(respBytes), nil } // AuthResponse 结构体,用于解析返回的 JSON 数据 type AuthResponse struct { Response struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` ExpiresIn int `json:"expires_in"` Scope string `json:"scope"` } `json:"response"` } // GetAccessToken 获取登录授权的 access_token func GetAccessToken(apiURL, plainPassword, salt, clientID, clientSecret, username, orgAuthCode string) (AuthResponse, error) { // 当前时间戳(毫秒级) timestamp := fmt.Sprintf("%d", time.Now().UnixMilli()) // 密码加密:MD5 + SHA1 encryptedPassword := md5AndSha1(plainPassword + salt) //"version": "6.0", // "timestamp": timestamp, //"method": "baiwang.oauth.token", // "grant_type": "password", //"client_id": clientID, // 构造请求体 authReq := map[string]interface{}{ "client_secret": clientSecret, "username": username, "password": encryptedPassword, "orgAuthCode": orgAuthCode, } var aa AuthResponse // 转换为 JSON reqBody, err := json.Marshal(authReq) if err != nil { return aa, fmt.Errorf("failed to marshal request: %v", err) } // 发送 POST 请求 resp, err := http.Post(apiURL+"?"+"version="+"6.0"+"&method="+"baiwang.oauth.token"+"&grant_type="+"password"+"&client_id="+clientID+"×tamp="+timestamp, "application/json", bytes.NewBuffer(reqBody)) if err != nil { return aa, fmt.Errorf("failed to make request: %v", err) } defer resp.Body.Close() // 读取响应 body, err := ioutil.ReadAll(resp.Body) if err != nil { return aa, fmt.Errorf("failed to read response: %v", err) } // 检查响应状态码 if resp.StatusCode != http.StatusOK { return aa, fmt.Errorf("request failed with status: %d, response: %s", resp.StatusCode, string(body)) } // 解析响应 JSON var authResp AuthResponse err = json.Unmarshal(body, &authResp) if err != nil { return aa, fmt.Errorf("failed to parse response: %v", err) } fmt.Println(authReq) fmt.Println(apiURL + "?" + "version=" + "6.0" + "&method=" + "baiwang.oauth.token" + "&grant_type=" + "password" + "&client_id=" + clientID + "×tamp=" + timestamp) fmt.Println(string(body)) fmt.Println(authResp) aa = authResp fmt.Println(aa) // 返回 Access Token return aa, nil } // md5AndSha1: MD5 + SHA-1 加密函数 func md5AndSha1(input string) string { return sha1Hash(md5Hash(input)) } // md5Hash: MD5 加密 func md5Hash(input string) string { hash := md5.New() hash.Write([]byte(input)) return hex.EncodeToString(hash.Sum(nil)) } // sha1Hash: SHA-1 加密 func sha1Hash(input string) string { hash := sha1.New() hash.Write([]byte(input)) return hex.EncodeToString(hash.Sum(nil)) } func (c *FapiaoApiController) QueryFaPiao() { id, _ := c.GetInt64("id") oc, _ := service.GetFaPiaoOrderById(id) sdk := invoice.NewSdk(common.HMAC_SHA256, "5058f0defd12047ee2a7", "51440fbee667ea9a53aaa68c9c408367", "", "") var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) routerAddress2, postData2 := fapiao.Query(config.SellerTaxpayerNum, oc.OrderSn, "") r3, err2 := sdk.HttpPost("https://apigw.goldentec.com", routerAddress2, postData2) fmt.Println("query") fmt.Println(string(r3)) if err2 != nil { fmt.Println(err2) } else { var resp3 QueryFaPiaoResultResponse // 将 byte 切片转换为结构体 json.Unmarshal(r3, &resp3) if resp3.Code == 0 { //var fapiaos models.HisFaPiaoOrder if resp3.Data.Status == 3 { // 异步调用查询操作,不阻塞主程序 oc.TicketSn = resp3.Data.TicketSn oc.TicketDate = resp3.Data.TicketDate oc.AmountWithTax = resp3.Data.AmountWithoutTax oc.AmountWithoutTax = resp3.Data.AmountWithoutTax oc.FapiaoStatus = "2" oc.TaxAmount = resp3.Data.TaxAmount oc.IsRedWashed = strconv.FormatInt(int64(resp3.Data.IsRedWashed), 10) oc.PdfUrl = resp3.Data.PdfUrl oc.OfdUrl = resp3.Data.OfdUrl oc.XmlUrl = resp3.Data.XmlUrl service.SaveFaPiaoOrder(&oc) ids := strings.Split(oc.OrderIds, ",") service.UpdateFaPiaoNumber(resp3.Data.TicketSn, ids) //同步发票号码 c.ServeSuccessJSON(map[string]interface{}{ "msg": "同步成功", }) } else if resp3.Data.Status == 1 { oc.FapiaoStatus = "1" oc.TicketSn = "" service.SaveFaPiaoOrder(&oc) c.ServeSuccessJSON(map[string]interface{}{ "msg": "同步成功", }) //service.UpdateFaPiaoNumber(resp3.Data.TicketSn, ids) //同步发票号码 } else if resp3.Data.Status == 2 { oc.FapiaoStatus = "3" oc.TicketSn = "" oc.Message = resp3.Data.Message service.SaveFaPiaoOrder(&oc) c.ServeSuccessJSON(map[string]interface{}{ "msg": "同步成功", }) } else { oc.FapiaoStatus = "3" oc.TicketSn = "" oc.Message = resp3.Data.Message service.SaveFaPiaoOrder(&oc) c.ServeSuccessJSON(map[string]interface{}{ "msg": "同步成功", }) } } else { //错误处理 c.ServeSuccessJSON(map[string]interface{}{ "msg": "查询失败" + resp3.Message, }) } //if resp3.Code == 0 { // // 异步调用查询操作,不阻塞主程序 // oc.TicketSn = resp3.Data.TicketSn // oc.TicketDate = resp3.Data.TicketDate // oc.AmountWithTax = resp3.Data.AmountWithoutTax // oc.AmountWithoutTax = resp3.Data.AmountWithoutTax // oc.FapiaoStatus = "2" // oc.TaxAmount = resp3.Data.TaxAmount // oc.IsRedWashed = strconv.FormatInt(int64(resp3.Data.IsRedWashed), 10) // oc.PdfUrl = resp3.Data.PdfUrl // oc.OfdUrl = resp3.Data.OfdUrl // oc.XmlUrl = resp3.Data.XmlUrl // service.SaveFaPiaoOrder(oc) // ids := strings.Split(oc.OrderIds, ",") // service.UpdateFaPiaoNumber(resp3.Data.TicketSn, ids) //同步发票号码 // c.ServeSuccessJSON(map[string]interface{}{ // "msg": "查询成功", // }) //} else { // //错误处理 // c.ServeSuccessJSON(map[string]interface{}{ // "msg": "查询失败" + resp3.Message, // }) //} } } func (c *HisApiController) GetNewFaPiaoData() { order_ids := c.GetString("order_ids") patient_id, _ := c.GetInt64("patient_id") //number := c.GetString("number") adminUser := c.GetAdminUserInfo() orders := strings.Split(order_ids, ",") patient, _ := service.GetFaPiaoPatientByID(adminUser.CurrentOrgId, patient_id) var bedCostTotal float64 = 0 //床位总费 var bedCostSelfTotal float64 = 0 //床位自费 var bedCostPartSelfTotal float64 = 0 //床位部分项目自费 var operationCostTotal float64 = 0 //手术费 var operationCostSelfTotal float64 = 0 //手术费 var operationCostPartSelfTotal float64 = 0 //手术费 var otherCostTotal float64 = 0 //其他费用 var otherCostSelfTotal float64 = 0 //其他费用 var otherCostPartSelfTotal float64 = 0 //其他费用 var materialCostTotal float64 = 0 //材料费 var materialCostSelfTotal float64 = 0 //材料费 var materialCostPartSelfTotal float64 = 0 //材料费 var westernMedicineCostTotal float64 = 0 //西药费 var westernMedicineCostSelfTotal float64 = 0 //西药费 var westernMedicineCostPartSelfTotal float64 = 0 //西药费 var chineseTraditionalMedicineCostTotal float64 = 0 //中成药 var chineseTraditionalMedicineCostSelfTotal float64 = 0 //中成药 var chineseTraditionalMedicineCostPartSelfTotal float64 = 0 //中成药 var checkCostTotal float64 = 0 //检查费 var checkCostSelfTotal float64 = 0 //检查费 var checkCostPartSelfTotal float64 = 0 //检查费 var hiliCostTotal float64 = 0 //护理费 var hiliCostSelfTotal float64 = 0 //护理费 //var hiliCostPartSelfTotal float64 = 0 //护理费 var laboratoryCostTotal float64 = 0 //化验费 var laboratoryCostSelfTotal float64 = 0 //化验费 var laboratoryCostPartSelfTotal float64 = 0 //化验费 var treatCostTotal float64 = 0 //治疗费用 var treatCostSelfTotal float64 = 0 //治疗费用 var treatCostPartSelfTotal float64 = 0 //治疗费用 var zhenChaCostTotal float64 = 0 //其他费用 var zhenChaCostSelfTotal float64 = 0 //其他费用 var zhenChaCostPartSelfTotal float64 = 0 //其他费用 decimal.DivisionPrecision = 2 var MedfeeSumamt float64 = 0 //治疗费用 var PsnCashPay float64 = 0 //治疗费用 var FundPaySumamt float64 = 0 //治疗费用 var HifpPay float64 = 0 //治疗费用 var MafPay float64 = 0 //治疗费用 var AcctPay float64 = 0 //治疗费用 for _, item := range orders { var new_order models.HisOrder order_id_num, _ := strconv.ParseInt(item, 10, 64) new_order, _ = service.GetHisOrderByID(order_id_num) MedfeeSumamt, _ = decimal.NewFromFloat(MedfeeSumamt).Add(decimal.NewFromFloat(new_order.MedfeeSumamt)).Float64() PsnCashPay, _ = decimal.NewFromFloat(PsnCashPay).Add(decimal.NewFromFloat(new_order.PsnCashPay)).Float64() FundPaySumamt, _ = decimal.NewFromFloat(FundPaySumamt).Add(decimal.NewFromFloat(new_order.FundPaySumamt)).Float64() HifpPay, _ = decimal.NewFromFloat(HifpPay).Add(decimal.NewFromFloat(new_order.HifpPay)).Float64() MafPay, _ = decimal.NewFromFloat(MafPay).Add(decimal.NewFromFloat(new_order.MafPay)).Float64() AcctPay, _ = decimal.NewFromFloat(AcctPay).Add(decimal.NewFromFloat(new_order.AcctPay)).Float64() orderInfos_two, _ := service.GetHisOrderDetailByNumber(new_order.Number, adminUser.CurrentOrgId) var balanceAccountsType int64 if new_order.IsMedicineInsurance == 1 { balanceAccountsType = 1 } else { balanceAccountsType = 2 } if balanceAccountsType == 2 { //orderInfos_two, _ := service.GetHisOrderDetailByNumber(order.Number, adminUser.CurrentOrgId) for _, item := range orderInfos_two { item.FulamtOwnpayAmt = item.DetItemFeeSumamt if item.HisDoctorAdviceInfo.ID > 0 && item.HisPrescriptionProject.ID == 0 { //药品 item.MedChrgitmType = "09" } if item.HisPrescriptionProject.ID > 0 && item.HisDoctorAdviceInfo.ID == 0 { if item.HisPrescriptionProject.Type == 2 { switch item.HisPrescriptionProject.VMHisProject.CostClassify { case 1: item.MedChrgitmType = "14" break case 2: item.MedChrgitmType = "05" break case 3: item.MedChrgitmType = "04" break case 4: item.MedChrgitmType = "03" break case 5: item.MedChrgitmType = "08" break case 6: item.MedChrgitmType = "14" break case 7: item.MedChrgitmType = "14" break case 8: item.MedChrgitmType = "03" break case 9: item.MedChrgitmType = "14" break } } else if item.HisPrescriptionProject.Type == 3 { item.MedChrgitmType = "08" } } } for _, item := range orderInfos_two { fmt.Println(item.MedChrgitmType) if item.MedChrgitmType == "07" { //床位费 hiliCostTotal, _ = decimal.NewFromFloat(hiliCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() hiliCostSelfTotal = hiliCostTotal } if item.MedChrgitmType == "01" { //床位费 bedCostTotal, _ = decimal.NewFromFloat(bedCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() bedCostSelfTotal = bedCostTotal } if item.MedChrgitmType == "02" { //诊察费 zhenChaCostTotal, _ = decimal.NewFromFloat(zhenChaCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() zhenChaCostSelfTotal = zhenChaCostTotal } if item.MedChrgitmType == "03" { //检查费 checkCostTotal, _ = decimal.NewFromFloat(checkCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() checkCostSelfTotal = checkCostTotal } if item.MedChrgitmType == "04" { //化验费 laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() laboratoryCostSelfTotal = laboratoryCostTotal } if item.MedChrgitmType == "05" || item.MedChrgitmType == "14" || item.MedChrgitmType == "201" { //治疗费 treatCostTotal, _ = decimal.NewFromFloat(treatCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() treatCostSelfTotal = treatCostTotal } if item.MedChrgitmType == "06" { //手术费 treatCostTotal, _ = decimal.NewFromFloat(operationCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() operationCostSelfTotal = treatCostTotal } if item.MedChrgitmType == "08" || item.MedChrgitmType == "1402" || item.MedChrgitmType == "1403" || item.MedChrgitmType == "1401" || item.MedChrgitmType == "301" { //材料费 materialCostTotal, _ = decimal.NewFromFloat(materialCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() materialCostSelfTotal = materialCostTotal } if item.MedChrgitmType == "09" || item.MedChrgitmType == "101" { //西药费 westernMedicineCostTotal, _ = decimal.NewFromFloat(westernMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() westernMedicineCostSelfTotal = westernMedicineCostTotal } if item.MedChrgitmType == "11" { //中成费 chineseTraditionalMedicineCostTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() chineseTraditionalMedicineCostSelfTotal = chineseTraditionalMedicineCostTotal } if c.GetAdminUserInfo().CurrentOrgId == 10106 { if item.MedChrgitmType == "0" || item.MedChrgitmType == "12" || item.MedChrgitmType == "02" { //其他费 otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() otherCostSelfTotal = otherCostTotal } } else { if item.MedChrgitmType == "0" || item.MedChrgitmType == "12" { //其他费 otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() otherCostSelfTotal = otherCostTotal } } } } else { for _, item := range orderInfos_two { if item.MedChrgitmType == "01" { //床位费 bedCostTotal, _ = decimal.NewFromFloat(bedCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //bedCostSelfTotal, _ = decimal.NewFromFloat(bedCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //bedCostPartSelfTotal, _ = decimal.NewFromFloat(bedCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if item.MedChrgitmType == "02" { //诊察费 zhenChaCostTotal, _ = decimal.NewFromFloat(zhenChaCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //zhenChaCostSelfTotal, _ = decimal.NewFromFloat(zhenChaCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //zhenChaCostPartSelfTotal, _ = decimal.NewFromFloat(zhenChaCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if c.GetAdminUserInfo().CurrentOrgId == 10188 || c.GetAdminUserInfo().CurrentOrgId == 10217 { if item.MedChrgitmType == "03" { //检查费 laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //laboratoryCostSelfTotal, _ = decimal.NewFromFloat(laboratoryCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //laboratoryCostPartSelfTotal, _ = decimal.NewFromFloat(laboratoryCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } } else { if item.MedChrgitmType == "03" { //检查费 checkCostTotal, _ = decimal.NewFromFloat(checkCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //checkCostSelfTotal, _ = decimal.NewFromFloat(checkCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //checkCostPartSelfTotal, _ = decimal.NewFromFloat(checkCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } } if item.MedChrgitmType == "04" { //化验费 laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //laboratoryCostSelfTotal, _ = decimal.NewFromFloat(laboratoryCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //laboratoryCostPartSelfTotal, _ = decimal.NewFromFloat(laboratoryCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if item.MedChrgitmType == "05" || item.MedChrgitmType == "14" || item.MedChrgitmType == "201" { //治疗费 treatCostTotal, _ = decimal.NewFromFloat(treatCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //treatCostSelfTotal, _ = decimal.NewFromFloat(treatCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //treatCostPartSelfTotal, _ = decimal.NewFromFloat(treatCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if item.MedChrgitmType == "06" { //手术费 operationCostTotal, _ = decimal.NewFromFloat(operationCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //operationCostSelfTotal, _ = decimal.NewFromFloat(operationCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //operationCostPartSelfTotal, _ = decimal.NewFromFloat(operationCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if item.MedChrgitmType == "08" || item.MedChrgitmType == "1401" || item.MedChrgitmType == "1402" || item.MedChrgitmType == "1403" || item.MedChrgitmType == "301" { //材料费 materialCostTotal, _ = decimal.NewFromFloat(materialCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //materialCostSelfTotal, _ = decimal.NewFromFloat(materialCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //materialCostPartSelfTotal, _ = decimal.NewFromFloat(materialCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if item.MedChrgitmType == "07" { //护理 hiliCostTotal, _ = decimal.NewFromFloat(hiliCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //hiliCostSelfTotal, _ = decimal.NewFromFloat(hiliCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //hiliCostPartSelfTotal, _ = decimal.NewFromFloat(hiliCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if item.MedChrgitmType == "09" || item.MedChrgitmType == "101" { //西药费 westernMedicineCostTotal, _ = decimal.NewFromFloat(westernMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //westernMedicineCostSelfTotal, _ = decimal.NewFromFloat(westernMedicineCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //westernMedicineCostPartSelfTotal, _ = decimal.NewFromFloat(westernMedicineCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if item.MedChrgitmType == "11" { //中成费 chineseTraditionalMedicineCostTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //chineseTraditionalMedicineCostSelfTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //chineseTraditionalMedicineCostPartSelfTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } if item.MedChrgitmType == "0" || item.MedChrgitmType == "12" { //其他费 otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() //otherCostSelfTotal, _ = decimal.NewFromFloat(otherCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64() //otherCostPartSelfTotal, _ = decimal.NewFromFloat(otherCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64() } } } } //pre_pay_money := service.GetUserMoney(order.PatientId, adminUser.CurrentOrgId) //sum, _ := service.RefundListSum(adminUser.CurrentOrgId, startRecordDateTime, endRecordDateTime, order.PatientId) admin, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, adminUser.AdminUser.Id) charge_admin, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, adminUser.AdminUser.Id) c.ServeSuccessJSON(map[string]interface{}{ "charge_admin_name": charge_admin.UserName, "patient": patient, "admin_user_name": admin.UserName, //收款员 "bedCostTotal": bedCostTotal, "bedCostSelfTotal": bedCostSelfTotal, "bedCostPartSelfTotal": bedCostPartSelfTotal, "operationCostTotal": operationCostTotal, "operationCostSelfTotal": operationCostSelfTotal, "operationCostPartSelfTotal": operationCostPartSelfTotal, "otherCostTotal": otherCostTotal, "otherCostSelfTotal": otherCostSelfTotal, "otherCostPartSelfTotal": otherCostPartSelfTotal, "materialCostTotal": materialCostTotal, "materialCostSelfTotal": materialCostSelfTotal, "materialCostPartSelfTotal": materialCostPartSelfTotal, "westernMedicineCostTotal": westernMedicineCostTotal, "westernMedicineCostSelfTotal": westernMedicineCostSelfTotal, "westernMedicineCostPartSelfTotal": westernMedicineCostPartSelfTotal, "chineseTraditionalMedicineCostTotal": chineseTraditionalMedicineCostTotal, "chineseTraditionalMedicineCostSelfTotal": chineseTraditionalMedicineCostSelfTotal, "chineseTraditionalMedicineCostPartSelfTotal": chineseTraditionalMedicineCostPartSelfTotal, "checkCostTotal": checkCostTotal, "checkCostSelfTotal": checkCostSelfTotal, "checkCostPartSelfTotal": checkCostPartSelfTotal, "laboratoryCostTotal": laboratoryCostTotal, "laboratoryCostSelfTotal": laboratoryCostSelfTotal, "laboratoryCostPartSelfTotal": laboratoryCostPartSelfTotal, "treatCostTotal": treatCostTotal, "treatCostSelfTotal": treatCostSelfTotal, "treatCostPartSelfTotal": treatCostPartSelfTotal, "zhenChaCostTotal": zhenChaCostTotal, "zhenChaCostSelfTotal": zhenChaCostSelfTotal, "zhenChaCostPartSelfTotal": zhenChaCostPartSelfTotal, "hiliCostTotal": hiliCostTotal, "hiliCostSelfTotal": hiliCostSelfTotal, "medfee_sumamt": MedfeeSumamt, "fund_pay_sumamt": FundPaySumamt, "hifp_pay": HifpPay, "maf_pay": MafPay, "acct_pay": AcctPay, "psn_cash_pay": PsnCashPay, }) } type FapiaoApiController struct { BaseAuthAPIController } type InvoiceRequest struct { SellerName string `json:"seller_name,omitempty"` // 销方名称 SellerTaxpayerNum string `json:"seller_taxpayer_num"` // 销方纳税人识别号 SellerAddress string `json:"seller_address"` // 销方地址 SellerTel string `json:"seller_tel"` // 销方电话 SellerBankName string `json:"seller_bank_name"` // 销方银行名称 SellerBankAccount string `json:"seller_bank_account"` // 销方银行账号 TitleType int `json:"title_type"` // 抬头类型:1 个人、政府事业单位;2 企业 BuyerTitle string `json:"buyer_title"` // 购方名称 BuyerTaxpayerNum string `json:"buyer_taxpayer_num,omitempty"` // 购方纳税人识别号 BuyerAddress string `json:"buyer_address,omitempty"` // 购方地址 BuyerPhone string `json:"buyer_phone,omitempty"` // 购方电话 BuyerBankName string `json:"buyer_bank_name,omitempty"` // 购方银行名称 BuyerBankAccount string `json:"buyer_bank_account,omitempty"` // 购方银行账号 BuyerEmail string `json:"buyer_email,omitempty"` // 收票人邮箱 OrderID string `json:"order_id"` // 商户订单号 InvoiceTypeCode string `json:"invoice_type_code,omitempty"` // 开具发票类型 CallbackURL string `json:"callback_url"` // 发票结果回传地址 Drawer string `json:"drawer"` // 开票人姓名 Payee string `json:"payee,omitempty"` // 收款人姓名 Checker string `json:"checker,omitempty"` // 复核人姓名 TerminalCode string `json:"terminal_code"` // 税盘号 UserOpenID string `json:"user_openid,omitempty"` // 商家用户标识 SpecialInvoiceKind string `json:"special_invoice_kind,omitempty"` // 特殊票种标识 AmountHasTax string `json:"amount_has_tax"` // 含税总金额 TaxAmount string `json:"tax_amount"` // 总税额 AmountWithoutTax string `json:"amount_without_tax"` // 不含税总金额 Remark string `json:"remark,omitempty"` // 备注 StoreNo string `json:"store_no,omitempty"` // 门店编码 Template int `json:"template"` // 发票模板 Info *InvoiceInfo `json:"info,omitempty"` // 冠名票信息 TaxpayerConfirmation *TaxpayerConfirmation `json:"taxpayer_confirmation,omitempty"` // 纳税人确认信息 SpecificBusinessCode string `json:"specific_business_code,omitempty"` // 特定业务代码 RealStaticRent *RealStaticRent `json:"real_static_rent,omitempty"` // 不动产经营租赁信息 PassengerTransport []PassengerTransport `json:"passenger_transport,omitempty"` // 旅客运输信息 GoodsTransport []GoodsTransport `json:"goods_transport,omitempty"` // 货物运输信息 AgriculturalPurchase *AgriculturalPurchase `json:"agricultural_purchase,omitempty"` // 农产品收购信息 BuildingService *BuildingService `json:"building_service,omitempty"` // 建筑服务信息 RealStaticSales *RealStaticSales `json:"real_static_sales,omitempty"` // 不动产销售信息 TractorCombine *TractorCombine `json:"tractor_combine,omitempty"` // 拖拉机与联合收割机信息 UsedCarService *UsedCarService `json:"used_car_service,omitempty"` // 二手车服务信息 UsedCarSell *UsedCarSell `json:"used_car_sell,omitempty"` // 二手车销售信息 DeductionService *DeductionService `json:"deduction_service,omitempty"` // 差额征税信息 Items []Item `json:"items"` // 项目商品明细 } type InvoiceInfo struct { UseDate string `json:"use_date,omitempty"` // 入园日期 TicketName string `json:"ticket_name,omitempty"` // 票据名称 } type TaxpayerConfirmation struct { RenewableResourceRecyclingFlag int `json:"renewable_resource_recycling_flag,omitempty"` // 再生资源回收单位标志 DrawWithNoBuyerFlag int `json:"draw_with_nobuyer_flag,omitempty"` // 无购买方纳税人信息继续开票标志 NotDutyFreeReason string `json:"not_dutyfree_reason,omitempty"` // 放弃享受减按1%征收率原因 } type RealStaticRent struct { PropertyNum string `json:"property_num"` // 房屋产权证号 Location string `json:"location"` // 不动产地址 (省市区县) AddressDetail string `json:"address_detail"` // 不动产详细地址 RentBeginDate string `json:"rent_begin_date"` // 租赁期起 RentEndDate string `json:"rent_end_date"` // 租赁期止 IntercityFlag string `json:"intercity_flag"` // 跨地市标志 UnitOfArea int `json:"unit_of_area"` // 面积单位 } type PassengerTransport struct { Traveler string `json:"traveler,omitempty"` // 出行人 IDType int `json:"id_type,omitempty"` // 证件类型 IDNumber string `json:"id_number,omitempty"` // 证件号码 TravelDate string `json:"travel_date,omitempty"` // 出行日期 DeparturePlace string `json:"departure_place,omitempty"` // 出发地 DestinationPlace string `json:"destination_palce,omitempty"` // 到达地 VehicleType int `json:"vehicle_type,omitempty"` // 交通工具类型 Level string `json:"level,omitempty"` // 等级 } type GoodsTransport struct { TransportNumber string `json:"transport_number,omitempty"` // 运输工具号牌 TransportKind string `json:"transport_kind,omitempty"` // 运输工具种类 GoodsName string `json:"goods_name,omitempty"` // 货物名称 DeparturePlace string `json:"departure_place,omitempty"` // 出发地 DestinationPlace string `json:"destination_place,omitempty"` // 到达地 } type AgriculturalPurchase struct { IDType string `json:"id_type,omitempty"` // 证件类型 } type BuildingService struct { Site string `json:"site"` // 建筑服务发生地 DetailSite string `json:"detail_site,omitempty"` // 详细地址 BuildingProject string `json:"building_project"` // 建筑项目名称 CrossSign string `json:"cross_sign"` // 跨地市标志 } type RealStaticSales struct { PropertyNum string `json:"property_num,omitempty"` // 房屋产权证书号 Location string `json:"location"` // 不动产地址 AddressDetail string `json:"address_detail,omitempty"` // 不动产详细地址 CrossSign string `json:"cross_sign"` // 跨市标志 UnitOfArea int `json:"unit_of_area"` // 面积单位 OnlineContractCode string `json:"online_contract_code,omitempty"` // 不动产单元代码/网签合同编码 } type TractorCombine struct { ChassisNumber string `json:"chassis_number,omitempty"` // 底盘号或机架号 EngineNumber string `json:"engine_number"` // 发动机号 IsRegister string `json:"is_register,omitempty"` // 是否用于拖拉机和联合收割机登记 } type UsedCarService struct { TicketSN string `json:"ticket_sn"` // 发票号码 PaperTicketCode string `json:"paper_ticket_code"` // 纸票发票代码 PaperTicketSN string `json:"paper_ticket_sn"` // 纸票发票号码 } type UsedCarSell struct { FrameNumber string `json:"frame_number"` // 车架号码 LicensePlateNumber string `json:"license_plate_number"` // 车牌号 BrandModel string `json:"brand_model"` // 厂牌型号 RegistrationCertificate string `json:"registration_certificate"` // 登记证号 TransferOfficeName string `json:"transfer_office_name"` // 转入地车辆管理所名称 NatureOfEnterprise string `json:"nature_of_enterprise"` // 企业性质 } type DeductionService struct { TaxDiffServiceFlag int `json:"tax_diff_service_flag,omitempty"` // 差额征税标识 TaxableServiceName string `json:"taxable_service_name,omitempty"` // 差额征税项目名称 } type Item struct { ItemName string `json:"item_name"` // 商品名称 ItemSpec string `json:"item_spec,omitempty"` // 商品规格 ItemUnit string `json:"item_unit"` // 商品单位 ItemQuantity float64 `json:"item_quantity"` // 商品数量 ItemPrice float64 `json:"item_price"` // 商品单价 ItemAmount float64 `json:"item_amount"` // 商品金额 ItemTaxRate float64 `json:"item_tax_rate"` // 商品税率 ItemTaxAmount float64 `json:"item_tax_amount"` // 商品税额 RowType int `json:"row_type"` // 行性质标志 } func (c *FapiaoApiController) GetFaPiaoList() { page, _ := c.GetInt64("page", -1) limit, _ := c.GetInt64("limit", -1) start_time := c.GetString("start_time") end_time := c.GetString("end_time") keywords := c.GetString("keywords") timeLayout := "2006-01-02" loc, _ := time.LoadLocation("Local") var startTime int64 if len(start_time) > 0 { theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc) if err != nil { //fmt.Println(err) c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong) return } startTime = theTime.Unix() } var endTime int64 if len(end_time) > 0 { theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc) if err != nil { utils.ErrorLog(err.Error()) c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong) return } endTime = theTime.Unix() } adminUser := c.GetAdminUserInfo() org_id := adminUser.CurrentOrgId order, err, total := service.GetFaPiaoList(org_id, page, limit, startTime, endTime, keywords) if err == nil { c.ServeSuccessJSON(map[string]interface{}{ "fapiao_record": order, "total": total, }) } else { c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } } func (c *FapiaoApiController) GetOrderFaPiaoList() { page, _ := c.GetInt64("page", -1) limit, _ := c.GetInt64("limit", -1) start_time := c.GetString("start_time") end_time := c.GetString("end_time") is_open_fapiao, _ := c.GetInt64("is_open_fapiao", 0) sort_type, _ := c.GetInt64("sort_type", 0) keywords := c.GetString("keywords") patient_id, _ := c.GetInt64("patient_id", 0) timeLayout := "2006-01-02" loc, _ := time.LoadLocation("Local") var startTime int64 if len(start_time) > 0 { theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc) if err != nil { //fmt.Println(err) c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong) return } startTime = theTime.Unix() } var endTime int64 if len(end_time) > 0 { theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc) if err != nil { utils.ErrorLog(err.Error()) c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong) return } endTime = theTime.Unix() } adminUser := c.GetAdminUserInfo() org_id := adminUser.CurrentOrgId order, err, total := service.GetFaPiaoSettleList(org_id, page, limit, startTime, endTime, sort_type, start_time, end_time, is_open_fapiao, patient_id, keywords) if err == nil { c.ServeSuccessJSON(map[string]interface{}{ "order": order, "total": total, }) } else { c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException) return } } func (c *FapiaoApiController) GetLoginUploadCode() { sdk := invoice.NewSdk(common.HMAC_SHA256, "5058f0defd12047ee2a7", "51440fbee667ea9a53aaa68c9c408367", "", "test") var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) routerAddress, postData := fapiao.GetSMSCode(config) //发票开具 fmt.Println(routerAddress) fmt.Println(postData) r, err := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData) if err != nil { fmt.Println(err) } else { var resp SmsCode // 将 byte 切片转换为结构体 json.Unmarshal(r, &resp) if resp.Code == 0 { c.ServeSuccessJSON(map[string]interface{}{ "msg": resp.Message, }) } } } type SmsCode struct { Code int `json:"code"` Message string `json:"message"` } func (c *FapiaoApiController) Login() { code := c.GetString("code") var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) sdk := invoice.NewSdk(common.HMAC_SHA256, "5058f0defd12047ee2a7", "51440fbee667ea9a53aaa68c9c408367", "", "test") routerAddress, postData := fapiao.Login(code, config) //发票开具 r, err := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData) if err != nil { fmt.Println(err) } else { var resp SmsCode // 将 byte 切片转换为结构体 json.Unmarshal(r, &resp) if resp.Code == 0 { c.ServeSuccessJSON(map[string]interface{}{ "msg": resp.Message, }) } } } func (c *FapiaoApiController) GetQRCode() { sdk := invoice.NewSdk(common.HMAC_SHA256, "5058f0defd12047ee2a7", "51440fbee667ea9a53aaa68c9c408367", "", "test") var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) routerAddress, postData := fapiao.GetQRCode(config) //发票开具 r, err := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData) if err != nil { fmt.Println(err) } else { var resp QRAuth // 将 byte 切片转换为结构体 err := json.Unmarshal(r, &resp) fmt.Println(resp) if err != nil { fmt.Println("Error unmarshalling:", err) } else { if resp.Code == 0 { decodedBytes, _ := base64.StdEncoding.DecodeString(resp.Data.QrCode) if len(resp.Data.AuthId) == 0 { //还没进行授权,则获取二维码信息 c.ServeSuccessJSON(map[string]interface{}{ "cus_status": 1, "qr_code": string(decodedBytes), }) } else { status := GetQRStatus(c.GetAdminUserInfo().CurrentOrgId, resp.Data.AuthId) if status == "UNDEFINE" { c.ServeSuccessJSON(map[string]interface{}{ "cus_status": -1, "msg": "未定义", }) } else if status == "UNHANDLED" { c.ServeSuccessJSON(map[string]interface{}{ "cus_status": 1, "qr_code": string(decodedBytes), }) } else if status == "REAL_AUTH_SUCCESS" { c.ServeSuccessJSON(map[string]interface{}{ "cus_status": 2, "msg": "已经实名认证成功", }) } else if status == "REFRESH" { c.ServeSuccessJSON(map[string]interface{}{ "cus_status": 1, "qr_code": string(decodedBytes), }) } else if status == "NEED_RELOGIN_BUREAU" { c.ServeSuccessJSON(map[string]interface{}{ "cus_status": -3, "msg": "登录失效,请重新短信登录税局", }) } } } else { c.ServeSuccessJSON(map[string]interface{}{ "cus_status": -4, "msg": resp.Message, }) } } //fmt.Println(string(r)) } } func (c *FapiaoApiController) OpenFaPiao() { //var config models.FapiaoConfig //config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) //认证接口 sdk := invoice.NewSdk(common.HMAC_SHA256, "5058f0defd12047ee2a7", "51440fbee667ea9a53aaa68c9c408367", "", "") //status := GetQRStatusTwo(c.GetAdminUserInfo().CurrentOrgId) //fmt.Println("11112222") // //fmt.Println(status) //if status == 0 { // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAuthWrong) // return //} //查询余量接口 //routerAddress, postData := bwfapiao.QueryStock(config) //r, err := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData) //fmt.Println(string(r)) //if err != nil { // fmt.Println(err) //} else { // var resp2 FapiaoStock // // 将 byte 切片转换为结构体 // err2 := json.Unmarshal(r, &resp2) // if err2 != nil { // fmt.Println(err2) // // } else { // if resp2.Code == 0 { // if resp2.Data.LeftQuantity <= 0 { // c.ServeSuccessJSON(map[string]interface{}{ // "msg": "发票余量不足,请登录高灯平台申领发票", // "status": -1, // }) // return // } // } // } //} //return //开蓝票逻辑 order_ids := c.GetString("order_ids") admin_user_id, _ := c.GetInt64("admin_user_id") ids := strings.Split(order_ids, ",") orders, _ := service.GetFaPiaoOrderByIDS(ids) var MedfeeSumamt float64 = 0 //治疗费用 var PsnCashPay float64 = 0 //治疗费用 var FundPaySumamt float64 = 0 //治疗费用 var HifmiPay float64 = 0 //治疗费用 var MafPay float64 = 0 //治疗费用 var HifpPay float64 = 0 //治疗费用 var AcctPay float64 = 0 //治疗费用 var details []models.HisOrderInfo var numbers []string decimal.DivisionPrecision = 2 var remark string for _, oss := range orders { MedfeeSumamt, _ = decimal.NewFromFloat(MedfeeSumamt).Add(decimal.NewFromFloat(oss.MedfeeSumamt)).Float64() PsnCashPay, _ = decimal.NewFromFloat(PsnCashPay).Add(decimal.NewFromFloat(oss.PsnCashPay)).Float64() FundPaySumamt, _ = decimal.NewFromFloat(FundPaySumamt).Add(decimal.NewFromFloat(oss.FundPaySumamt)).Float64() HifmiPay, _ = decimal.NewFromFloat(HifmiPay).Add(decimal.NewFromFloat(oss.HifmiPay)).Float64() MafPay, _ = decimal.NewFromFloat(MafPay).Add(decimal.NewFromFloat(oss.MafPay)).Float64() HifpPay, _ = decimal.NewFromFloat(HifpPay).Add(decimal.NewFromFloat(oss.HifpPay)).Float64() AcctPay, _ = decimal.NewFromFloat(AcctPay).Add(decimal.NewFromFloat(oss.AcctPay)).Float64() numbers = append(numbers, oss.Number) } if MedfeeSumamt > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "医疗总费用: " + MedfeeSumamt_str } else { remark = remark + " 医疗总费用:" + MedfeeSumamt_str } } if FundPaySumamt > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", FundPaySumamt) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "基金支付总金额: " + MedfeeSumamt_str } else { remark = remark + " 基金支付总金额:" + MedfeeSumamt_str } } if PsnCashPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", PsnCashPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "个人现金支付: " + MedfeeSumamt_str } else { remark = remark + " 个人现金支付:" + MedfeeSumamt_str } } if HifmiPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", HifmiPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "大病基金支付: " + MedfeeSumamt_str } else { remark = remark + " 大病基金支付:" + MedfeeSumamt_str } } if AcctPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", AcctPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "个账支付: " + MedfeeSumamt_str } else { remark = remark + " 个账支付:" + MedfeeSumamt_str } } if HifpPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", HifpPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "基本统筹基金支付: " + MedfeeSumamt_str } else { remark = remark + " 基本统筹基金支付:" + MedfeeSumamt_str } } if MafPay > 0 { MedfeeSumamt_str := fmt.Sprintf("%.2f", MafPay) if len(remark) == 0 { //MedfeeSumamt_str := fmt.Sprintf("%.2f", MedfeeSumamt) remark = "医疗救助基金支付: " + MedfeeSumamt_str } else { remark = remark + " 医疗救助基金支付:" + MedfeeSumamt_str } } details, _ = service.GetFaPiaoOrderInfoByNumbers(numbers) role, _ := service.GetAdminUserRole(admin_user_id, c.GetAdminUserInfo().CurrentOrgId) //role.UserName = "" type CostType struct { name string price float64 } var cts []CostType var ct CostType var bedCostTotal float64 = 0 //床位总费 var operationCostTotal float64 = 0 //手术费 var otherCostTotal float64 = 0 //其他费用 var materialCostTotal float64 = 0 //材料费 var westernMedicineCostTotal float64 = 0 //西药费 var chineseTraditionalMedicineCostTotal float64 = 0 //中成药 var checkCostTotal float64 = 0 //检查费 var laboratoryCostTotal float64 = 0 //化验费 var treatCostTotal float64 = 0 //治疗费用 var huliCostTotal float64 = 0 //治疗费用 var zhencaCostTotal float64 = 0 //治疗费用 for _, item := range details { if item.MedChrgitmType == "01" { //床位费 bedCostTotal, _ = decimal.NewFromFloat(bedCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "07" { //护理费 huliCostTotal, _ = decimal.NewFromFloat(huliCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if c.GetAdminUserInfo().CurrentOrgId == 10188 || c.GetAdminUserInfo().CurrentOrgId == 10217 { if item.MedChrgitmType == "03" { //检查费 laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } } else { if item.MedChrgitmType == "03" { //检查费 checkCostTotal, _ = decimal.NewFromFloat(checkCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } } if item.MedChrgitmType == "04" { //化验费 laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "05" || item.MedChrgitmType == "1402" || item.MedChrgitmType == "1403" { //治疗费 treatCostTotal, _ = decimal.NewFromFloat(treatCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "06" { //手术费 operationCostTotal, _ = decimal.NewFromFloat(operationCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "08" { //材料费 materialCostTotal, _ = decimal.NewFromFloat(materialCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "09" { //西药费 westernMedicineCostTotal, _ = decimal.NewFromFloat(westernMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "11" { //中成费 chineseTraditionalMedicineCostTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "14" || item.MedChrgitmType == "0" || item.MedChrgitmType == "12" { //其他费 otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } if item.MedChrgitmType == "02" { //诊察 zhencaCostTotal, _ = decimal.NewFromFloat(zhencaCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64() } } if bedCostTotal > 0 { ct.name = "床位费" ct.price = bedCostTotal cts = append(cts, ct) } if operationCostTotal > 0 { ct.name = "手术费" ct.price = operationCostTotal cts = append(cts, ct) } if otherCostTotal > 0 { ct.name = "其他费" ct.price = otherCostTotal cts = append(cts, ct) } if materialCostTotal > 0 { ct.name = "材料费" ct.price = materialCostTotal cts = append(cts, ct) } if westernMedicineCostTotal > 0 { ct.name = "西药费" ct.price = westernMedicineCostTotal cts = append(cts, ct) } if chineseTraditionalMedicineCostTotal > 0 { ct.name = "中成药费" ct.price = chineseTraditionalMedicineCostTotal cts = append(cts, ct) } if checkCostTotal > 0 { ct.name = "检查费" ct.price = checkCostTotal cts = append(cts, ct) } if laboratoryCostTotal > 0 { ct.name = "化验费" ct.price = laboratoryCostTotal cts = append(cts, ct) } if treatCostTotal > 0 { ct.name = "治疗费" ct.price = treatCostTotal cts = append(cts, ct) } if huliCostTotal > 0 { ct.name = "护理费" ct.price = huliCostTotal cts = append(cts, ct) } if zhencaCostTotal > 0 { ct.name = "诊察费" ct.price = zhencaCostTotal cts = append(cts, ct) } fmt.Println(cts) org_config, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId) var config2 models.FapiaoConfig config2, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) number := strconv.FormatInt(time.Now().Unix(), 10) + "_" + strconv.FormatInt(orders[0].UserOrgId, 10) + "_" + strconv.FormatInt(orders[0].PatientId, 10) amountWithoutTax, _, taxAmount, amountHasTax := CalculatePriceDetails(MedfeeSumamt, 1, 0.00) patient, _ := service.GetXTPatientInfo(c.GetAdminUserInfo().CurrentOrgId, orders[0].PatientId) orders[0].PsnName = patient.Name role.UserName = "陈金娣" postData3 := map[string]interface{}{ "seller_name": org_config.OrgName, "seller_taxpayer_num": config2.SellerTaxpayerNum, "seller_address": config2.SellerAddress, "seller_tel": config2.SellerTel, "seller_bank_name": config2.SellerBankName, "seller_bank_account": config2.SellerBankAccount, "title_type": 1, "buyer_title": orders[0].PsnName + "(个人)", "buyer_taxpayer_num": "", "buyer_address": "", "buyer_phone": "", "buyer_bank_name": "", "buyer_bank_account": "", "buyer_email": "", "order_id": number, "invoice_type_code": "082", "callback_url": "http://www.goldentec.com/callback", "drawer": role.UserName, "payee": "", "checker": "", "terminal_code": config2.TerminalCode, "user_openid": "", "special_invoice_kind": "", "zsfs": "", "deduction": "", "amount_has_tax": amountHasTax, "tax_amount": taxAmount, "amount_without_tax": amountWithoutTax, "remark": remark, } ////项目商品明细 items := make([]map[string]interface{}, 0) for _, ct := range cts { item := make(map[string]interface{}) amountWithoutTax, _, taxAmount, _ := CalculatePriceDetails(ct.price, 1, 0.00) item["name"] = ct.name item["tax_code"] = "3070202000000000000" item["models"] = "" item["unit"] = "" item["total_price"] = amountWithoutTax item["total"] = "1" item["price"] = amountWithoutTax item["tax_rate"] = "0.00" item["tax_amount"] = taxAmount item["discount"] = "0" item["preferential_policy_flag"] = "1" item["zero_tax_flag"] = "1" item["vat_special_management"] = "免税" items = append(items, item) } postData3["items"] = items routerAddress, postData4 := fapiao.Blue(postData3) //发票开具 fmt.Println(postData4) return r, err4 := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData4) fmt.Println("blue") fmt.Println(err4) fmt.Println(string(r)) if err4 != nil { fmt.Println(err4) } else { var resp OpenFaPiaoResultResponse // 将 byte 切片转换为结构体 err := json.Unmarshal(r, &resp) fmt.Println(resp) if err != nil { fmt.Println("Error unmarshalling:", err) } else { fmt.Println(resp) if resp.Code == 0 { var fapiaos models.HisFaPiaoOrder fapiaos.InvoiceId = resp.Data.InvoiceId fapiaos.OrderSn = resp.Data.OrderSn fapiaos.FapiaoStatus = "1" fapiaos.OrderIds = order_ids fapiaos.UserOrgId = c.GetAdminUserInfo().CurrentOrgId fapiaos.Status = 1 fapiaos.PatientId = orders[0].PatientId fapiaos.Ctime = time.Now().Unix() fapiaos.Mtime = time.Now().Unix() fapiaos.Creator = role.UserName fapiaos.MedfeeSumamt = MedfeeSumamt fapiaos.FundPaySumamt = FundPaySumamt fapiaos.PsnCashPay = PsnCashPay fmt.Println(ids) service.UpdateFaPiaoSN(resp.Data.OrderSn, ids) //同步发票号码 err5 := service.SaveFaPiaoOrder(&fapiaos) // 异步调用查询操作,通过闭包传递参数 // 异步调用查询操作,通过闭包传递多个参数 go func(num string, sn string, number string, fapiaos models.HisFaPiaoOrder, ids []string) { // 延迟等待一定时间再查询 time.Sleep(30 * time.Second) // 调用查询发票的函数 //queryInvoice(id, user, retries) routerAddress2, postData2 := fapiao.Query(num, sn, number) r3, err2 := sdk.HttpPost("https://apigw.goldentec.com", routerAddress2, postData2) fmt.Println("query") fmt.Println(string(r3)) if err2 != nil { fmt.Println(err2) } else { var resp3 QueryFaPiaoResultResponse // 将 byte 切片转换为结构体 json.Unmarshal(r3, &resp3) if resp3.Code == 0 { if resp3.Data.Status == 3 { // 异步调用查询操作,不阻塞主程序 fapiaos.TicketSn = resp3.Data.TicketSn fapiaos.TicketDate = resp3.Data.TicketDate fapiaos.AmountWithTax = resp3.Data.AmountWithoutTax fapiaos.AmountWithoutTax = resp3.Data.AmountWithoutTax fapiaos.FapiaoStatus = "2" fapiaos.TaxAmount = resp3.Data.TaxAmount fapiaos.IsRedWashed = strconv.FormatInt(int64(resp3.Data.IsRedWashed), 10) fapiaos.PdfUrl = resp3.Data.PdfUrl fapiaos.OfdUrl = resp3.Data.OfdUrl fapiaos.XmlUrl = resp3.Data.XmlUrl service.SaveFaPiaoOrder(&fapiaos) service.UpdateFaPiaoNumber(resp3.Data.TicketSn, ids) //同步发票号码 } else if resp3.Data.Status == 1 { fapiaos.FapiaoStatus = "1" fapiaos.TicketSn = "" service.SaveFaPiaoOrder(&fapiaos) //service.UpdateFaPiaoNumber(resp3.Data.TicketSn, ids) //同步发票号码 } else if resp3.Data.Status == 2 { fapiaos.FapiaoStatus = "3" fapiaos.TicketSn = "" fapiaos.Message = resp3.Data.Message service.SaveFaPiaoOrder(&fapiaos) } else { fapiaos.FapiaoStatus = "3" fapiaos.TicketSn = "" fapiaos.Message = resp3.Data.Message service.SaveFaPiaoOrder(&fapiaos) } } else { //错误处理 c.ServeSuccessJSON(map[string]interface{}{ "msg": "查询失败" + resp3.Message, }) } } }(config2.SellerTaxpayerNum, resp.Data.OrderSn, number, fapiaos, ids) // 这里将多个参数传递给闭包 if err5 == nil { c.ServeSuccessJSON(map[string]interface{}{ "msg": "开具成功,审核中。", }) } } else { //错误处理 c.ServeSuccessJSON(map[string]interface{}{ "msg": "开具失败" + resp.Message, }) } } } } func (c *FapiaoApiController) RedFaPiao() { id, _ := c.GetInt64("id") admin_user_id, _ := c.GetInt64("admin_user_id") role2, _ := service.GetAdminUserRole(admin_user_id, c.GetAdminUserInfo().CurrentOrgId) fapiao_config, _ := service.GetFaPiaoOrderById(id) var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId) sdk := invoice.NewSdk(common.HMAC_SHA256, "5058f0defd12047ee2a7", "51440fbee667ea9a53aaa68c9c408367", "", "test") routerAddress, postData := fapiao.Red(config.SellerTaxpayerNum, "", fapiao_config.OrderSn) //发票开具 fmt.Println("postData") fmt.Println(postData) fmt.Println("postData") red, err := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData) fmt.Println("red") fmt.Println(red) fmt.Println("red") if err != nil { fmt.Println(err) } else { var resp RedResult // 将 byte 切片转换为结构体 json.Unmarshal(red, &resp) fmt.Println("resp") fmt.Println(resp) fmt.Println("resp") if resp.Code == 0 { if resp.Data[0].State == 1 { //查询红票开具情况 routerAddress2, postData2 := fapiao.Query(config.SellerTaxpayerNum, fapiao_config.OrderSn, "") r3, _ := sdk.HttpPost("https://apigw.goldentec.com", routerAddress2, postData2) var resp3 QueryFaPiaoResultResponse // 将 byte 切片转换为结构体 json.Unmarshal(r3, &resp3) fmt.Println("resp") fmt.Println(string(r3)) fmt.Println(resp3) fmt.Println("resp") if resp3.Code == 0 { if resp3.Data.IsRedWashed == 1 { fapiao_config.IsRedWashed = "1" fapiao_config.Status = 0 fapiao_config.RedInvoiceId = resp.Data[0].InvoiceId fapiao_config.RedInvoiceCreator = role2.UserName service.SaveFaPiaoOrder(&fapiao_config) //将结算表的发票号码清空 service.UpdateFaPiaoNumberByNumber(fapiao_config.TicketSn) c.ServeSuccessJSON(map[string]interface{}{ "msg": "红冲成功", }) } else { c.ServeSuccessJSON(map[string]interface{}{ "msg": "系统错误,红冲失败", }) } } else { c.ServeSuccessJSON(map[string]interface{}{ "msg": resp3.Message, }) } } else { c.ServeSuccessJSON(map[string]interface{}{ "msg": resp.Message, }) } } else { c.ServeSuccessJSON(map[string]interface{}{ "msg": resp.Message, }) } } } func GetQRStatusTwo(org_id int64) (status int64) { sdk := invoice.NewSdk(common.HMAC_SHA256, "5058f0defd12047ee2a7", "51440fbee667ea9a53aaa68c9c408367", "", "test") var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(org_id) routerAddress, postData := fapiao.GetQRCode(config) //发票开具 r, err := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData) if err != nil { fmt.Println(err) } else { var resp QRAuth // 将 byte 切片转换为结构体 err := json.Unmarshal(r, &resp) fmt.Println(resp) if err != nil { fmt.Println("Error unmarshalling:", err) } else { if len(resp.Data.AuthId) == 0 { //还没实名认证 } else { status = 1 status_str := GetQRStatus(org_id, resp.Data.AuthId) if status_str == "UNDEFINE" { status = 0 } else if status_str == "UNHANDLED" { status = 0 } else if status_str == "REAL_AUTH_SUCCESS" { status = 1 } else if status_str == "REFRESH" { status = 0 } else if status_str == "NEED_RELOGIN_BUREAU" { status = 0 } } } } return } type RedResult struct { Code int `json:"code"` Data []struct { State int `json:"state"` Message string `json:"message"` OrderSn string `json:"order_sn"` InvoiceId string `json:"invoice_id"` } `json:"data"` Message string `json:"message"` } type QueryFaPiaoResultResponse struct { Code int `json:"code"` Data struct { OrderSn string `json:"order_sn"` Status int `json:"status"` Message string `json:"message"` TicketDate string `json:"ticket_date"` TicketSn string `json:"ticket_sn"` TicketCode string `json:"ticket_code"` CheckCode string `json:"check_code"` AmountWithTax string `json:"amount_with_tax"` AmountWithoutTax string `json:"amount_without_tax"` TaxAmount string `json:"tax_amount"` IsRedWashed int `json:"is_red_washed"` PdfUrl string `json:"pdf_url"` OfdUrl string `json:"ofd_url"` XmlUrl string `json:"xml_url"` } `json:"data"` Message string `json:"message"` } type OpenFaPiaoResultResponse struct { Code int `json:"code"` Message string `json:"message"` Data struct { State int `json:"state"` OrderSn string `json:"order_sn"` InvoiceId string `json:"invoice_id"` } `json:"data"` } type SurplusStockResponse struct { Code int `json:"code"` Message string `json:"message"` Data struct { LeftQuantity int `json:"left_quantity"` } `json:"data"` } func GetFaPiaoStock(org_id int64) (left_quantity int) { sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test") var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(org_id) routerAddress, postData := fapiao.QueryStock(config) r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData) if err != nil { fmt.Println(err) } else { var resp SurplusStockResponse // 将 byte 切片转换为结构体 err := json.Unmarshal(r, &resp) if err != nil { fmt.Println("Error unmarshalling:", err) } else { if resp.Code == 0 { left_quantity = resp.Data.LeftQuantity } } } return } type Response struct { Code int `json:"code"` Message string `json:"message"` Data struct { Status string `json:"status"` } `json:"data"` } func GetQRStatus(org_id int64, auth_id string) (status string) { sdk := invoice.NewSdk(common.HMAC_SHA256, "5058f0defd12047ee2a7", "51440fbee667ea9a53aaa68c9c408367", "", "test") fmt.Println(sdk) var config models.FapiaoConfig config, _ = service.FindFaPiaoConfigInfo(org_id) fmt.Println(config) routerAddress, postData := fapiao.GetQRStatus(auth_id, config) //发票开具 fmt.Println(routerAddress) fmt.Println(postData) r, err := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData) if err != nil { status = "FAILD" fmt.Println(err) } else { fmt.Println(r) var resp Response // 将 byte 切片转换为结构体 err := json.Unmarshal(r, &resp) fmt.Println(string(r)) if err != nil { status = "FAILD" fmt.Println("Error unmarshalling:", err) } else { status = resp.Data.Status fmt.Printf("Parsed struct: %+v\n", resp) } } return status //return } // 计算商品价格、税额等函数 func CalculatePriceDetails(totalCost float64, itemCount int, taxRate float64) (string, string, string, string) { // 商品不含税总金额,保留两位小数 amountWithoutTax := roundTo(totalCost/(1+taxRate), 2) // 商品不含税单价,保留八位小数 pricePerItem := roundTo(amountWithoutTax/float64(itemCount), 8) // 税额,保留两位小数 taxAmount := roundTo(amountWithoutTax*taxRate, 2) // 含税总金额 amountHasTax := amountWithoutTax + taxAmount return fmt.Sprintf("%f", amountWithoutTax), fmt.Sprintf("%f", pricePerItem), fmt.Sprintf("%f", taxAmount), fmt.Sprintf("%f", amountHasTax) } // 保留指定小数位数的函数 func roundTo(value float64, places int) float64 { scale := math.Pow(10, float64(places)) return math.Round(value*scale) / scale } type QRAuth struct { Code int `json:"code"` Message string `json:"message"` Data struct { AuthId string `json:"auth_id"` QrCode string `json:"qr_code"` } `json:"data"` } type FapiaoStock struct { Code int `json:"code"` Data struct { LeftQuantity int `json:"left_quantity"` } `json:"data"` Message string `json:"message"` }