浏览代码

fix:换票功能修改

duxin 1 年之前
父节点
当前提交
7a26a4be9d
共有 1 个文件被更改,包括 360 次插入134 次删除
  1. 360 134
      src/jfw/modules/subscribepay/src/service/invoice.go

+ 360 - 134
src/jfw/modules/subscribepay/src/service/invoice.go

@@ -13,6 +13,7 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
+	"github.com/google/uuid"
 	"io/ioutil"
 	"jy/src/jfw/modules/subscribepay/src/config"
 	"jy/src/jfw/modules/subscribepay/src/util"
@@ -26,16 +27,16 @@ import (
 
 type Invoice struct {
 	*xweb.Action
-	addinvoice      xweb.Mapper `xweb:"/invoice/add"`       //开发票
-	showinvoice     xweb.Mapper `xweb:"/invoice/show"`      //查看发票
-	callbackinvoice xweb.Mapper `xweb:"/invoice/callback"`  //开发票回调
-	replaceinvoice  xweb.Mapper `xweb:"/invoice/replace"`   //换发票
-	refundinvoice   xweb.Mapper `xweb:"/invoice/refund"`    //退票
-	invoiceinfo     xweb.Mapper `xweb:"/invoice/info"`      //订单详情数据
-	available       xweb.Mapper `xweb:"/invoice/available"` //是否可用开发票
-	invoiceswitch   xweb.Mapper `xweb:"/invoice/switch"`    //发票开关
-	invoiceQuery    xweb.Mapper `xweb:"/invoice/query"`     //发票信息查询
-	invoiceSubmit   xweb.Mapper `xweb:"/invoice/submit"`    //发票信息提交
+	addinvoice        xweb.Mapper `xweb:"/invoice/add"`       //开发票
+	showinvoice       xweb.Mapper `xweb:"/invoice/show"`      //查看发票
+	callbackinvoice   xweb.Mapper `xweb:"/invoice/callback"`  //开发票回调
+	newReplaceinvoice xweb.Mapper `xweb:"/invoice/replace"`   //换发票
+	refundinvoice     xweb.Mapper `xweb:"/invoice/refund"`    //退票
+	invoiceinfo       xweb.Mapper `xweb:"/invoice/info"`      //订单详情数据
+	available         xweb.Mapper `xweb:"/invoice/available"` //是否可用开发票
+	invoiceswitch     xweb.Mapper `xweb:"/invoice/switch"`    //发票开关
+	invoiceQuery      xweb.Mapper `xweb:"/invoice/query"`     //发票信息查询
+	invoiceSubmit     xweb.Mapper `xweb:"/invoice/submit"`    //发票信息提交
 }
 
 var dbname = "invoice"
@@ -193,6 +194,10 @@ func (this *Invoice) Addinvoice() error {
 	phone_num := this.GetString("phone_num")
 	code := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
 	isSys, _ := this.GetBool("isSys")
+	newPrice, _ := this.GetFloat("price")
+	if newPrice <= 0 {
+		return errors.New("金额不能为0")
+	}
 	jsonData := ReturnJson{}
 	invoice_status := -1   //发票表开票失败
 	updata_status := false //更新表状态
@@ -204,139 +209,152 @@ func (this *Invoice) Addinvoice() error {
 		u := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId, "applyBill_status": map[string]interface{}{"ne": 2}}, "order_money,product_type,order_channel,pay_way,pay_money,is_backstage_order,billingMode", "")
 		if u != nil {
 			//后端代用户下单支持开票 order_channel = xdqd04
-			if qutil.IntAll((*u)["billingMode"]) == 1 && (qutil.IntAll((*u)["is_backstage_order"]) != 1 || qutil.InterfaceToStr((*u)["order_channel"]) == "xdqd04") {
-				var prices float64
-				//公对公转账 账单金额可以修改 开发票应取实付金额 pay_money
-				//微信支付宝支付 pay_money为订单金额减去微信or支付包红包
-				if qutil.ObjToString((*u)["pay_way"]) == "transferAccounts" {
-					prices = qutil.Float64All((*u)["pay_money"]) / float64(100)
-				} else {
-					prices = qutil.Float64All((*u)["order_money"]) / float64(100)
-				}
-				price = strconv.FormatFloat(prices, 'f', -1, 64)
-				product_name = (*u)["product_type"].(string)
-				applyBill_status = 1
-				data := make(map[string]interface{})
-				dataexport_data := make(map[string]interface{})
-				dataexport_data["applyBill_status"] = applyBill_status
-				if applyBill_type == "个人" {
-					dataexport_data["applyBill_type"] = 0
-					data["taxpayer_identnum"] = ""
-					data["company_name"] = ""
-					dataexport_data["applyBill_taxnum"] = ""
-					dataexport_data["applybill_company"] = ""
-				} else {
-					data["taxpayer_identnum"] = code
-					data["company_name"] = applyBill_company
-					dataexport_data["applyBill_taxnum"] = code
-					dataexport_data["applybill_company"] = applyBill_company
-					dataexport_data["applyBill_type"] = 1
-				}
-				dataexport_data["user_mail"] = my_email
-				data["product_type"] = product_name
-				data["order_code"] = order_code
-				data["mail"] = my_email
-				data["phone"] = phone_num
-				data["invoice_type"] = applyBill_type
-				data["invoice_changed"] = 0
-				data["create_time"] = time.Now().Unix()
-				data["user_id"] = userId
-				data["invoice_status"] = 0
-				data["invoice_money"] = price
-				var orders = []map[string]interface{}{}
-				var items = []map[string]interface{}{}
-				item := map[string]interface{}{
-					"name":        product_name,
-					"code":        config.InvoiceConfig.Code,
-					"yhzcbs":      config.InvoiceConfig.Tax_policy,
-					"lineType":    config.InvoiceConfig.Invoice_nature,
-					"taxRate":     config.InvoiceConfig.Tax_rate,
-					"taxPrice":    price,
-					"totalAmount": price,
-					"quantity":    "1",
+			//if qutil.IntAll((*u)["billingMode"]) == 1 && (qutil.IntAll((*u)["is_backstage_order"]) != 1 || qutil.InterfaceToStr((*u)["order_channel"]) == "xdqd04") {
+			//获取此订单开票中与已开票的订单金额
+			var (
+				oldPrices, prices float64
+			)
+			oldData := util.Mysql.SelectBySql(fmt.Sprintf(`SELECT SUM(invoice_money) as invoice_money FROM %s WHERE order_code = '%s' and user_id = '%s'  and invoice_status in (0,1)`, dbname, order_code, userId))
+			if oldData != nil && len(*oldData) > 0 {
+				oldPrices = qutil.Float64All((*oldData)[0]["invoice_money"])
+			}
+			//公对公转账 账单金额可以修改 开发票应取实付金额 pay_money
+			//微信支付宝支付 pay_money为订单金额减去微信or支付包红包
+			if qutil.ObjToString((*u)["pay_way"]) == "transferAccounts" {
+				prices = qutil.Float64All((*u)["pay_money"]) / float64(100)
+			} else {
+				prices = qutil.Float64All((*u)["order_money"]) / float64(100)
+			}
+			if prices < oldPrices+newPrice {
+				log.Println("开票金额已查出订单实际金额")
+				jsonData["invoice_status"] = -3
+				this.ServeJson(jsonData)
+				return nil
+			}
+			price = strconv.FormatFloat(newPrice, 'f', -1, 64)
+			product_name = (*u)["product_type"].(string)
+			applyBill_status = 1
+			data := make(map[string]interface{})
+			dataexport_data := make(map[string]interface{})
+			dataexport_data["applyBill_status"] = applyBill_status
+			if applyBill_type == "个人" {
+				dataexport_data["applyBill_type"] = 0
+				data["taxpayer_identnum"] = ""
+				data["company_name"] = ""
+				dataexport_data["applyBill_taxnum"] = ""
+				dataexport_data["applybill_company"] = ""
+			} else {
+				data["taxpayer_identnum"] = code
+				data["company_name"] = applyBill_company
+				dataexport_data["applyBill_taxnum"] = code
+				dataexport_data["applybill_company"] = applyBill_company
+				dataexport_data["applyBill_type"] = 1
+			}
+			dataexport_data["user_mail"] = my_email
+			data["product_type"] = product_name
+			data["order_code"] = order_code
+			data["mail"] = my_email
+			data["phone"] = phone_num
+			data["invoice_type"] = applyBill_type
+			data["invoice_changed"] = 0
+			data["create_time"] = time.Now().Unix()
+			data["user_id"] = userId
+			data["invoice_status"] = 0
+			data["invoice_money"] = price
+			var orders = []map[string]interface{}{}
+			var items = []map[string]interface{}{}
+			item := map[string]interface{}{
+				"name":        product_name,
+				"code":        config.InvoiceConfig.Code,
+				"yhzcbs":      config.InvoiceConfig.Tax_policy,
+				"lineType":    config.InvoiceConfig.Invoice_nature,
+				"taxRate":     config.InvoiceConfig.Tax_rate,
+				"taxPrice":    price,
+				"totalAmount": price,
+				"quantity":    "1",
+			}
+			items = append(items, item)
+			order := map[string]interface{}{
+				"billNo": order_code,
+				"items":  items,
+			}
+			orders = append(orders, order)
+			client := &http.Client{}
+			body := map[string]interface{}{
+				"Swno":      order_code,
+				"custType":  "03",
+				"orders":    orders,
+				"custTaxNo": code,
+				"phone":     phone_num,
+				"billDate":  NowFormat(Date_Full_Layout), //单据日期  格式:yyyy-MM-dd HH:mm:ss
+			}
+
+			if applyBill_type == "单位" {
+				body["custName"] = applyBill_company
+			} else {
+				body["custName"] = applyBill_type
+			}
+			//发送请求之前插入数据,防止请求时间过长
+			if !isSys {
+				status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
+				if len(*status) > 0 {
+					return nil
 				}
-				items = append(items, item)
-				order := map[string]interface{}{
-					"billNo": order_code,
-					"items":  items,
+				if i := util.Mysql.Insert(dbname, data); i > 0 {
+					invoice_status = 0
 				}
-				orders = append(orders, order)
-				client := &http.Client{}
-				body := map[string]interface{}{
-					"Swno":      order_code,
-					"custType":  "03",
-					"orders":    orders,
-					"custTaxNo": code,
-					"phone":     phone_num,
-					"billDate":  NowFormat(Date_Full_Layout), //单据日期  格式:yyyy-MM-dd HH:mm:ss
+				if !util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId}, dataexport_data) {
+					invoice_status = -1
 				}
-
-				if applyBill_type == "单位" {
-					body["custName"] = applyBill_company
-				} else {
-					body["custName"] = applyBill_type
+			} else {
+				if ok := util.Mysql.Update(dbname, map[string]interface{}{
+					"order_code":      order_code,
+					"user_id":         userId,
+					"invoice_changed": 0,
+				}, data); ok {
+					invoice_status = 0
 				}
-				//发送请求之前插入数据,防止请求时间过长
-				if !isSys {
-					status := util.Mysql.Find(dbname, map[string]interface{}{"order_code": order_code, "user_id": userId}, "", "create_time", 0, 0)
-					if len(*status) > 0 {
-						return nil
-					}
-					if i := util.Mysql.Insert(dbname, data); i > 0 {
-						invoice_status = 0
-					}
-					if !util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": order_code, "user_id": userId}, dataexport_data) {
+			}
+			if config.InvoiceConfig.Third_party_switch {
+				b, _ := json.Marshal(body)
+				buffer := bytes.NewBuffer(b)
+				request, _ := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/Add", buffer)
+				response, err := client.Do(request)
+				if err == nil {
+					res, err := ioutil.ReadAll(response.Body)
+					if err != nil {
 						invoice_status = -1
-					}
-				} else {
-					if ok := util.Mysql.Update(dbname, map[string]interface{}{
-						"order_code":      order_code,
-						"user_id":         userId,
-						"invoice_changed": 0,
-					}, data); ok {
-						invoice_status = 0
-					}
-				}
-				if config.InvoiceConfig.Third_party_switch {
-					b, _ := json.Marshal(body)
-					buffer := bytes.NewBuffer(b)
-					request, _ := http.NewRequest("POST", config.InvoiceConfig.Invoice_interface_address+"/Invoice/Add", buffer)
-					response, err := client.Do(request)
-					if err == nil {
-						res, err := ioutil.ReadAll(response.Body)
-						if err != nil {
-							invoice_status = -1
-						} else {
-							resMap := qutil.ObjToMap(string(res))
-							if *resMap != nil {
-								if qutil.IntAll((*resMap)["code"]) == 0 { //开票成功
-									invoice_status = 1
-									jsonData["invoice_status"] = invoice_status
-								} else if qutil.IntAll((*resMap)["code"]) == 2 { //开票中
-									// log.Println("开票中")
-									invoice_status = 0
-									jsonData["invoice_status"] = invoice_status
-								} else { //开票失败
-									// log.Println("开票失败")
-									invoice_status = -1
-									jsonData["invoice_status"] = invoice_status
-								}
-							}
-							defer response.Body.Close()
-							resData := (*resMap)["data"].(map[string]interface{})
-							update_status := util.Mysql.Update(dbname, map[string]interface{}{"order_code": order_code}, map[string]interface{}{
-								"invoice_serialnum": resData["swno"],
-								"invoice_code":      resData["fpdm"],
-								"invoice_number":    resData["fphm"],
-								"url":               resData["path"],
-								"invoice_status":    invoice_status,
-							})
-							if !update_status {
-								log.Println("order_ocde:", order_code+"update fail")
+					} else {
+						resMap := qutil.ObjToMap(string(res))
+						if *resMap != nil {
+							if qutil.IntAll((*resMap)["code"]) == 0 { //开票成功
+								invoice_status = 1
+								jsonData["invoice_status"] = invoice_status
+							} else if qutil.IntAll((*resMap)["code"]) == 2 { //开票中
+								// log.Println("开票中")
+								invoice_status = 0
+								jsonData["invoice_status"] = invoice_status
+							} else { //开票失败
+								// log.Println("开票失败")
+								invoice_status = -1
+								jsonData["invoice_status"] = invoice_status
 							}
 						}
+						defer response.Body.Close()
+						resData := (*resMap)["data"].(map[string]interface{})
+						update_status := util.Mysql.Update(dbname, map[string]interface{}{"order_code": order_code}, map[string]interface{}{
+							"invoice_serialnum": resData["swno"],
+							"invoice_code":      resData["fpdm"],
+							"invoice_number":    resData["fphm"],
+							"url":               resData["path"],
+							"invoice_status":    invoice_status,
+						})
+						if !update_status {
+							log.Println("order_ocde:", order_code+"update fail")
+						}
 					}
 				}
+				//}
 			}
 		} else {
 			if invoice_status != 1 {
@@ -440,6 +458,61 @@ func (this *Invoice) Showinvoice() {
 
 }
 
+// 查看发票
+func (this *Invoice) ShowinvoiceList() {
+	order_code := this.GetString("order_code")
+	//红冲发票开关
+	redSwitchInfo := map[string]interface{}{
+		"ris": config.InvoiceConfig.Red_invoice_switch,
+		"rim": config.InvoiceConfig.Red_invoice_msg,
+	}
+	invoices := util.Mysql.SelectBySql(fmt.Sprintf(`SELECT * FROM invoice WHERE order_code = '%s'`, order_code))
+	if invoices != nil {
+		isIos := util.IsMobileIOS(this.Request.UserAgent())
+		var invoiceData []map[string]interface{}
+		for _, data := range *invoices {
+			delete(data, "user_id")
+			var changed bool
+			if data["only_Identifying"] != nil {
+				//查询是否换票
+				changed = util.Mysql.CountBySql(`SELECT count(*) FROM invoice   WHERE order_code = '?' and invoice_status in (0,1) and only_Identifying = ?`, order_code, data["only_Identifying"]) > 1
+			}
+			//if changed && data["invoice_status"] == 0 { //此纪录为换票中的发票
+			//	continue
+			//}
+			data["changed"] = changed
+			data["status"] = "processing"
+			if url := qutil.InterfaceToStr(data["url"]); url != "" {
+				data["status"] = "success"
+				//ios 移动端
+				if isIos {
+					//国家税务局-增值税电子发票公共服务平台
+					if strings.Contains(url, "tysl.beijing.chinatax") {
+						data["url"] = strings.ReplaceAll(url, "/preview.html?code=", "/web-reader/reader?file=")
+					}
+				}
+			}
+			invoiceData = append(invoiceData, data)
+		}
+		this.ServeJson(map[string]interface{}{
+			"invoiceData":   invoiceData,
+			"redSwitchInfo": redSwitchInfo,
+		})
+	} else {
+		data := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+			"order_code": order_code,
+		}, "order_status,applybill_status,order_code,user_mail,applybill_type,applybill_company,user_phone,applybill_taxnum", "")
+		if data != nil {
+			(*data)["status"] = "fail"
+		}
+
+		this.ServeJson(map[string]interface{}{
+			"orderData":     data,
+			"redSwitchInfo": redSwitchInfo,
+		})
+	}
+}
+
 // 开发票回调
 func (this *Invoice) Callbackinvoice() {
 	isRed, _ := this.GetBool("isRed")
@@ -1003,6 +1076,159 @@ func (this *Invoice) Replaceinvoice() {
 
 }
 
+// 新换票
+func (this *Invoice) NewReplaceinvoice() {
+	//红冲开关
+	if !config.InvoiceConfig.Red_invoice_switch {
+		this.ServeJson(map[string]interface{}{
+			"invoice_status": -1,
+			"invoice_msg":    config.InvoiceConfig.Red_invoice_msg,
+		})
+		return
+	}
+	invoice_type := this.GetString("invoice_type")
+	phone := this.GetString("phone_num")
+	e_mail := this.GetString("email")
+	company_name := this.GetString("company")
+	id_num := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
+	invoice_status := 0
+	userId := qutil.ObjToString(this.GetSession("userId"))
+	//order_code := this.GetString("order_code")
+	sid := this.GetString("sid")
+	oRes := util.Mysql.FindOne(dbname, map[string]interface{}{"id": sid, "user_id": userId, "invoie_changed": 0}, "", "") //仅线上开发票可换票
+	if oRes != nil && len(*oRes) > 0 {
+		var (
+			qSql    string
+			errCode []string
+			//saveData []map[string]interface{}
+			resArr []map[string]interface{}
+		)
+		if qutil.IntAll((*oRes)["invoice_status"]) == -2 {
+			this.ServeJson(map[string]interface{}{
+				"error_code": -1,
+				"error_msg":  "发票状态错误",
+			})
+			return
+		}
+		if invoice_order_code := qutil.InterfaceToStr((*oRes)["invoice_order_code"]); invoice_order_code == "" ||
+			len(strings.Split(invoice_order_code, ",")) <= 1 {
+			resArr = append(resArr, *oRes)
+		} else { //多订单联合开票
+			qSql = fmt.Sprintf(`SELECT * FROM invoice WHERE invoice_order_code = '%s'`, qutil.InterfaceToStr((*oRes)["invoice_order_code"]))
+			res1 := util.Mysql.SelectBySql(qSql)
+			if res1 != nil && len(*res1) > 0 {
+				resArr = *res1
+			}
+		}
+		var isMail bool
+		for _, res := range resArr {
+			newUuid := uuid.New()
+			if res["only_Identifying"] == nil { //无唯一id 允许换票一次 生成唯一id
+				res["only_Identifying"] = newUuid
+				util.Mysql.Update(dbname, map[string]interface{}{"id": res["id"]}, map[string]interface{}{"only_Identifying": newUuid})
+			}
+			data := res
+			delete(data, "id")
+			switch IsEdit(res, phone, e_mail, id_num, company_name, invoice_type) {
+			case true:
+				if util.Mysql.Count(dbname, map[string]interface{}{
+					"order_code":       res["order_code"],
+					"user_id":          userId,
+					"only_Identifying": res["only_Identifying"],
+				}) > 1 {
+					continue
+				}
+				var html string
+				if invoice_type == "个人" {
+					emailHtml := emailHtml_gr
+					emailHtmls := fmt.Sprintf(emailHtml, phone, e_mail)
+					html = fmt.Sprintf(email_format, res["order_code"], res["url"], emailHtmls)
+				} else {
+					emailHtml := emailHtml_gs
+					emailHtmls := fmt.Sprintf(emailHtml, company_name, id_num, phone, e_mail)
+					html = fmt.Sprintf(email_format, res["order_code"], res["url"], emailHtmls)
+				}
+				data["invoice_changed"] = 1
+				data["invoice_status"] = 1
+				data["billing_time"] = time.Now().Unix()
+				data["create_time"] = time.Now().Unix()
+				data["user_id"] = userId
+				order_id := util.Mysql.Insert(dbname, data)
+				if order_id == -1 {
+					errCode = append(errCode, fmt.Sprintf("%s_%s", res["order_code"], res["invoice_order_code"]))
+				}
+				if !isMail { //成功发邮件
+					isMail = true
+					InvoiceSendMail(res["mail"].(string), html, "电子发票")
+				}
+			case false:
+				if util.Mysql.Count(dbname, map[string]interface{}{
+					"order_code":       res["order_code"],
+					"user_id":          userId,
+					"only_Identifying": res["only_Identifying"],
+				}) > 1 {
+					continue
+				}
+				dataexport_data := make(map[string]interface{})
+				if invoice_type == "个人" {
+					dataexport_data["applyBill_type"] = 0
+					dataexport_data["applyBill_taxnum"] = ""
+					dataexport_data["applybill_company"] = ""
+				} else {
+					dataexport_data["applyBill_type"] = 1
+					dataexport_data["applyBill_taxnum"] = id_num
+					dataexport_data["applybill_company"] = company_name
+				}
+				dataexport_data["user_mail"] = e_mail
+				util.Mysql.Update("dataexport_order", map[string]interface{}{"order_code": res["order_code"], "user_id": userId}, dataexport_data)
+
+				data["mail"] = e_mail
+				data["phone"] = phone
+				data["invoice_type"] = invoice_type
+				data["company_name"] = company_name
+				data["taxpayer_identnum"] = id_num
+				data["invoice_changed"] = 1
+				data["create_time"] = time.Now().Unix()
+				data["user_id"] = userId
+				data["invoice_status"] = invoice_status
+				order_id := util.Mysql.Insert(dbname, data)
+				if order_id == -1 {
+					errCode = append(errCode, fmt.Sprintf("%s_%s", res["order_code"], res["invoice_order_code"]))
+				}
+			}
+		}
+		log.Println("换票错误信息:", errCode)
+		if !config.InvoiceConfig.Third_party_switch {
+			this.ServeJson(map[string]interface{}{
+				"invoice_status": invoice_status,
+			})
+			return
+		}
+	} else {
+		if qutil.IntAll((*oRes)["invoice_status"]) < 0 {
+			this.ServeJson(map[string]interface{}{
+				"error_code": -1,
+				"error_msg":  "发票状态错误",
+			})
+			return
+		}
+	}
+
+}
+
+func IsEdit(res map[string]interface{}, phone, e_mail, id_num, company_name, invoice_type string) bool {
+	if invoice_type == "个人" {
+		if phone == res["phone"] && e_mail == res["mail"] && res["invoice_type"] == "个人" {
+			return true
+		}
+	} else {
+		if phone == res["phone"] && e_mail == res["mail"] && id_num == res["taxpayer_identnum"] && company_name == res["company_name"] && res["invoice_type"] == "单位" {
+			return true
+		}
+	}
+	return false
+}
+
 // 退票
 func (this *Invoice) Refundinvoice() {
 	if !config.InvoiceConfig.Third_party_switch {