123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989 |
- package controllers
-
- import (
- "XT_New/common"
- "XT_New/enums"
- "XT_New/invoice"
- "XT_New/models"
- "XT_New/service"
- "XT_New/service/fapiao"
- "XT_New/utils"
- "encoding/base64"
- "encoding/json"
- "fmt"
- "github.com/astaxie/beego"
- "github.com/shopspring/decimal"
- "math"
- "strconv"
- "strings"
- "time"
- )
-
- func FaPiaoApiRegistRouters() {
- beego.Router("/api/fapiao/sms/code", &FapiaoApiController{}, "get:GetLoginUploadCode")
- beego.Router("/api/fapiao/sms/login", &FapiaoApiController{}, "get:Login")
- beego.Router("/api/fapiao/qrcode/get", &FapiaoApiController{}, "get:GetQRCode")
-
- beego.Router("/api/fapiao/blue", &FapiaoApiController{}, "get:OpenFaPiao")
- beego.Router("/api/fapiao/red", &FapiaoApiController{}, "get:RedFaPiao")
-
- beego.Router("/api/order/fapiao/list", &FapiaoApiController{}, "get:GetOrderFaPiaoList")
- beego.Router("/api/gdfapiao/list", &FapiaoApiController{}, "get:GetFaPiaoList")
-
- }
-
- 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")
- 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)
- 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)
-
- 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)
- 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", "", "test")
- status := GetQRStatusTwo(c.GetAdminUserInfo().CurrentOrgId)
- fmt.Println("11112222")
-
- fmt.Println(status)
- if status == 0 {
- c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAuthWrong)
- return
- }
- //查询余量接口
- //routerAddress, postData := fapiao.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 details []models.HisOrderInfo
- var numbers []string
- decimal.DivisionPrecision = 2
-
- 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()
- numbers = append(numbers, oss.Number)
- }
- 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.13)
-
- 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": "医疗发票",
- }
-
- ////项目商品明细
- items := make([]map[string]interface{}, 0)
- for _, ct := range cts {
- item := make(map[string]interface{})
- amountWithoutTax, _, taxAmount, _ := CalculatePriceDetails(ct.price, 1, 0.06)
- 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.06"
- item["tax_amount"] = taxAmount
- item["discount"] = "0"
- item["preferential_policy_flag"] = ""
- item["zero_tax_flag"] = ""
- item["vat_special_management"] = ""
- items = append(items, item)
- }
-
- postData3["items"] = items
- routerAddress, postData4 := fapiao.Blue(postData3) //发票开具
- r, err4 := sdk.HttpPost("https://apigw.goldentec.com", routerAddress, postData4)
- fmt.Println("blue")
- 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 {
- //开具蓝票成功,请求查询接口,获取发票相关数据
- routerAddress2, postData2 := fapiao.Query(config2.SellerTaxpayerNum, resp.Data.OrderSn, 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 {
- var fapiao models.HisFaPiaoOrder
- fapiao.InvoiceId = resp.Data.InvoiceId
- fapiao.OrderSn = resp.Data.OrderSn
- fapiao.TicketSn = resp3.Data.TicketSn
- fapiao.TicketDate = resp3.Data.TicketDate
- fapiao.AmountWithTax = resp3.Data.AmountWithoutTax
- fapiao.AmountWithoutTax = resp3.Data.AmountWithoutTax
- fapiao.TaxAmount = resp3.Data.TaxAmount
- fapiao.IsRedWashed = strconv.FormatInt(int64(resp3.Data.IsRedWashed), 10)
- fapiao.PdfUrl = resp3.Data.PdfUrl
- fapiao.OfdUrl = resp3.Data.OfdUrl
- fapiao.XmlUrl = resp3.Data.XmlUrl
- fapiao.FapiaoStatus = "1"
- fapiao.OrderIds = order_ids
- fapiao.UserOrgId = c.GetAdminUserInfo().CurrentOrgId
- fapiao.Status = 1
- fapiao.PatientId = orders[0].PatientId
- fapiao.Ctime = time.Now().Unix()
- fapiao.Mtime = time.Now().Unix()
- fapiao.Creator = role.UserName
- fapiao.MedfeeSumamt = MedfeeSumamt
- fapiao.FundPaySumamt = FundPaySumamt
- fapiao.PsnCashPay = PsnCashPay
- err5 := service.SaveFaPiaoOrder(fapiao)
- fmt.Println(err5)
- if err5 == nil {
- service.UpdateFaPiaoNumber(resp3.Data.TicketSn, ids) //同步发票号码
- c.ServeSuccessJSON(map[string]interface{}{
- "msg": "开具成功",
- })
- }
- } else {
- //错误处理
-
- }
- }
- } else {
- //错误处理
-
- }
- }
- }
- }
- func (c *FapiaoApiController) RedFaPiao() {
- //认证
- status := GetQRStatusTwo(c.GetAdminUserInfo().CurrentOrgId)
- if status == 0 {
- c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAuthWrong)
- return
- }
-
- 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": "红冲失败",
- })
- }
- } else {
- c.ServeSuccessJSON(map[string]interface{}{
- "msg": "红冲失败",
- })
- }
- } else {
-
- c.ServeSuccessJSON(map[string]interface{}{
- "msg": "红冲失败",
- })
- }
- }
- }
- 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"`
- }
|