Bladeren bron

提交代码

陈少旭 2 maanden geleden
bovenliggende
commit
157f66d66f
10 gewijzigde bestanden met toevoegingen van 895 en 128 verwijderingen
  1. 41 0
      common/crypto.go
  2. 23 0
      common/json.go
  3. 27 0
      common/rand.go
  4. 645 33
      controllers/fapiao_controller.go
  5. 88 0
      invoice/sdk.go
  6. 26 23
      models/fapiao.go
  7. 2 59
      service/fapiao/bule.go
  8. 4 4
      service/fapiao/query.go
  9. 6 5
      service/fapiao/red.go
  10. 33 4
      service/fapiao_service.go

+ 41 - 0
common/crypto.go Bestand weergeven

@@ -0,0 +1,41 @@
1
+package common
2
+
3
+import (
4
+	"crypto/hmac"
5
+	"crypto/sha256"
6
+)
7
+
8
+const (
9
+	// HMAC签名算法
10
+	HMAC_SHA256 = "HMAC-SHA256"
11
+)
12
+
13
+// HMAC_Sha256 加密
14
+func HMAC_Sha256(data string, secret string) []byte {
15
+	h := hmac.New(sha256.New, []byte(secret))
16
+	h.Write([]byte(data))
17
+	return h.Sum(nil)
18
+}
19
+
20
+// RSASHA256 加密
21
+// func RSASHA256(data string, Key string) (string, error) {
22
+// 	h := sha256.New()
23
+// 	h.Write([]byte(data))
24
+// 	hashed := h.Sum(nil)
25
+// 	block, _ := pem.Decode([]byte(Key))
26
+// 	if block == nil {
27
+// 		return "", errors.New("private key error")
28
+// 	}
29
+
30
+// 	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
31
+// 	if err != nil {
32
+// 		return "", err
33
+// 	}
34
+
35
+// 	signature, err := rsa.SignPKCS1v15(cryptorand.Reader, privateKey, crypto.SHA256, hashed)
36
+// 	if err != nil {
37
+// 		return "", err
38
+// 	}
39
+
40
+// 	return base64.StdEncoding.EncodeToString(signature), nil
41
+// }

+ 23 - 0
common/json.go Bestand weergeven

@@ -0,0 +1,23 @@
1
+package common
2
+
3
+import (
4
+	"encoding/json"
5
+)
6
+
7
+func GetPostDataWithMap(post map[string]interface{}) (string, error) {
8
+	//json := jsoniter.Config{
9
+	//	MarshalFloatWith6Digits: true,
10
+	//	EscapeHTML:              false,
11
+	//	SortMapKeys:             true, //本身高灯平台仅要求对最外层json key进行asci码升序排序,但map是无序且随机的,所以签名和post数据均排序以保持一致
12
+	//	UseNumber:               true,
13
+	//	DisallowUnknownFields:   false,
14
+	//	CaseSensitive:           true,
15
+	//}.Froze()
16
+
17
+	s, err := json.Marshal(&post)
18
+	if err != nil {
19
+		return "", err
20
+	}
21
+
22
+	return string(s), nil
23
+}

+ 27 - 0
common/rand.go Bestand weergeven

@@ -0,0 +1,27 @@
1
+package common
2
+
3
+import (
4
+	"fmt"
5
+	"math/rand"
6
+	"strings"
7
+	"time"
8
+)
9
+
10
+const (
11
+	numLen = 10 //随机序列长度
12
+)
13
+
14
+var (
15
+	numeric = [numLen]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} //随机序列
16
+)
17
+
18
+func GetRand(width int) string {
19
+	r := len(numeric)
20
+	rand.Seed(time.Now().UnixNano())
21
+
22
+	var sb strings.Builder
23
+	for i := 0; i < width; i++ {
24
+		fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
25
+	}
26
+	return sb.String()
27
+}

+ 645 - 33
controllers/fapiao_controller.go Bestand weergeven

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

+ 88 - 0
invoice/sdk.go Bestand weergeven

@@ -0,0 +1,88 @@
1
+package invoice
2
+
3
+import (
4
+	"encoding/base64"
5
+	"errors"
6
+	"io/ioutil"
7
+	"net/http"
8
+	"strconv"
9
+	"strings"
10
+	"time"
11
+
12
+	"XT_New/common"
13
+)
14
+
15
+func NewSdk(algorithm, appkey, appsecret, privateKey, env string) *Client {
16
+	return &Client{
17
+		env:        env,
18
+		appkey:     appkey,
19
+		appsecret:  appsecret,
20
+		algorithm:  algorithm,
21
+		privateKey: privateKey,
22
+	}
23
+}
24
+
25
+type Client struct {
26
+	env        string
27
+	appkey     string
28
+	appsecret  string
29
+	privateKey string
30
+	algorithm  string
31
+}
32
+
33
+func (this *Client) HttpPost(baseUrl string, routerAddress string, post map[string]interface{}) ([]byte, error) {
34
+
35
+	// 获取转换后的post字符串
36
+	postData, err := common.GetPostDataWithMap(post)
37
+	if err != nil {
38
+		return nil, err
39
+	}
40
+
41
+	timestamp := strconv.FormatInt(time.Now().Unix(), 10)                //获取时间戳
42
+	nonce := common.GetRand(6)                                           //6位随机数
43
+	auth, err := this.getAuth(routerAddress, postData, timestamp, nonce) //认证串
44
+	if err != nil {
45
+		return nil, err
46
+	}
47
+
48
+	client := &http.Client{}
49
+
50
+	reqest, err := http.NewRequest("POST", baseUrl+routerAddress, strings.NewReader((postData)))
51
+	if err != nil {
52
+		return nil, err
53
+	}
54
+
55
+	reqest.Header.Add("Authorization", auth)
56
+	reqest.Header.Add("Content-Type", "application/json")
57
+
58
+	r, err := client.Do(reqest)
59
+	if err != nil {
60
+		return nil, err
61
+	}
62
+	defer r.Body.Close()
63
+
64
+	return ioutil.ReadAll(r.Body)
65
+}
66
+
67
+// getAuth 获取授权字符串
68
+func (this *Client) getAuth(routerAddress string, postData string, timestamp string, nonce string) (string, error) {
69
+
70
+	originStr := "algorithm=" + this.algorithm + "|appkey=" + this.appkey + "|nonce=" + nonce + "|timestamp=" + timestamp + "|" + routerAddress + "|" + postData
71
+
72
+	var signs string
73
+	var err error
74
+	switch this.algorithm {
75
+	case common.HMAC_SHA256:
76
+		signs = base64.StdEncoding.EncodeToString(common.HMAC_Sha256(originStr, this.appsecret))
77
+	default:
78
+		panic(errors.New("algorithm not exists"))
79
+	}
80
+
81
+	if err != nil {
82
+		return "", err
83
+	}
84
+
85
+	auth := "algorithm=" + this.algorithm + ",appkey=" + this.appkey + ",nonce=" + nonce + ",timestamp=" + timestamp + ",signature=" + signs
86
+
87
+	return auth, nil
88
+}

+ 26 - 23
models/fapiao.go Bestand weergeven

@@ -61,29 +61,32 @@ func (HisOrderByFaPiao) TableName() string {
61 61
 }
62 62
 
63 63
 type HisFaPiaoOrder struct {
64
-	ID               int64   `gorm:"column:id" json:"id" form:"id"`
65
-	InvoiceId        string  `gorm:"column:invoice_id" json:"invoice_id" form:"invoice_id"`
66
-	OrderSn          string  `gorm:"column:order_sn" json:"order_sn" form:"order_sn"`
67
-	TicketSn         string  `gorm:"column:ticket_sn" json:"ticket_sn" form:"ticket_sn"`
68
-	TicketDate       string  `gorm:"column:ticket_date" json:"ticket_date" form:"ticket_date"`
69
-	AmountWithTax    string  `gorm:"column:amount_with_tax" json:"amount_with_tax" form:"amount_with_tax"`
70
-	AmountWithoutTax string  `gorm:"column:amount_without_tax" json:"amount_without_tax" form:"amount_without_tax"`
71
-	TaxAmount        string  `gorm:"column:tax_amount" json:"tax_amount" form:"tax_amount"`
72
-	IsRedWashed      string  `gorm:"column:is_red_washed" json:"is_red_washed" form:"is_red_washed"`
73
-	PdfUrl           string  `gorm:"column:pdf_url" json:"pdf_url" form:"pdf_url"`
74
-	OfdUrl           string  `gorm:"column:ofd_url" json:"ofd_url" form:"ofd_url"`
75
-	XmlUrl           string  `gorm:"column:xml_url" json:"xml_url" form:"xml_url"`
76
-	FapiaoStatus     string  `gorm:"column:fapiao_status" json:"fapiao_status" form:"fapiao_status"`
77
-	OrderIds         string  `gorm:"column:order_ids" json:"order_ids" form:"order_ids"`
78
-	UserOrgId        int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
79
-	Status           int64   `gorm:"column:status" json:"status" form:"status"`
80
-	PatientId        int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
81
-	Ctime            int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
82
-	Mtime            int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
83
-	Creator          string  `gorm:"column:creator" json:"creator" form:"creator"`
84
-	MedfeeSumamt     float64 `gorm:"column:medfee_sumamt" json:"medfee_sumamt" form:"medfee_sumamt"`
85
-	PsnCashPay       float64 `gorm:"column:psn_cash_pay" json:"psn_cash_pay" form:"psn_cash_pay"`
86
-	FundPaySumamt    float64 `gorm:"column:fund_pay_sumamt" json:"fund_pay_sumamt" form:"fund_pay_sumamt"`
64
+	ID                int64    `gorm:"column:id" json:"id" form:"id"`
65
+	InvoiceId         string   `gorm:"column:invoice_id" json:"invoice_id" form:"invoice_id"`
66
+	OrderSn           string   `gorm:"column:order_sn" json:"order_sn" form:"order_sn"`
67
+	TicketSn          string   `gorm:"column:ticket_sn" json:"ticket_sn" form:"ticket_sn"`
68
+	TicketDate        string   `gorm:"column:ticket_date" json:"ticket_date" form:"ticket_date"`
69
+	AmountWithTax     string   `gorm:"column:amount_with_tax" json:"amount_with_tax" form:"amount_with_tax"`
70
+	AmountWithoutTax  string   `gorm:"column:amount_without_tax" json:"amount_without_tax" form:"amount_without_tax"`
71
+	TaxAmount         string   `gorm:"column:tax_amount" json:"tax_amount" form:"tax_amount"`
72
+	IsRedWashed       string   `gorm:"column:is_red_washed" json:"is_red_washed" form:"is_red_washed"`
73
+	PdfUrl            string   `gorm:"column:pdf_url" json:"pdf_url" form:"pdf_url"`
74
+	OfdUrl            string   `gorm:"column:ofd_url" json:"ofd_url" form:"ofd_url"`
75
+	XmlUrl            string   `gorm:"column:xml_url" json:"xml_url" form:"xml_url"`
76
+	FapiaoStatus      string   `gorm:"column:fapiao_status" json:"fapiao_status" form:"fapiao_status"`
77
+	OrderIds          string   `gorm:"column:order_ids" json:"order_ids" form:"order_ids"`
78
+	UserOrgId         int64    `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
79
+	Status            int64    `gorm:"column:status" json:"status" form:"status"`
80
+	PatientId         int64    `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
81
+	Ctime             int64    `gorm:"column:ctime" json:"ctime" form:"ctime"`
82
+	Mtime             int64    `gorm:"column:mtime" json:"mtime" form:"mtime"`
83
+	Creator           string   `gorm:"column:creator" json:"creator" form:"creator"`
84
+	MedfeeSumamt      float64  `gorm:"column:medfee_sumamt" json:"medfee_sumamt" form:"medfee_sumamt"`
85
+	PsnCashPay        float64  `gorm:"column:psn_cash_pay" json:"psn_cash_pay" form:"psn_cash_pay"`
86
+	FundPaySumamt     float64  `gorm:"column:fund_pay_sumamt" json:"fund_pay_sumamt" form:"fund_pay_sumamt"`
87
+	RedInvoiceId      string   `gorm:"column:red_invoice_id" json:"red_invoice_id" form:"red_invoice_id"`
88
+	RedInvoiceCreator string   `gorm:"column:red_invoice_creator" json:"red_invoice_creator" form:"red_invoice_creator"`
89
+	Patients          Patients `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"patient"`
87 90
 }
88 91
 
89 92
 func (HisFaPiaoOrder) TableName() string {

+ 2 - 59
service/fapiao/bule.go Bestand weergeven

@@ -1,63 +1,6 @@
1 1
 package fapiao
2 2
 
3
-import "XT_New/models"
4
-
5
-func Blue(config models.FapiaoConfig) (routerAddress string, postData map[string]interface{}) {
6
-
7
-	routerAddress = "/tax-api/invoice/blue/v1"
8
-
9
-	postData = map[string]interface{}{
10
-		"seller_name":          "wkbb invoice blue test",
11
-		"seller_taxpayer_num":  "your seller_taxpayer_num",
12
-		"seller_address":       "",
13
-		"seller_tel":           "",
14
-		"seller_bank_name":     "",
15
-		"seller_bank_account":  "",
16
-		"title_type":           1,
17
-		"buyer_title":          "海南高灯科技",
18
-		"buyer_taxpayer_num":   "",
19
-		"buyer_address":        "",
20
-		"buyer_bank_name":      "",
21
-		"buyer_bank_account":   "",
22
-		"buyer_phone":          "",
23
-		"buyer_email":          "",
24
-		"taker_phone":          "",
25
-		"order_id":             "fc5fec2d1b6942658c009a151d4cffa5",
26
-		"invoice_type_code":    "032",
27
-		"callback_url":         "http://www.test.com",
28
-		"drawer":               "TEST",
29
-		"payee":                "TEST",
30
-		"checker":              "TEST",
31
-		"terminal_code":        "661234567789",
32
-		"user_openid":          "ba9ea0bdfa1f460993c990564caab18f",
33
-		"special_invoice_kind": "",
34
-		"zsfs":                 "",
35
-		"deduction":            "",
36
-		"amount_has_tax":       "66.66",
37
-		"tax_amount":           "66.66",
38
-		"amount_without_tax":   "66.66",
39
-		"remark":               "readme",
40
-	}
41
-
42
-	//项目商品明细
43
-	items := make([]map[string]interface{}, 1)
44
-	item := make(map[string]interface{})
45
-	item["name"] = "海鲜真划算"
46
-	item["tax_code"] = "your tax_code"
47
-	item["models"] = "zyx"
48
-	item["unit"] = "个"
49
-	item["total_price"] = "66.66"
50
-	item["total"] = "5"
51
-	item["price"] = "17.22"
52
-	item["tax_rate"] = "66.66"
53
-	item["tax_amount"] = "66.66"
54
-	item["discount"] = "66.66"
55
-	item["preferential_policy_flag"] = "0"
56
-	item["zero_tax_flag"] = "0"
57
-	item["vat_special_management"] = ""
58
-	items[0] = item
59
-
60
-	postData["items"] = items
61
-
3
+func Blue(postData map[string]interface{}) (string, map[string]interface{}) {
4
+	routerAddress := "/tax-api/invoice/blue/v1"
62 5
 	return routerAddress, postData
63 6
 }

+ 4 - 4
service/fapiao/query.go Bestand weergeven

@@ -2,14 +2,14 @@ package fapiao
2 2
 
3 3
 import "XT_New/models"
4 4
 
5
-func Query() (routerAddress string, postData map[string]interface{}) {
5
+func Query(seller_taxpayer_num string, order_sn string, order_id string) (routerAddress string, postData map[string]interface{}) {
6 6
 
7 7
 	routerAddress = "/tax-api/invoice/query/v1"
8 8
 
9 9
 	postData = map[string]interface{}{
10
-		"seller_taxpayer_num": "500102010004038",
11
-		"order_sn":            "",
12
-		"order_id":            "gp_20190828115454_742_11296_31131",
10
+		"seller_taxpayer_num": seller_taxpayer_num,
11
+		"order_sn":            order_sn,
12
+		"order_id":            order_id,
13 13
 		"is_red":              0,
14 14
 	}
15 15
 

+ 6 - 5
service/fapiao/red.go Bestand weergeven

@@ -1,15 +1,16 @@
1 1
 package fapiao
2 2
 
3
-func Red() (routerAddress string, postData map[string]interface{}) {
3
+func Red(seller_taxpayer_num string, callback_url string, order_sn string) (routerAddress string, postData map[string]interface{}) {
4 4
 
5
-	routerAddress = "/tax-api/invoice/red/v1"
5
+	routerAddress = "/tax-api/invoice/red/quick/v1"
6 6
 
7 7
 	invoices := make([]map[string]interface{}, 1)
8 8
 
9 9
 	invoice := make(map[string]interface{})
10
-	invoice["seller_taxpayer_num"] = "111112222233333"
11
-	invoice["callback_url"] = "http://test.feehi.com/sign/mock/invoice-callback.php"
12
-	invoice["order_sn"] = "6555407740980870214"
10
+	invoice["seller_taxpayer_num"] = seller_taxpayer_num
11
+	invoice["callback_url"] = callback_url
12
+	invoice["order_sn"] = order_sn
13
+	invoice["apply_reason"] = "2"
13 14
 
14 15
 	invoices[0] = invoice
15 16
 

+ 33 - 4
service/fapiao_service.go Bestand weergeven

@@ -69,12 +69,11 @@ func GetFaPiaoSettleList(user_org_id int64, page int64, limit int64, start_time_
69 69
 	return
70 70
 }
71 71
 
72
-func GetFaPiaoList(user_org_id int64, page int64, limit int64, start_time_timestamp int64, end_time_timestamp int64) (order []*models.HisOrder, err error, total int64) {
72
+func GetFaPiaoList(user_org_id int64, page int64, limit int64, start_time_timestamp int64, end_time_timestamp int64) (order []*models.HisFaPiaoOrder, err error, total int64) {
73 73
 	offset := (page - 1) * limit
74 74
 	db := readDb.Model(&models.HisFaPiaoOrder{})
75
-	db = db.Preload("Patients", "status = 1 AND user_org_id = ?", user_org_id).
76
-		Preload("HisFaPiaoOrder", "status = 1")
77
-	db = db.Where("ctime >= ? and ctime <= ? and user_org_id = ?", start_time_timestamp, end_time_timestamp, user_org_id)
75
+	db = db.Preload("Patients", "status = 1 AND user_org_id = ?", user_org_id)
76
+	db = db.Where("ctime >= ? and ctime <= ? and user_org_id = ? and status = 1", start_time_timestamp, end_time_timestamp, user_org_id)
78 77
 	// Count the total number of records
79 78
 	db = db.Count(&total)
80 79
 	// Apply pagination
@@ -83,3 +82,33 @@ func GetFaPiaoList(user_org_id int64, page int64, limit int64, start_time_timest
83 82
 	err = db.Find(&order).Error
84 83
 	return
85 84
 }
85
+
86
+func GetFaPiaoOrderByIDS(ids []string) (orders []models.HisOrder, err error) {
87
+	err = readDb.Model(&models.HisOrder{}).Where("id in (?) AND status = 1", ids).Find(&orders).Error
88
+	return
89
+}
90
+
91
+func GetFaPiaoOrderById(id int64) (orders models.HisFaPiaoOrder, err error) {
92
+	err = readDb.Model(&models.HisFaPiaoOrder{}).Where("id = ?", id).Find(&orders).Error
93
+	return
94
+}
95
+
96
+func GetFaPiaoOrderInfoByNumbers(numbers []string) (infos []models.HisOrderInfo, err error) {
97
+	err = readDb.Model(&models.HisOrderInfo{}).Where("order_number in (?)", numbers).Find(&infos).Error
98
+	return
99
+}
100
+
101
+func SaveFaPiaoOrder(fapiao models.HisFaPiaoOrder) (err error) {
102
+	err = writeDb.Save(&fapiao).Error
103
+	return
104
+}
105
+
106
+func UpdateFaPiaoNumber(number string, ids []string) (err error) {
107
+	err = XTWriteDB().Model(&models.HisOrder{}).Where("id in (?)", ids).Updates(map[string]interface{}{"fa_piao_number": number}).Error
108
+	return
109
+}
110
+
111
+func UpdateFaPiaoNumberByNumber(number string) (err error) {
112
+	err = XTWriteDB().Model(&models.HisOrder{}).Where("fa_piao_number = ?", number).Updates(map[string]interface{}{"fa_piao_number": ""}).Error
113
+	return
114
+}