fapiao_controller.go 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. package controllers
  2. import (
  3. "XT_New/common"
  4. "XT_New/enums"
  5. "XT_New/invoice"
  6. "XT_New/models"
  7. "XT_New/service"
  8. "XT_New/service/fapiao"
  9. "XT_New/utils"
  10. "encoding/json"
  11. "fmt"
  12. "github.com/astaxie/beego"
  13. "github.com/shopspring/decimal"
  14. "math"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. func FaPiaoApiRegistRouters() {
  20. beego.Router("/api/fapiao/sms/code", &FapiaoApiController{}, "get:GetLoginUploadCode")
  21. beego.Router("/api/fapiao/sms/login", &FapiaoApiController{}, "get:Login")
  22. beego.Router("/api/fapiao/qrcode/get", &FapiaoApiController{}, "get:GetQRCode")
  23. beego.Router("/api/fapiao/blue", &FapiaoApiController{}, "get:OpenFaPiao")
  24. beego.Router("/api/fapiao/red", &FapiaoApiController{}, "get:RedFaPiao")
  25. beego.Router("/api/order/fapiao/list", &FapiaoApiController{}, "get:GetOrderFaPiaoList")
  26. beego.Router("/api/gdfapiao/list", &FapiaoApiController{}, "get:GetFaPiaoList")
  27. }
  28. type FapiaoApiController struct {
  29. BaseAuthAPIController
  30. }
  31. type InvoiceRequest struct {
  32. SellerName string `json:"seller_name,omitempty"` // 销方名称
  33. SellerTaxpayerNum string `json:"seller_taxpayer_num"` // 销方纳税人识别号
  34. SellerAddress string `json:"seller_address"` // 销方地址
  35. SellerTel string `json:"seller_tel"` // 销方电话
  36. SellerBankName string `json:"seller_bank_name"` // 销方银行名称
  37. SellerBankAccount string `json:"seller_bank_account"` // 销方银行账号
  38. TitleType int `json:"title_type"` // 抬头类型:1 个人、政府事业单位;2 企业
  39. BuyerTitle string `json:"buyer_title"` // 购方名称
  40. BuyerTaxpayerNum string `json:"buyer_taxpayer_num,omitempty"` // 购方纳税人识别号
  41. BuyerAddress string `json:"buyer_address,omitempty"` // 购方地址
  42. BuyerPhone string `json:"buyer_phone,omitempty"` // 购方电话
  43. BuyerBankName string `json:"buyer_bank_name,omitempty"` // 购方银行名称
  44. BuyerBankAccount string `json:"buyer_bank_account,omitempty"` // 购方银行账号
  45. BuyerEmail string `json:"buyer_email,omitempty"` // 收票人邮箱
  46. OrderID string `json:"order_id"` // 商户订单号
  47. InvoiceTypeCode string `json:"invoice_type_code,omitempty"` // 开具发票类型
  48. CallbackURL string `json:"callback_url"` // 发票结果回传地址
  49. Drawer string `json:"drawer"` // 开票人姓名
  50. Payee string `json:"payee,omitempty"` // 收款人姓名
  51. Checker string `json:"checker,omitempty"` // 复核人姓名
  52. TerminalCode string `json:"terminal_code"` // 税盘号
  53. UserOpenID string `json:"user_openid,omitempty"` // 商家用户标识
  54. SpecialInvoiceKind string `json:"special_invoice_kind,omitempty"` // 特殊票种标识
  55. AmountHasTax string `json:"amount_has_tax"` // 含税总金额
  56. TaxAmount string `json:"tax_amount"` // 总税额
  57. AmountWithoutTax string `json:"amount_without_tax"` // 不含税总金额
  58. Remark string `json:"remark,omitempty"` // 备注
  59. StoreNo string `json:"store_no,omitempty"` // 门店编码
  60. Template int `json:"template"` // 发票模板
  61. Info *InvoiceInfo `json:"info,omitempty"` // 冠名票信息
  62. TaxpayerConfirmation *TaxpayerConfirmation `json:"taxpayer_confirmation,omitempty"` // 纳税人确认信息
  63. SpecificBusinessCode string `json:"specific_business_code,omitempty"` // 特定业务代码
  64. RealStaticRent *RealStaticRent `json:"real_static_rent,omitempty"` // 不动产经营租赁信息
  65. PassengerTransport []PassengerTransport `json:"passenger_transport,omitempty"` // 旅客运输信息
  66. GoodsTransport []GoodsTransport `json:"goods_transport,omitempty"` // 货物运输信息
  67. AgriculturalPurchase *AgriculturalPurchase `json:"agricultural_purchase,omitempty"` // 农产品收购信息
  68. BuildingService *BuildingService `json:"building_service,omitempty"` // 建筑服务信息
  69. RealStaticSales *RealStaticSales `json:"real_static_sales,omitempty"` // 不动产销售信息
  70. TractorCombine *TractorCombine `json:"tractor_combine,omitempty"` // 拖拉机与联合收割机信息
  71. UsedCarService *UsedCarService `json:"used_car_service,omitempty"` // 二手车服务信息
  72. UsedCarSell *UsedCarSell `json:"used_car_sell,omitempty"` // 二手车销售信息
  73. DeductionService *DeductionService `json:"deduction_service,omitempty"` // 差额征税信息
  74. Items []Item `json:"items"` // 项目商品明细
  75. }
  76. type InvoiceInfo struct {
  77. UseDate string `json:"use_date,omitempty"` // 入园日期
  78. TicketName string `json:"ticket_name,omitempty"` // 票据名称
  79. }
  80. type TaxpayerConfirmation struct {
  81. RenewableResourceRecyclingFlag int `json:"renewable_resource_recycling_flag,omitempty"` // 再生资源回收单位标志
  82. DrawWithNoBuyerFlag int `json:"draw_with_nobuyer_flag,omitempty"` // 无购买方纳税人信息继续开票标志
  83. NotDutyFreeReason string `json:"not_dutyfree_reason,omitempty"` // 放弃享受减按1%征收率原因
  84. }
  85. type RealStaticRent struct {
  86. PropertyNum string `json:"property_num"` // 房屋产权证号
  87. Location string `json:"location"` // 不动产地址 (省市区县)
  88. AddressDetail string `json:"address_detail"` // 不动产详细地址
  89. RentBeginDate string `json:"rent_begin_date"` // 租赁期起
  90. RentEndDate string `json:"rent_end_date"` // 租赁期止
  91. IntercityFlag string `json:"intercity_flag"` // 跨地市标志
  92. UnitOfArea int `json:"unit_of_area"` // 面积单位
  93. }
  94. type PassengerTransport struct {
  95. Traveler string `json:"traveler,omitempty"` // 出行人
  96. IDType int `json:"id_type,omitempty"` // 证件类型
  97. IDNumber string `json:"id_number,omitempty"` // 证件号码
  98. TravelDate string `json:"travel_date,omitempty"` // 出行日期
  99. DeparturePlace string `json:"departure_place,omitempty"` // 出发地
  100. DestinationPlace string `json:"destination_palce,omitempty"` // 到达地
  101. VehicleType int `json:"vehicle_type,omitempty"` // 交通工具类型
  102. Level string `json:"level,omitempty"` // 等级
  103. }
  104. type GoodsTransport struct {
  105. TransportNumber string `json:"transport_number,omitempty"` // 运输工具号牌
  106. TransportKind string `json:"transport_kind,omitempty"` // 运输工具种类
  107. GoodsName string `json:"goods_name,omitempty"` // 货物名称
  108. DeparturePlace string `json:"departure_place,omitempty"` // 出发地
  109. DestinationPlace string `json:"destination_place,omitempty"` // 到达地
  110. }
  111. type AgriculturalPurchase struct {
  112. IDType string `json:"id_type,omitempty"` // 证件类型
  113. }
  114. type BuildingService struct {
  115. Site string `json:"site"` // 建筑服务发生地
  116. DetailSite string `json:"detail_site,omitempty"` // 详细地址
  117. BuildingProject string `json:"building_project"` // 建筑项目名称
  118. CrossSign string `json:"cross_sign"` // 跨地市标志
  119. }
  120. type RealStaticSales struct {
  121. PropertyNum string `json:"property_num,omitempty"` // 房屋产权证书号
  122. Location string `json:"location"` // 不动产地址
  123. AddressDetail string `json:"address_detail,omitempty"` // 不动产详细地址
  124. CrossSign string `json:"cross_sign"` // 跨市标志
  125. UnitOfArea int `json:"unit_of_area"` // 面积单位
  126. OnlineContractCode string `json:"online_contract_code,omitempty"` // 不动产单元代码/网签合同编码
  127. }
  128. type TractorCombine struct {
  129. ChassisNumber string `json:"chassis_number,omitempty"` // 底盘号或机架号
  130. EngineNumber string `json:"engine_number"` // 发动机号
  131. IsRegister string `json:"is_register,omitempty"` // 是否用于拖拉机和联合收割机登记
  132. }
  133. type UsedCarService struct {
  134. TicketSN string `json:"ticket_sn"` // 发票号码
  135. PaperTicketCode string `json:"paper_ticket_code"` // 纸票发票代码
  136. PaperTicketSN string `json:"paper_ticket_sn"` // 纸票发票号码
  137. }
  138. type UsedCarSell struct {
  139. FrameNumber string `json:"frame_number"` // 车架号码
  140. LicensePlateNumber string `json:"license_plate_number"` // 车牌号
  141. BrandModel string `json:"brand_model"` // 厂牌型号
  142. RegistrationCertificate string `json:"registration_certificate"` // 登记证号
  143. TransferOfficeName string `json:"transfer_office_name"` // 转入地车辆管理所名称
  144. NatureOfEnterprise string `json:"nature_of_enterprise"` // 企业性质
  145. }
  146. type DeductionService struct {
  147. TaxDiffServiceFlag int `json:"tax_diff_service_flag,omitempty"` // 差额征税标识
  148. TaxableServiceName string `json:"taxable_service_name,omitempty"` // 差额征税项目名称
  149. }
  150. type Item struct {
  151. ItemName string `json:"item_name"` // 商品名称
  152. ItemSpec string `json:"item_spec,omitempty"` // 商品规格
  153. ItemUnit string `json:"item_unit"` // 商品单位
  154. ItemQuantity float64 `json:"item_quantity"` // 商品数量
  155. ItemPrice float64 `json:"item_price"` // 商品单价
  156. ItemAmount float64 `json:"item_amount"` // 商品金额
  157. ItemTaxRate float64 `json:"item_tax_rate"` // 商品税率
  158. ItemTaxAmount float64 `json:"item_tax_amount"` // 商品税额
  159. RowType int `json:"row_type"` // 行性质标志
  160. }
  161. func (c *FapiaoApiController) GetFaPiaoList() {
  162. page, _ := c.GetInt64("page", -1)
  163. limit, _ := c.GetInt64("limit", -1)
  164. start_time := c.GetString("start_time")
  165. end_time := c.GetString("end_time")
  166. timeLayout := "2006-01-02"
  167. loc, _ := time.LoadLocation("Local")
  168. var startTime int64
  169. if len(start_time) > 0 {
  170. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  171. if err != nil {
  172. //fmt.Println(err)
  173. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  174. return
  175. }
  176. startTime = theTime.Unix()
  177. }
  178. var endTime int64
  179. if len(end_time) > 0 {
  180. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  181. if err != nil {
  182. utils.ErrorLog(err.Error())
  183. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  184. return
  185. }
  186. endTime = theTime.Unix()
  187. }
  188. adminUser := c.GetAdminUserInfo()
  189. org_id := adminUser.CurrentOrgId
  190. order, err, total := service.GetFaPiaoList(org_id, page, limit, startTime, endTime)
  191. if err == nil {
  192. c.ServeSuccessJSON(map[string]interface{}{
  193. "fapiao_record": order,
  194. "total": total,
  195. })
  196. } else {
  197. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  198. return
  199. }
  200. }
  201. func (c *FapiaoApiController) GetOrderFaPiaoList() {
  202. page, _ := c.GetInt64("page", -1)
  203. limit, _ := c.GetInt64("limit", -1)
  204. start_time := c.GetString("start_time")
  205. end_time := c.GetString("end_time")
  206. is_open_fapiao, _ := c.GetInt64("is_open_fapiao", 0)
  207. sort_type, _ := c.GetInt64("sort_type", 0)
  208. patient_id, _ := c.GetInt64("patient_id", 0)
  209. timeLayout := "2006-01-02"
  210. loc, _ := time.LoadLocation("Local")
  211. var startTime int64
  212. if len(start_time) > 0 {
  213. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  214. if err != nil {
  215. //fmt.Println(err)
  216. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  217. return
  218. }
  219. startTime = theTime.Unix()
  220. }
  221. var endTime int64
  222. if len(end_time) > 0 {
  223. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  224. if err != nil {
  225. utils.ErrorLog(err.Error())
  226. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  227. return
  228. }
  229. endTime = theTime.Unix()
  230. }
  231. adminUser := c.GetAdminUserInfo()
  232. org_id := adminUser.CurrentOrgId
  233. order, err, total := service.GetFaPiaoSettleList(org_id, page, limit, startTime, endTime, sort_type, start_time, end_time, is_open_fapiao, patient_id)
  234. if err == nil {
  235. c.ServeSuccessJSON(map[string]interface{}{
  236. "order": order,
  237. "total": total,
  238. })
  239. } else {
  240. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  241. return
  242. }
  243. }
  244. func (c *FapiaoApiController) GetLoginUploadCode() {
  245. sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
  246. var config models.FapiaoConfig
  247. config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
  248. routerAddress, postData := fapiao.GetSMSCode(config) //发票开具
  249. r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
  250. if err != nil {
  251. fmt.Println(err)
  252. } else {
  253. fmt.Println(string(r))
  254. }
  255. }
  256. func (c *FapiaoApiController) Login() {
  257. GetQRStatus(c.GetAdminUserInfo().CurrentOrgId)
  258. code := c.GetString("code")
  259. var config models.FapiaoConfig
  260. config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
  261. sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
  262. routerAddress, postData := fapiao.Login(code, config) //发票开具
  263. r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
  264. if err != nil {
  265. fmt.Println(err)
  266. } else {
  267. fmt.Println(string(r))
  268. }
  269. }
  270. func (c *FapiaoApiController) GetQRCode() {
  271. sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
  272. var config models.FapiaoConfig
  273. config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
  274. routerAddress, postData := fapiao.GetQRCode(config) //发票开具
  275. r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
  276. if err != nil {
  277. fmt.Println(err)
  278. } else {
  279. fmt.Println(string(r))
  280. }
  281. }
  282. func (c *FapiaoApiController) OpenFaPiao() {
  283. //认证接口
  284. //查询余量接口
  285. order_ids := c.GetString("order_ids")
  286. admin_user_id, _ := c.GetInt64("admin_user_id")
  287. ids := strings.Split(order_ids, ",")
  288. orders, _ := service.GetFaPiaoOrderByIDS(ids)
  289. var MedfeeSumamt float64 = 0 //治疗费用
  290. var PsnCashPay float64 = 0 //治疗费用
  291. var FundPaySumamt float64 = 0 //治疗费用
  292. var details []models.HisOrderInfo
  293. var numbers []string
  294. decimal.DivisionPrecision = 2
  295. for _, oss := range orders {
  296. MedfeeSumamt, _ = decimal.NewFromFloat(MedfeeSumamt).Add(decimal.NewFromFloat(oss.MedfeeSumamt)).Float64()
  297. PsnCashPay, _ = decimal.NewFromFloat(PsnCashPay).Add(decimal.NewFromFloat(oss.PsnCashPay)).Float64()
  298. FundPaySumamt, _ = decimal.NewFromFloat(FundPaySumamt).Add(decimal.NewFromFloat(oss.FundPaySumamt)).Float64()
  299. numbers = append(numbers, oss.Number)
  300. }
  301. details, _ = service.GetFaPiaoOrderInfoByNumbers(numbers)
  302. //orders, _ := service.GetFaPiaoOrderByIDS(ids)
  303. role, _ := service.GetAdminUserRole(admin_user_id, c.GetAdminUserInfo().CurrentOrgId)
  304. role.UserName = "王毅"
  305. type CostType struct {
  306. name string
  307. price float64
  308. }
  309. var cts []CostType
  310. var ct CostType
  311. var bedCostTotal float64 = 0 //床位总费
  312. var operationCostTotal float64 = 0 //手术费
  313. var otherCostTotal float64 = 0 //其他费用
  314. var materialCostTotal float64 = 0 //材料费
  315. var westernMedicineCostTotal float64 = 0 //西药费
  316. var chineseTraditionalMedicineCostTotal float64 = 0 //中成药
  317. var checkCostTotal float64 = 0 //检查费
  318. var laboratoryCostTotal float64 = 0 //化验费
  319. var treatCostTotal float64 = 0 //治疗费用
  320. var huliCostTotal float64 = 0 //治疗费用
  321. var zhencaCostTotal float64 = 0 //治疗费用
  322. for _, item := range details {
  323. if item.MedChrgitmType == "01" { //床位费
  324. bedCostTotal, _ = decimal.NewFromFloat(bedCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  325. }
  326. if item.MedChrgitmType == "07" { //护理费
  327. huliCostTotal, _ = decimal.NewFromFloat(huliCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  328. }
  329. if c.GetAdminUserInfo().CurrentOrgId == 10188 || c.GetAdminUserInfo().CurrentOrgId == 10217 {
  330. if item.MedChrgitmType == "03" { //检查费
  331. laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  332. }
  333. } else {
  334. if item.MedChrgitmType == "03" { //检查费
  335. checkCostTotal, _ = decimal.NewFromFloat(checkCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  336. }
  337. }
  338. if item.MedChrgitmType == "04" { //化验费
  339. laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  340. }
  341. if item.MedChrgitmType == "05" || item.MedChrgitmType == "1402" || item.MedChrgitmType == "1403" { //治疗费
  342. treatCostTotal, _ = decimal.NewFromFloat(treatCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  343. }
  344. if item.MedChrgitmType == "06" { //手术费
  345. operationCostTotal, _ = decimal.NewFromFloat(operationCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  346. }
  347. if item.MedChrgitmType == "08" { //材料费
  348. materialCostTotal, _ = decimal.NewFromFloat(materialCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  349. }
  350. if item.MedChrgitmType == "09" { //西药费
  351. westernMedicineCostTotal, _ = decimal.NewFromFloat(westernMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  352. }
  353. if item.MedChrgitmType == "11" { //中成费
  354. chineseTraditionalMedicineCostTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  355. }
  356. if item.MedChrgitmType == "14" || item.MedChrgitmType == "0" || item.MedChrgitmType == "12" { //其他费
  357. otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  358. }
  359. if item.MedChrgitmType == "02" { //诊察
  360. zhencaCostTotal, _ = decimal.NewFromFloat(zhencaCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
  361. }
  362. }
  363. if bedCostTotal > 0 {
  364. ct.name = "床位费"
  365. ct.price = bedCostTotal
  366. cts = append(cts, ct)
  367. }
  368. if operationCostTotal > 0 {
  369. ct.name = "手术费"
  370. ct.price = operationCostTotal
  371. cts = append(cts, ct)
  372. }
  373. if otherCostTotal > 0 {
  374. ct.name = "其他费"
  375. ct.price = otherCostTotal
  376. cts = append(cts, ct)
  377. }
  378. if materialCostTotal > 0 {
  379. ct.name = "材料费"
  380. ct.price = materialCostTotal
  381. cts = append(cts, ct)
  382. }
  383. if westernMedicineCostTotal > 0 {
  384. ct.name = "西药费"
  385. ct.price = westernMedicineCostTotal
  386. cts = append(cts, ct)
  387. }
  388. if chineseTraditionalMedicineCostTotal > 0 {
  389. ct.name = "中成药费"
  390. ct.price = chineseTraditionalMedicineCostTotal
  391. cts = append(cts, ct)
  392. }
  393. if checkCostTotal > 0 {
  394. ct.name = "检查费"
  395. ct.price = checkCostTotal
  396. cts = append(cts, ct)
  397. }
  398. if laboratoryCostTotal > 0 {
  399. ct.name = "化验费"
  400. ct.price = laboratoryCostTotal
  401. cts = append(cts, ct)
  402. }
  403. if treatCostTotal > 0 {
  404. ct.name = "治疗费"
  405. ct.price = treatCostTotal
  406. cts = append(cts, ct)
  407. }
  408. if huliCostTotal > 0 {
  409. ct.name = "护理费"
  410. ct.price = huliCostTotal
  411. cts = append(cts, ct)
  412. }
  413. if zhencaCostTotal > 0 {
  414. ct.name = "诊察费"
  415. ct.price = zhencaCostTotal
  416. cts = append(cts, ct)
  417. }
  418. fmt.Println(cts)
  419. config, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId)
  420. var config2 models.FapiaoConfig
  421. config2, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
  422. number := strconv.FormatInt(time.Now().Unix(), 10) + "_" + strconv.FormatInt(orders[0].UserOrgId, 10) + "_" + strconv.FormatInt(orders[0].PatientId, 10)
  423. amountWithoutTax, _, taxAmount, amountHasTax := CalculatePriceDetails(MedfeeSumamt, 1, 0.13)
  424. postData := map[string]interface{}{
  425. "seller_name": config.OrgName,
  426. "seller_taxpayer_num": config2.SellerTaxpayerNum,
  427. "seller_address": config2.SellerAddress,
  428. "seller_tel": config2.SellerTel,
  429. "seller_bank_name": config2.SellerBankName,
  430. "seller_bank_account": config2.SellerBankAccount,
  431. "title_type": 1,
  432. "buyer_title": orders[0].PsnName,
  433. "buyer_taxpayer_num": "",
  434. "buyer_address": "",
  435. "buyer_phone": "",
  436. "buyer_bank_name": "",
  437. "buyer_bank_account": "",
  438. "buyer_email": "",
  439. "order_id": number,
  440. "invoice_type_code": "082",
  441. "callback_url": "http://www.goldentec.com/callback",
  442. "drawer": role.UserName,
  443. "payee": "",
  444. "checker": "",
  445. "terminal_code": "140301195503104110",
  446. "user_openid": "",
  447. "special_invoice_kind": "",
  448. "zsfs": "",
  449. "deduction": "",
  450. "amount_has_tax": amountHasTax,
  451. "tax_amount": taxAmount,
  452. "amount_without_tax": amountWithoutTax,
  453. "remark": "医疗发票",
  454. }
  455. ////项目商品明细
  456. items := make([]map[string]interface{}, 0)
  457. for _, ct := range cts {
  458. item := make(map[string]interface{})
  459. amountWithoutTax, _, taxAmount, _ := CalculatePriceDetails(ct.price, 1, 0.06)
  460. item["name"] = ct.name
  461. item["tax_code"] = "3070202000000000000"
  462. item["models"] = ""
  463. item["unit"] = ""
  464. item["total_price"] = amountWithoutTax
  465. item["total"] = "1"
  466. item["price"] = amountWithoutTax
  467. item["tax_rate"] = "0.06"
  468. item["tax_amount"] = taxAmount
  469. item["discount"] = "0"
  470. item["preferential_policy_flag"] = ""
  471. item["zero_tax_flag"] = ""
  472. item["vat_special_management"] = ""
  473. items = append(items, item)
  474. }
  475. postData["items"] = items
  476. fmt.Println("postData")
  477. fmt.Println(postData)
  478. sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
  479. routerAddress, postData := fapiao.Blue(postData) //发票开具
  480. r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
  481. fmt.Println("blue")
  482. fmt.Println(string(r))
  483. if err != nil {
  484. fmt.Println(err)
  485. } else {
  486. var resp OpenFaPiaoResultResponse
  487. // 将 byte 切片转换为结构体
  488. err := json.Unmarshal(r, &resp)
  489. fmt.Println(resp)
  490. if err != nil {
  491. fmt.Println("Error unmarshalling:", err)
  492. } else {
  493. fmt.Println(resp)
  494. if resp.Code == 0 {
  495. //开具蓝票成功,请求查询接口,获取发票相关数据
  496. routerAddress2, postData2 := fapiao.Query(config2.SellerTaxpayerNum, resp.Data.OrderSn, number)
  497. r3, err2 := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress2, postData2)
  498. fmt.Println("query")
  499. fmt.Println(string(r3))
  500. if err2 != nil {
  501. fmt.Println(err2)
  502. } else {
  503. var resp3 QueryFaPiaoResultResponse
  504. // 将 byte 切片转换为结构体
  505. json.Unmarshal(r3, &resp3)
  506. if resp3.Code == 0 {
  507. var fapiao models.HisFaPiaoOrder
  508. fapiao.InvoiceId = resp.Data.InvoiceId
  509. fapiao.OrderSn = resp.Data.OrderSn
  510. fapiao.TicketSn = resp3.Data.TicketSn
  511. fapiao.TicketDate = resp3.Data.TicketDate
  512. fapiao.AmountWithTax = resp3.Data.AmountWithoutTax
  513. fapiao.AmountWithoutTax = resp3.Data.AmountWithoutTax
  514. fapiao.TaxAmount = resp3.Data.TaxAmount
  515. fapiao.IsRedWashed = strconv.FormatInt(int64(resp3.Data.IsRedWashed), 10)
  516. fapiao.PdfUrl = resp3.Data.PdfUrl
  517. fapiao.OfdUrl = resp3.Data.OfdUrl
  518. fapiao.XmlUrl = resp3.Data.XmlUrl
  519. fapiao.FapiaoStatus = "1"
  520. fapiao.OrderIds = order_ids
  521. fapiao.UserOrgId = c.GetAdminUserInfo().CurrentOrgId
  522. fapiao.Status = 1
  523. fapiao.PatientId = orders[0].PatientId
  524. fapiao.Ctime = time.Now().Unix()
  525. fapiao.Mtime = time.Now().Unix()
  526. fapiao.Creator = role.UserName
  527. fapiao.MedfeeSumamt = MedfeeSumamt
  528. fapiao.FundPaySumamt = FundPaySumamt
  529. fapiao.PsnCashPay = PsnCashPay
  530. err5 := service.SaveFaPiaoOrder(fapiao)
  531. fmt.Println(err5)
  532. if err5 == nil {
  533. service.UpdateFaPiaoNumber(resp3.Data.TicketSn, ids) //同步发票号码
  534. c.ServeSuccessJSON(map[string]interface{}{
  535. "msg": "开具成功",
  536. })
  537. }
  538. }
  539. }
  540. }
  541. }
  542. }
  543. }
  544. func (c *FapiaoApiController) RedFaPiao() {
  545. ////1.开发发票前先检查是否已经登录到税局和已经实名认证
  546. //status := GetQRStatus(c.GetAdminUserInfo().CurrentOrgId)
  547. //if status == "REAL_AUTH_SUCCESS" { //实人认证成功
  548. // GetQRStatus(c.GetAdminUserInfo().CurrentOrgId)
  549. // sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
  550. // var config models.FapiaoConfig
  551. // config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
  552. //
  553. // routerAddress, postData := fapiao.Red() //发票开具
  554. // _, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
  555. // if err != nil {
  556. // fmt.Println(err)
  557. // } else {
  558. //
  559. // }
  560. //}
  561. //order_ids := c.GetString("order_ids")
  562. id, _ := c.GetInt64("id")
  563. admin_user_id, _ := c.GetInt64("admin_user_id")
  564. role2, _ := service.GetAdminUserRole(admin_user_id, c.GetAdminUserInfo().CurrentOrgId)
  565. fapiao_config, _ := service.GetFaPiaoOrderById(id)
  566. var config models.FapiaoConfig
  567. config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
  568. sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
  569. routerAddress, postData := fapiao.Red(config.SellerTaxpayerNum, "", fapiao_config.OrderSn) //发票开具
  570. fmt.Println("postData")
  571. fmt.Println(postData)
  572. fmt.Println("postData")
  573. red, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
  574. fmt.Println("red")
  575. fmt.Println(red)
  576. fmt.Println("red")
  577. if err != nil {
  578. fmt.Println(err)
  579. } else {
  580. var resp RedResult
  581. // 将 byte 切片转换为结构体
  582. json.Unmarshal(red, &resp)
  583. fmt.Println("resp")
  584. fmt.Println(resp)
  585. fmt.Println("resp")
  586. if resp.Code == 0 {
  587. if resp.Data[0].State == 1 {
  588. //查询红票开具情况
  589. routerAddress2, postData2 := fapiao.Query(config.SellerTaxpayerNum, fapiao_config.OrderSn, "")
  590. r3, _ := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress2, postData2)
  591. var resp3 QueryFaPiaoResultResponse
  592. // 将 byte 切片转换为结构体
  593. json.Unmarshal(r3, &resp3)
  594. fmt.Println("resp")
  595. fmt.Println(string(r3))
  596. fmt.Println(resp3)
  597. fmt.Println("resp")
  598. if resp3.Code == 0 {
  599. if resp3.Data.IsRedWashed == 1 {
  600. fapiao_config.IsRedWashed = "1"
  601. fapiao_config.Status = 0
  602. fapiao_config.RedInvoiceId = resp.Data[0].InvoiceId
  603. fapiao_config.RedInvoiceCreator = role2.UserName
  604. service.SaveFaPiaoOrder(fapiao_config)
  605. //将结算表的发票号码清空
  606. service.UpdateFaPiaoNumberByNumber(fapiao_config.TicketSn)
  607. c.ServeSuccessJSON(map[string]interface{}{
  608. "msg": "红冲成功",
  609. })
  610. } else {
  611. c.ServeSuccessJSON(map[string]interface{}{
  612. "msg": "红冲失败",
  613. })
  614. }
  615. } else {
  616. c.ServeSuccessJSON(map[string]interface{}{
  617. "msg": "红冲失败",
  618. })
  619. }
  620. } else {
  621. c.ServeSuccessJSON(map[string]interface{}{
  622. "msg": "红冲失败",
  623. })
  624. }
  625. } else {
  626. c.ServeSuccessJSON(map[string]interface{}{
  627. "msg": "红冲失败",
  628. })
  629. }
  630. }
  631. }
  632. type RedResult struct {
  633. Code int `json:"code"`
  634. Data []struct {
  635. State int `json:"state"`
  636. Message string `json:"message"`
  637. OrderSn string `json:"order_sn"`
  638. InvoiceId string `json:"invoice_id"`
  639. } `json:"data"`
  640. Message string `json:"message"`
  641. }
  642. type QueryFaPiaoResultResponse struct {
  643. Code int `json:"code"`
  644. Data struct {
  645. OrderSn string `json:"order_sn"`
  646. Status int `json:"status"`
  647. Message string `json:"message"`
  648. TicketDate string `json:"ticket_date"`
  649. TicketSn string `json:"ticket_sn"`
  650. TicketCode string `json:"ticket_code"`
  651. CheckCode string `json:"check_code"`
  652. AmountWithTax string `json:"amount_with_tax"`
  653. AmountWithoutTax string `json:"amount_without_tax"`
  654. TaxAmount string `json:"tax_amount"`
  655. IsRedWashed int `json:"is_red_washed"`
  656. PdfUrl string `json:"pdf_url"`
  657. OfdUrl string `json:"ofd_url"`
  658. XmlUrl string `json:"xml_url"`
  659. } `json:"data"`
  660. Message string `json:"message"`
  661. }
  662. type OpenFaPiaoResultResponse struct {
  663. Code int `json:"code"`
  664. Message string `json:"message"`
  665. Data struct {
  666. State int `json:"state"`
  667. OrderSn string `json:"order_sn"`
  668. InvoiceId string `json:"invoice_id"`
  669. } `json:"data"`
  670. }
  671. type SurplusStockResponse struct {
  672. Code int `json:"code"`
  673. Message string `json:"message"`
  674. Data struct {
  675. LeftQuantity int `json:"left_quantity"`
  676. } `json:"data"`
  677. }
  678. func GetFaPiaoStock(org_id int64) (left_quantity int) {
  679. sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
  680. var config models.FapiaoConfig
  681. config, _ = service.FindFaPiaoConfigInfo(org_id)
  682. routerAddress, postData := fapiao.QueryStock(config)
  683. r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
  684. if err != nil {
  685. fmt.Println(err)
  686. } else {
  687. var resp SurplusStockResponse
  688. // 将 byte 切片转换为结构体
  689. err := json.Unmarshal(r, &resp)
  690. if err != nil {
  691. fmt.Println("Error unmarshalling:", err)
  692. } else {
  693. if resp.Code == 0 {
  694. left_quantity = resp.Data.LeftQuantity
  695. }
  696. }
  697. }
  698. return
  699. }
  700. type Response struct {
  701. Code int `json:"code"`
  702. Message string `json:"message"`
  703. Data struct {
  704. Status string `json:"status"`
  705. } `json:"data"`
  706. }
  707. func GetQRStatus(org_id int64) (status string) {
  708. sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
  709. fmt.Println(sdk)
  710. var config models.FapiaoConfig
  711. config, _ = service.FindFaPiaoConfigInfo(org_id)
  712. fmt.Println(config)
  713. routerAddress, postData := fapiao.GetQRStatus("", config) //发票开具
  714. r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
  715. if err != nil {
  716. status = "FAILD"
  717. fmt.Println(err)
  718. } else {
  719. fmt.Println(r)
  720. var resp Response
  721. // 将 byte 切片转换为结构体
  722. err := json.Unmarshal(r, &resp)
  723. if err != nil {
  724. status = "FAILD"
  725. fmt.Println("Error unmarshalling:", err)
  726. } else {
  727. status = resp.Data.Status
  728. fmt.Printf("Parsed struct: %+v\n", resp)
  729. }
  730. }
  731. return status
  732. //return
  733. }
  734. // 计算商品价格、税额等函数
  735. func CalculatePriceDetails(totalCost float64, itemCount int, taxRate float64) (string, string, string, string) {
  736. // 商品不含税总金额,保留两位小数
  737. amountWithoutTax := roundTo(totalCost/(1+taxRate), 2)
  738. // 商品不含税单价,保留八位小数
  739. pricePerItem := roundTo(amountWithoutTax/float64(itemCount), 8)
  740. // 税额,保留两位小数
  741. taxAmount := roundTo(amountWithoutTax*taxRate, 2)
  742. // 含税总金额
  743. amountHasTax := amountWithoutTax + taxAmount
  744. return fmt.Sprintf("%f", amountWithoutTax), fmt.Sprintf("%f", pricePerItem), fmt.Sprintf("%f", taxAmount), fmt.Sprintf("%f", amountHasTax)
  745. }
  746. // 保留指定小数位数的函数
  747. func roundTo(value float64, places int) float64 {
  748. scale := math.Pow(10, float64(places))
  749. return math.Round(value*scale) / scale
  750. }