def worker(self, keyword, get_data): try: if self.request.method == 'POST': if keyword == "code": code = get_data.get("code", "").strip() root = 'config.ini' basicMsg = configparser.ConfigParser() basicMsg.read(root) localCode = basicMsg.get("msg", "code") if code != "" and localCode == code: # 请求获取门店信息 data = store_pc_info.get_store_detail() if not self.connect or not data: store = config.get_local_store_info() data = { 'data': { "pcId": store.id(), "pcPhone": store.phone(), "pcAddress": store.address(), "pcSign": store.name(), }, 'code': 200 } if data.get('code') == 200: result = data.get("data") else: raise ApiException(ErrorCode.CodeError) else: raise ApiException(ErrorCode.CodeError) return set_return_dicts(result) elif keyword == "ip": return set_return_dicts(True) else: raise ApiException(ErrorCode.ErrorRequest) elif self.request.method == "GET": if keyword == "list": worker = user_handler.get_all_staff() worker_list = list() for data in worker: worker_list.append({ "workerId": data[0], "workerName": data[1] }) return set_return_dicts(worker_list) else: raise ApiException(ErrorCode.ErrorRequest) except ApiException as e: return set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser'])
def get(self, *args, **kwargs): try: # 异步 yield tornado.gen.Task(ioloop.IOLoop.instance().add_timeout, time.time()) if args != (): self.__keyWord = args[0] get_Data = self.get_all_argument() # print ('get:',get_Data) if len(args) > 1: get_Data['args'] = list(args) get_Data['args'].remove(self.__keyWord) checkSheBei = self.dbhelp.CheckSheBei(self.spbill_create_ip, self.deviceName) if checkSheBei == False: raise ApiException(ErrorCode.UserStateError) elif checkSheBei == 2: raise ApiException(ErrorCode.UserStateWaitError) if self.__keyWord: # result = self.func(self.__keyWord,get_Data) result = yield self.func(self.__keyWord, get_Data) else: result = yield self.func(get_Data) # result = self.func(get_Data) TransmissionResult = json.dumps(result) # print ('get_send:{}'.format(TransmissionResult)) self.write(TransmissionResult) self.finish() except ApiException as e: self.write( json.dumps( Set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser']))) self.finish() except: self.write( json.dumps( Set_return_dicts(forWorker='不合法的参数', code=ErrorCode.ParameterError, forUser='******'))) self.finish()
def get(self, *args, **kwargs): try: # 异步 yield tornado.gen.Task(ioloop.IOLoop.instance().add_timeout, time.time()) if args != (): self.__keyWord = args[0] get_data = self.get_all_argument() if len(args) > 1: get_data['args'] = list(args) get_data['args'].remove(self.__keyWord) check_result = self.check_device() if not check_result: raise ApiException(ErrorCode.UserStateError) elif check_result == 2: raise ApiException(ErrorCode.UserStateWaitError) if self.__keyWord: result = yield self.func(self.__keyWord, get_data) else: result = yield self.func(get_data) transmission_result = json.dumps(result) self.write(transmission_result) self.finish() except ApiException as e: self.write( json.dumps( set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser']))) self.finish() except Exception as commException: print(commException) self.write( json.dumps( set_return_dicts(forWorker='不合法的参数', code=ErrorCode.ParameterError, forUser='******'))) self.finish()
def post(self, *args, **kwargs): try: # 异步 yield tornado.gen.Task(ioloop.IOLoop.instance().add_timeout, time.time()) if args != (): self.__keyWord = args[0] # json传输 try: get_Data = json.loads(self.request.body.decode()) except: try: get_Data = self.get_all_argument() except: raise ApiException(ErrorCode.JsonError) # print ('post:',get_Data) checkSheBei = self.dbhelp.CheckSheBei(self.spbill_create_ip, self.deviceName) if checkSheBei == False: raise ApiException(ErrorCode.UserStateError) elif checkSheBei == 2: raise ApiException(ErrorCode.UserStateWaitError) if self.__keyWord: result = yield self.func(self.__keyWord, get_Data) # result = self.func(self.__keyWord,get_Data) else: result = yield self.func(get_Data) # result = self.func(get_Data) TransmissionResult = json.dumps(result) # print ('post_send{}'.format(TransmissionResult)) self.write(TransmissionResult.encode('utf-8')) self.finish() except ApiException as e: self.write( json.dumps( Set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser']))) self.finish()
def post(self, *args, **kwargs): try: # 异步 yield tornado.gen.Task(ioloop.IOLoop.instance().add_timeout, time.time()) if args != (): self.__keyWord = args[0] # json传输 try: get_data = json.loads(self.request.body.decode()) except Exception as outer: print(outer) try: get_data = self.get_all_argument() except Exception as inner: print(inner) raise ApiException(ErrorCode.JsonError) # print ('post:',get_Data) check_result = self.check_device() if not check_result: raise ApiException(ErrorCode.UserStateError) elif check_result == 2: raise ApiException(ErrorCode.UserStateWaitError) if self.__keyWord: result = yield self.func(self.__keyWord, get_data) else: result = yield self.func(get_data) transmission_result = json.dumps(result) self.write(transmission_result.encode('utf-8')) self.finish() except ApiException as e: self.write( json.dumps( set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser']))) self.finish()
def ApiService(self, keyWord, getData): try: if self.request.method == "GET": if keyWord == "one": second_services = service_handler.get_all_first_level_service( ) send_data = list() for data in second_services: send_data.append({ "oneMenuId": data[0], "name": data[1] }) return set_return_dicts(send_data) elif keyWord == "two": first_service_id = getData.get("oneMenuId") second_services = service_handler.get_second_service_by_father( first_service_id) send_data = list() for data in second_services: second_service_id = data[2] second_service_name = data[3] attribute_dict = {} for attr in service_handler.get_attribute_by_service( second_service_id): attribute_dict[attr[1]] = '1' send_data.append({ "twoMenuId": second_service_id, "name": second_service_name, "attribute": attribute_dict, }) return set_return_dicts(send_data) else: raise ApiException(ErrorCode.ErrorRequest) except ApiException as e: return set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser'])
def ApiService(self, keyWord, getData): try: if self.request.method == "GET": if keyWord == "one": resultData = self.dbhelp.getOneMenu() sendData = list() for data in resultData: sendData.append({ "oneMenuId": data[0], "name": data[1] }) return Set_return_dicts(sendData) elif keyWord == "two": id = getData.get("oneMenuId") resultData = self.dbhelp.getTwoMenu(id) sendData = list() for data in resultData: attribute = data[2].split(',') attributeState = data[3].split(',') attributeDict = {} for i in range(len(attribute)): if attribute[i] != "" and attributeState[i] == '1': attributeDict[attribute[i]] = attributeState[i] sendData.append({ "twoMenuId": data[0], "name": data[1], "attribute": attributeDict, }) return Set_return_dicts(sendData) else: raise ApiException(ErrorCode.ErrorRequest) except ApiException as e: return Set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser'])
def GetPreviewHtml(self,getData,getHeight=False): mustSet = ['数量','单价','小计','总价','单位','备注'] if getData.get("createdTime"): today = getData.get("createdTime") else: today = datetime.now() if getData.get("orderNo"): orderNo = getData.get("orderNo") else: orderNo = self.dbhelp.GetOrderNo(today) parameter = getData.get("parameter",[]) if type(parameter) == str: parameter = json.loads(parameter) carUser = getData.pop("carUser","1") carId = getData.pop("carId","1") carPhone = getData.pop("carPhone","1") pcSign = getData.pop("pcSign","1") pcId = getData.pop("pcId","1") root = 'config.ini' basicMsg = configparser.ConfigParser() basicMsg.read(root) try: code = basicMsg.get("msg",'code') url = domain+"store/api/detail?code={}".format(code) req = requests.get(url=url) resultData = json.loads(req.text) except: fp = open("pc.conf",'rb') pcData = fp.readline().decode() fp.close() pcData = pcData.split(',') if len(pcData) < 4: pcData = [pcData[0],"","",""] resultData = { 'data' : { "pcId" : pcData[0], "pcPhone" : pcData[1], "pcAddress" : pcData[2], "pcSign" : pcData[3], }, 'code' : 200 } if resultData.get("code") != 200: storeName = "" pcAddress = "" pcPhone = "" else: storeName = resultData.get("data").get("pcSign","") pcAddress = resultData.get("data").get("pcAddress","") pcPhone = resultData.get("data").get("pcPhone","") fp = open("printer.txt",'rb') data = fp.readline().decode().replace("\n","").replace("\r","").replace("\ufeff","") fp.close() fontSize = 7 if data: try: fontSize = int(data) except: fontSize = 7 header = """<html> <style> table{ background-color:#000000 } .linetd{ text-align: center; border:solid 1px #000; width: 820px; color: red; height: 30px; } .halftd{ border:solid 1px #000; width: 410px; } #content{ text-align: center; border:solid 1px #000; position: relative; top: 50%; transform: translateY(-50%); } td{ padding:2px; align:center; border:1px solid black; background-color:#ffffff } """ + "*{font-size:"+str(fontSize)+"pt;}"+ ".bigWord{font-size:"+str(fontSize*1.5)+"pt;}" + "</style><head></head>" #总长度要减去备注和名称,因为名称长度另外设置,备注不打印 try: if parameter: tempAttribute = parameter[0].get('attribute') except: raise ApiException(ErrorCode.PrinterError) tdWidth = 19 self.logger.info('begin body') body = """ <body > <div style="width:100%;text-align:center"> <table width=100% CELLPADDING="0" CELLSPACING="1" border="0"> <tr> <td class="bigWord" align="center" colspan="100" width="100%"> {storeName} </td> </tr> <tr> <td colspan="50">车牌号:{carId}</td> <td colspan="50">销售日期:{createdTime}</td> </tr> <tr> <td colspan="50">客户电话:{carPhone}</td> <td colspan="50">销售单号:<span style="">{orderNo}</span></td> </tr> <tr> <td colspan="100" height="20px"> </td> </tr> """.format(storeName=pcSign,carId=carId,createdTime=today.strftime("%Y-%m-%d %H:%M:%S"),carPhone=carPhone,orderNo=orderNo) content = "" xuhao = 1 zongjia = 0 pageHeight = 100 self.logger.info('begin make attribute') for order in parameter: attribute = order.get("attribute") baseHeight = 180 #手动排序 #mustSet = ['数量','单价','小计','总价','单位','备注'] #去除mustset后的必然顺序为:"品牌","型号","工时费","更换里程" #后面用字符串排序key来排序 tempKeyList2 = ["品牌","型号","工时费","更换里程"] tempKeyList = list() for t in tempKeyList2: if attribute.get(t) and attribute.get(t) != '-': tempKeyList.append(t) for k,v in attribute.items(): if k not in mustSet+["品牌","型号","工时费","更换里程"] and v != "-" and v != "" and k != "检索ID": tempKeyList.append(k) tempKeyList.sort() noMustSet = OrderedDict() keyListLen = 0 for k in tempKeyList: noMustSet[k] = attribute.get(k) keyListLen += 1 #总长度要减去备注和名称,因为名称长度另外设置,备注不打印 td = "" keyDict = dict() i = 0 j = 0 tdList = list() keyList = list() for k,v in noMustSet.items(): # if k not in mustSet: td += "<td colspan=\"{tdWidth}\" align=\"center\">{key}</td>".format(tdWidth=tdWidth,key=k) keyList.append(k) if i >= 4: i = 0 tdList.append(td) td = "" keyDict[j] = keyList keyList = list() j += 1 else: i += 1 pageHeight += int(keyListLen/5 + 1) * 60 + baseHeight #补齐 if keyList: if len(keyList) < 5: num = len(keyList) for i in range(5-num): keyList.append("") td += "<td colspan=\"{tdWidth}\" align=\"center\"></td>".format(tdWidth=tdWidth) tdList.append(td) keyDict[j] = keyList #序号合并列数 xuNum = len(tdList)*2 + 2 content += """ <tr style="font-weight:800"> <td colspan="5" align="center">序</td> <td colspan="{tdWidth}" align="center">名称</td> <td colspan="{tdWidth}" align="center">单位</td> <td colspan="{tdWidth}" align="center">数量</td> <td colspan="{tdWidth}" align="center">单价</td> <td colspan="{tdWidth}" align="center">小计</td> </tr> <tr> <td rowspan="{xuNum}" colspan="5" align="center">{xuhao}</td> <td colspan="{tdWidth}" align="center">{project}</td> <td colspan="{tdWidth}" align="center">{unit}</td> <td colspan="{tdWidth}" align="center">{number}</td> <td colspan="{tdWidth}" align="center">{unitPrice}</td> <td colspan="{tdWidth}" align="center">{xiaoji}</td> </tr> """.format(xuNum=xuNum,xuhao=xuhao,unit=attribute.get("单位",""),number=attribute.get("数量",""),unitPrice=attribute.get("单价",""), xiaoji=attribute.get('小计',""),tdWidth=tdWidth,project=order.get("project")) moreContent = "" ii = 0 for td in tdList: #先放入表头 moreContent += "<tr style=\"font-weight:800\">" + td + "</tr>" #再放入内容 moreContent += """ <tr> <td colspan="{tdWidth}" align="center">{one}</td> <td colspan="{tdWidth}" align="center">{two}</td> <td colspan="{tdWidth}" align="center">{three}</td> <td colspan="{tdWidth}" align="center">{four}</td> <td colspan="{tdWidth}" align="center">{five}</td> </tr> """.format(tdWidth=tdWidth,one=attribute.get(keyDict[ii][0],"-") if keyDict[ii][0] != '' else "", two=attribute.get(keyDict[ii][1],"-") if keyDict[ii][1] != '' else "", three=attribute.get(keyDict[ii][2],"-") if keyDict[ii][2] != '' else "", four=attribute.get(keyDict[ii][3],"-") if keyDict[ii][3] != '' else "", five=attribute.get(keyDict[ii][4],"-") if keyDict[ii][4] != '' else "") ii += 1 fenge = """ <tr> <td colspan="100" height="20px"> </td> </tr> """ zongjiaconetent = """ <tr> <td colspan="95">总价:{zongjia}</td> </tr> """.format(zongjia=attribute.get('总价',"")) content += moreContent + zongjiaconetent + fenge xuhao += 1 zongjia += float(attribute.get('总价',0)) self.logger.info('end make attribute') zongjia = str(zongjia) cn = cncurrency(zongjia) foot = """ <tr> <td style="height:35px" colspan="70">合计人名币(大写):{cn}</td> <td style="height:35px" colspan="30">小写:{zongjia}</td> </tr> <tr> <td colspan="30">{storeName}</td> <td colspan="35">地址:{pcAddress}</td> <td colspan="35">联系电话:{pcPhone}</td> </tr> </table> </div> </body> </html> """.format(cn=cn,zongjia=zongjia,storeName=pcSign,pcPhone=pcPhone,pcAddress=pcAddress) html = header + body + content + foot self.logger.info('add str end') if getHeight: return html,pageHeight else: return html
def ApiOrder(self,keyWord,getData): try: if self.request.method == 'POST': if keyWord == "add": today = datetime.now() orderNo = self.dbhelp.GetOrderNo(today) getData["orderNo"] = orderNo getData["createdTime"] = today try: # if True: carUser = getData.get("carUser") userId = getData.get("userId") workerId = getData.get("workerId") pcId = getData.get("pcId") carPhone = getData.get("carPhone") carModel = getData.get("carModel") carId = getData.get("carId") pcSign = getData.get("pcSign") workerName = getData.get("workerName") root = 'config.ini' basicMsg = configparser.ConfigParser() basicMsg.read(root) orderCheckId = GetOrderId() saveData = { 'createdTime' : getData.get("createdTime").strftime("%Y-%m-%d %H:%M:%S"), 'userId' : userId, 'pcId' : pcId, 'pcSign' : pcSign, 'carId' : carId, 'workerName' : workerName, 'workerId' : workerId, 'carUser' : carUser, 'carPhone' : carPhone, 'carModel' : carModel, "orderNo":orderNo, "orderCheckId":orderCheckId, 'code' : basicMsg.get("msg","code"), } parameter = getData.get("parameter",[]) if type(parameter) == str: parameter = json.loads(parameter) page = 0 for data in parameter: page += 1 orderId = GetOrderId() temp = { 'project':data.get('project'), 'id' : orderId, 'attribute' : json.dumps(data.get('attribute')) } self.dbhelp.InsertXiaoFei(dict(temp, **saveData)) #回访设置 if data.get("callbackTime"): dbname = "CallBack" key = "{},{},{},{},{},{}".format("callbackTime","phone",'carId',"username",'createdTime','state') value = "\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\'".format(data.get("callbackTime"),carPhone,carId,carUser,today,'0') self.dbhelp.InsertData(dbname,key,value) except: raise ApiException(ErrorCode.ParameterMiss) try: # if True: #打印 p = "defaultPrinter" #打印机名称 html,pageHeight = self.GetPreviewHtml(getData,True) Printer.printing(p, html,pageHeight) except: # raise ApiException(ErrorCode.PrinterError) pass return Set_return_dicts({"orderNo":orderNo}) elif keyWord == 'preview': self.logger.info('============begin-printer==============') html = self.GetPreviewHtml(getData) self.logger.info('============end-printer==============') return Set_return_dicts(html) else: raise ApiException(ErrorCode.ErrorRequest) elif self.request.method == "GET": if not self.storeId: raise ApiException(ErrorCode.PCError) if keyWord == "detail": checkOrderId = getData.get("checkOrderId") if not checkOrderId: raise ApiException(ErrorCode.ParameterMiss) if self.connect: resultDict = SocketServer("orderdetail {} {}".format(self.storeId,checkOrderId)) else: result = self.dbhelp.GetXiaoFeiByKey("orderCheckId",checkOrderId) resultList = list() resultDict = {} if result: createdTime = '' carId = '' carUser = '' carPhone = '' carModel = '' totalPrice = 0 pcId = '' orderNo = '' for data in result: attribute = OrderedDict(json.loads(data[8])) createdTime = data[0] carId = data[2] carUser = data[3] carPhone = data[4] carModel = data[5] price = float(attribute.get("总价",0)) pcId = data[9] orderNo = data[1] if pcId: totalPrice += price attribute['project'] = data[7] attribute['totalPrice'] = price attribute['orderNo'] = orderNo resultList.append(attribute) fp = open("pc.conf",'rb') pcData = fp.readline().decode() pcData = pcData.split(',') fp.close() try: pcSign = pcData[3] except: pcSign = "" resultDict = { "msg" : resultList, "totalPrice" : totalPrice, "createdTime" : createdTime, "carId" : carId, "carUser" : carUser, "carPhone" : carPhone, "carModel" : carModel, "orderNo" : orderNo, "checkOrderId" : checkOrderId, "pcSign" : pcSign, } if resultDict == 'restart': raise ApiException(ErrorCode.ReStartPC) # resultDict = {} return Set_return_dicts(resultDict) else: raise ApiException(ErrorCode.ErrorRequest) except ApiException as e: return Set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser'])
def ApiUser(self,keyWord,getData): try: if self.request.method == 'POST': if keyWord == "add": try: userName = getData.pop("username") carPhone = getData.pop("carPhone") carModel = getData.pop("carModel") carId = getData.pop("carId") except: raise ApiException(ErrorCode.ParameterMiss) key = "userName,carPhone,carModel,carId,createdTime" value = "'{}','{}','{}','{}','{}'".format(userName,carPhone,carModel,carId,GetToday()) tempUser = self.dbhelp.GetUserByKey("carId",carId) if tempUser: updateData = "userName=\'{}\',carPhone=\'{}\',carModel=\'{}\'".format(userName,carPhone,carModel) search = "carId=\'{}\'".format(carId) try: self.dbhelp.UpdateData("User",updateData,search) except: raise ApiException(ErrorCode.ParameterError) userId = tempUser[0][0] else: try: userId = self.dbhelp.InsertData("User",key,value) except: raise ApiException(ErrorCode.UserMore) return Set_return_dicts({"userId":userId}) else: raise ApiException(ErrorCode.ErrorRequest) elif self.request.method == "GET": # basicMsg = configparser.ConfigParser() # root = 'config.ini' # basicMsg.read(root) # code = basicMsg.get('msg','code') if not self.storeId: raise ApiException(ErrorCode.PCError) if keyWord == "find": key = getData.get("key","") if key not in ["carPhone","carId"]: raise ApiException(ErrorCode.ParameterError) value = getData.get("value","") if self.connect: temp = SocketServer("user {} {} {}".format(self.storeId,key,value)) if not temp: temp = self.GetFind(key,value) else: temp = self.GetFind(key,value) result = [] keyTemp = [] if temp == 'restart': raise ApiException(ErrorCode.ReStartPC) # result = [] else: for data in temp: key = data.get("phone") + data.get("carId") + data.get("carModel") + data.get("userName") if key in keyTemp: pass else: result.append(data) keyTemp.append(key) return Set_return_dicts(result) elif keyWord == 'order': carId = getData.get("carId","") carPhone = getData.get("carPhone","") if not carId: raise ApiException(ErrorCode.ParameterMiss) if self.connect: allOrderMoney = 0 result = SocketServer("userorder {} {} {}".format(self.storeId,carId,carPhone)) if result: orderNumber = len(result) for data in result: allOrderMoney += data.get("totalPrice") else: result,orderNumber,allOrderMoney = self.GetOrder(carId,carPhone) else: result,orderNumber,allOrderMoney = self.GetOrder(carId,carPhone) if result == 'restart': raise ApiException(ErrorCode.ReStartPC) # result = [] else: result.sort(key=lambda obj:obj.get('createdTime'), reverse=True) for data in result: msg = data.get("msg") for msgData in msg: temp = {} attribute = msgData.get("attribute") for k,v in attribute.items(): if v != "" and v != "-": temp[k] = v msgData['attribute'] = temp sendMsg = { 'orderMsg' : result, 'orderNumber' : orderNumber, 'allOrderMoney' : allOrderMoney } return Set_return_dicts(sendMsg) else: raise ApiException(ErrorCode.ErrorRequest) except ApiException as e: return Set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser'])
def print_html(printer): root = 'config.ini' basicMsg = configparser.ConfigParser() basicMsg.read(root) try: if not myconnect: raise ApiException(ErrorCode.ErrorRequest) code = basicMsg.get("msg", 'code') url = domain + "store/api/detail?code={}".format(code) req = requests.get(url=url) resultData = json.loads(req.text) except: fp = open("pc.conf", 'rb') pcData = fp.readline().decode() fp.close() pcData = pcData.split(',') if len(pcData) < 4: pcData = [pcData[0], "", "", ""] resultData = { 'data': { "pcId": pcData[0], "pcPhone": pcData[1], "pcAddress": pcData[2], "pcSign": pcData[3], }, 'code': 200 } mustSet = ['数量', '单价', '小计', '总价', '单位', '备注'] if resultData.get("code") != 200: storeName = "" pcAddress = "" pcPhone = "" else: storeName = resultData.get("data").get("pcSign", "") pcAddress = resultData.get("data").get("pcAddress", "") pcPhone = resultData.get("data").get("pcPhone", "") result = get_sale_info_by_one_key("orderCheckId", selectOrderNo) fp = open("printer.txt", 'rb') data = fp.readline().decode().replace("\n", "").replace("\r", "").replace( "\ufeff", "") fp.close() fontSize = 7 if data: try: fontSize = int(data) except: fontSize = 7 # *{font-size:65px;} if result: header = """<html> <style> table{ background-color:#000000; } .linetd{ text-align: center; width: 820px; color: red; height: 30px; } .halftd{ width: 410px; } #content{ text-align: center; position: relative; top: 50%; transform: translateY(-50%); } td{ padding:2px; align:center; border:1px solid black; background-color:#ffffff } """ + "*{font-size:" + str( fontSize) + "pt;}" + ".bigWord{font-size:" + str( fontSize * 1.5) + "pt;}" + "</style><head></head>" # *{font-size:50px;} tdWidth = 19 body = """ <body style="text-align: center;"> <table width=100% CELLPADDING="0" CELLSPACING="1" border="0"> <tr> <td class="bigWord" align="center" colspan="100" width="100%"> {storeName} </td> </tr> <tr> <td colspan="50">车牌号:{carId}</td> <td colspan="50">销售日期:{createdTime}</td> </tr> <tr> <td colspan="50">客户电话:{carPhone}</td> <td colspan="50">销售单号:<span style="">{orderNo}</span></td> </tr> <tr> <td colspan="100" height="20px"> </td> </tr> """.format(storeName=storeName, carId=result[0][2], createdTime=result[0][0], carPhone=result[0][4], orderNo=result[0][1]) content = "" xuhao = 1 zongjia = 0 page = 0 pageHeight = 100 for order in result: page += 1 attribute = json.loads(order[8]) baseHeight = 180 # 手动排序 # mustSet = ['数量','单价','小计','总价','单位','备注'] # 去除mustset后的必然顺序为:"品牌","型号","工时费","更换里程" # 后面用字符串排序key来排序 tempKeyList2 = ["品牌", "型号", "工时费", "更换里程"] tempKeyList = list() for t in tempKeyList2: if attribute.get(t) and attribute.get(t) != '-': tempKeyList.append(t) for k, v in attribute.items(): if k not in mustSet + [ "品牌", "型号", "工时费", "更换里程" ] and v != "-" and v != "" and k != "检索ID": tempKeyList.append(k) tempKeyList.sort() noMustSet = OrderedDict() for k in tempKeyList: noMustSet[k] = attribute.get(k) # 总长度要减去备注和名称,因为名称长度另外设置,备注不打印 td = "" keyDict = dict() i = 0 j = 0 tdList = list() keyList = list() pageHeight += int(len(noMustSet.keys()) / 5 + 1) * 60 + baseHeight for k, v in noMustSet.items(): # if k not in mustSet and v != "-" and v != "" and k!="检索ID" : td += "<td colspan=\"{tdWidth}\" align=\"center\"><b>{key}</b></td>".format( tdWidth=tdWidth, key=k) keyList.append(k) if i >= 4: i = 0 tdList.append(td) td = "" keyDict[j] = keyList keyList = list() j += 1 else: i += 1 # 补齐 if keyList: if len(keyList) < 5: num = len(keyList) for i in range(5 - num): keyList.append("") td += "<td colspan=\"{tdWidth}\" align=\"center\"></td>".format( tdWidth=tdWidth) tdList.append(td) keyDict[j] = keyList # 序号合并列数 xuNum = len(tdList) * 2 + 2 # createdTime,orderNo,carId,carUser,carPhone,carModel,workerName,project,brand," \ # "model,huawen,number,unitPrice,xiaoji,gongshi,ghlc,remark,totalPrice,pcId,unit content += """ <tr> <td colspan="5" align="center"><b>序</b></td> <td colspan="{tdWidth}" align="center"><b>名称</b></td> <td colspan="{tdWidth}" align="center"><b>单位</b></td> <td colspan="{tdWidth}" align="center"><b>数量</b></td> <td colspan="{tdWidth}" align="center"><b>单价</b></td> <td colspan="{tdWidth}" align="center"><b>小计</b></td> </tr> <tr> <td rowspan="{xuNum}" colspan="5" align="center"><br/>{xuhao}</td> <td colspan="{tdWidth}" align="center">{project}</td> <td colspan="{tdWidth}" align="center">{unit}</td> <td colspan="{tdWidth}" align="center">{number}</td> <td colspan="{tdWidth}" align="center">{unitPrice}</td> <td colspan="{tdWidth}" align="center">{xiaoji}</td> </tr> """.format(xuNum=xuNum, xuhao=xuhao, unit=attribute.get("单位", ""), number=attribute.get("数量", ""), unitPrice=attribute.get("单价", ""), xiaoji=attribute.get('小计', ""), project=order[7], tdWidth=tdWidth) moreContent = "" ii = 0 for td in tdList: # 先放入表头 moreContent += "<tr>" + td + "</tr>" # 再放入内容 moreContent += """ <tr> <td colspan="{tdWidth}" align="center">{one}</td> <td colspan="{tdWidth}" align="center">{two}</td> <td colspan="{tdWidth}" align="center">{three}</td> <td colspan="{tdWidth}" align="center">{four}</td> <td colspan="{tdWidth}" align="center">{five}</td> </tr> """.format(tdWidth=tdWidth, one=attribute.get(keyDict[ii][0], ""), two=attribute.get(keyDict[ii][1], ""), three=attribute.get(keyDict[ii][2], ""), four=attribute.get(keyDict[ii][3], ""), five=attribute.get(keyDict[ii][4], "")) ii += 1 fenge = """ <tr> <td colspan="100" height="20px"> </td> </tr> """ zongjiaconetent = """ <tr> <td colspan="95">总价:{zongjia}</td> </tr> """.format(zongjia=attribute.get('总价', "")) content += moreContent + zongjiaconetent + fenge xuhao += 1 try: zongjia += float(attribute.get('总价', 0)) except: zongjia = 0 zongjia = str(zongjia) cn = cncurrency(zongjia) foot = """ <tr> <td style="height:35px" colspan="70">合计人名币(大写):{cn}</td> <td style="height:35px" colspan="30">小写:{zongjia}</td> </tr> <tr> <td colspan="30">{storeName}</td> <td colspan="35">地址:{pcAddress}</td> <td colspan="35">联系电话:{pcPhone}</td> </tr> </table> </body> </html> """.format(cn=cn, zongjia=zongjia, storeName=storeName, pcPhone=pcPhone, pcAddress=pcAddress) html = header + body + content + foot textDocument = QTextDocument() textDocument.setHtml(html) textDocument.setDocumentMargin(35) printer.setPageSize(QPrinter.Custom) # height = baseHeight+((page-1)*150) # printer.setPaperSize(QSizeF(printer.logicalDpiX()*(86/25.4),height),QPrinter.Point) # textDocument.setPageSize(QSizeF(printer.logicalDpiX()*(86/25.4),height)) printer.setPaperSize(QSizeF(581, pageHeight), QPrinter.Point) textDocument.setPageSize(QSizeF(581, pageHeight)) textOp = QTextOption() textOp.setWrapMode(QTextOption.WrapAnywhere) textOp.setAlignment(Qt.AlignCenter) textDocument.setDefaultTextOption(textOp) printer.setOutputFormat(QPrinter.NativeFormat) textDocument.print(printer)
def ApiWorker(self, keyWord, getData): try: if self.request.method == 'POST': if keyWord == "code": result = {} code = getData.get("code", "").strip() root = 'config.ini' basicMsg = configparser.ConfigParser() basicMsg.read(root) localCode = basicMsg.get("msg", "code") if code != "" and localCode == code: #请求获取门店信息 if self.connect: url = domain + "store/api/detail?code={}".format( code) try: req = requests.get(url) jsonData = req.text data = json.loads(jsonData) except: fp = open("pc.conf", 'rb') pcData = fp.readline().decode() fp.close() pcData = pcData.split(',') if len(pcData) < 4: pcData = [pcData[0], "", "", ""] data = { 'data': { "pcId": pcData[0], "pcPhone": pcData[1], "pcAddress": pcData[2], "pcSign": pcData[3], }, 'code': 200 } else: fp = open("pc.conf", 'rb') pcData = fp.readline().decode() fp.close() pcData = pcData.split(',') if len(pcData) < 4: pcData = [pcData[0], "", "", ""] data = { 'data': { "pcId": pcData[0], "pcPhone": pcData[1], "pcAddress": pcData[2], "pcSign": pcData[3], }, 'code': 200 } if data.get('code') == 200: result = data.get("data") else: raise ApiException(ErrorCode.CodeError) else: raise ApiException(ErrorCode.CodeError) return Set_return_dicts(result) elif keyWord == "ip": return Set_return_dicts(True) else: raise ApiException(ErrorCode.ErrorRequest) elif self.request.method == "GET": if keyWord == "list": worker = self.dbhelp.GetWorker() workerList = list() for data in worker: workerList.append({ "workerId": data[0], "workerName": data[1] }) return Set_return_dicts(workerList) else: raise ApiException(ErrorCode.ErrorRequest) except ApiException as e: return Set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser'])
def user(self, keyword, get_data): try: if self.request.method == 'POST': if keyword == "add": try: username = get_data.pop("username") phone = get_data.pop("carPhone") car_model = get_data.pop("carModel") car_id = get_data.pop("carId") except Exception as e: print(e) raise ApiException(ErrorCode.ParameterMiss) customer = Customer() customer.username(username) customer.car_model(car_model) customer.phone(phone) customer.car_id(car_id) customer.create_time(time_utils.get_now()) temp_user = customer_handler.get_customer_by_key( "carId", car_id) if temp_user: try: customer_handler.update_customer_by_car_id( customer) except Exception as update_exception: print(update_exception) raise ApiException(ErrorCode.ParameterError) customer_id = temp_user[0][0] else: try: customer_id = customer_handler.add_customer( customer) except Exception as insert_exception: print(insert_exception) raise ApiException(ErrorCode.UserMore) return set_return_dicts({"userId": customer_id}) else: raise ApiException(ErrorCode.ErrorRequest) elif self.request.method == "GET": if not self.storeId: raise ApiException(ErrorCode.PCError) if keyword == "find": key = get_data.get("key", "") if key not in ["carPhone", "carId"]: raise ApiException(ErrorCode.ParameterError) value = get_data.get("value", "") if self.connect: temp = SocketServer("user {} {} {}".format( self.storeId, key, value)) if not temp: temp = self.find_customer(key, value) else: temp = self.find_customer(key, value) result = [] key_temp = [] if temp == 'restart': raise ApiException(ErrorCode.ReStartPC) else: for data in temp: key = data.get("phone") + data.get( "carId") + data.get("carModel") + data.get( "userName") if key in key_temp: pass else: result.append(data) key_temp.append(key) return set_return_dicts(result) elif keyword == 'order': car_id = get_data.get("carId", "") phone = get_data.get("carPhone", "") if not car_id: raise ApiException(ErrorCode.ParameterMiss) if self.connect: all_order_money = 0.0 result = SocketServer("userorder {} {} {}".format( self.storeId, car_id, phone)) if result: order_number = len(result) for data in result: all_order_money += data.get("totalPrice") else: result, order_number, all_order_money = self.get_order( car_id) else: result, order_number, all_order_money = self.get_order( car_id) if result == 'restart': raise ApiException(ErrorCode.ReStartPC) # result = [] else: print('sort') try: result.sort(key=lambda obj: obj.get('createdTime'), reverse=True) except Exception as sortE: print(sortE) try: for data in result: print(data) msg = data.get("msg") for msg_data in msg: temp = {} attribute = msg_data.get("attribute") for k, v in attribute.items(): if v != "" and v != "-": temp[k] = v msg_data['attribute'] = temp except Exception as forException: print(forException) send_msg = { 'orderMsg': result, 'orderNumber': order_number, 'allOrderMoney': all_order_money } print(send_msg) return set_return_dicts(send_msg) else: raise ApiException(ErrorCode.ErrorRequest) except ApiException as e: return set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser'])
def ApiOrder(self, keyWord, getData): try: if self.request.method == 'POST': if keyWord == "add": today = datetime.now() orderNo = get_sale_order_no(today) getData["orderNo"] = orderNo getData["createdTime"] = today print(keyWord) try: # if True: carUser = getData.get("carUser") userId = getData.get("userId") workerId = getData.get("workerId") pcId = getData.get("pcId") carPhone = getData.get("carPhone") carModel = getData.get("carModel") carId = getData.get("carId") pc_sign = getData.get("pcSign") workerName = getData.get("workerName") root = 'config.ini' basicMsg = configparser.ConfigParser() basicMsg.read(root) orderCheckId = get_order_id() saveData = { 'createdTime': getData.get("createdTime").strftime( "%Y-%m-%d %H:%M:%S"), 'userId': userId, 'pcId': pcId, 'pcSign': pc_sign, 'carId': carId, 'workerName': workerName, 'workerId': workerId, 'carUser': carUser, 'carPhone': carPhone, 'carModel': carModel, "orderNo": orderNo, "orderCheckId": orderCheckId, 'code': basicMsg.get("msg", "code"), } parameter = getData.get("parameter", []) if type(parameter) == str: parameter = json.loads(parameter) page = 0 for data in parameter: page += 1 order_id = get_order_id() services = data.get('project') services = services.split('-') first_service_name = services[0] second_service_name = services[1] first_service_id = service_handler.get_service_id_by_name( first_service_name)[0] second_service_id = service_handler.get_service_id_by_name( second_service_name, first_service_id)[0] attributes = data.get('attribute') print(attributes) try: unit = attributes.get('单位', '') unit_price = float(attributes.pop('单价', '')) number = int(attributes.get('数量', '')) subtotal = float(attributes.get('小计', '')) total = float(attributes.get('总价', '')) note = attributes.get('备注', '') except Exception as attribute_deal_error: print(attribute_deal_error) unit = '' unit_price = 0.0 number = 0 subtotal = 0.0 total = 0.0 note = '' temp = { 'project': data.get('project'), 'id': order_id, 'attribute': json.dumps(data.get('attribute')), 'serviceId': second_service_id, 'unit': unit, 'unit_price': unit_price, 'number': number, 'subtotal': subtotal, 'total': total, 'note': note } sale_id = sale_handler.add_sale_info( dict(temp, **saveData)) service_attrs = service_handler.get_attribute_by_service( second_service_id) print(service_attrs) all_required_attr = attribute_handler.get_all_required_attributes( ) required_attr_list = [] for attr in all_required_attr: required_attr_list.append(attr[1]) for srv_attr in service_attrs: attr_name = srv_attr[1] if attr_name not in required_attr_list: attr_id = attribute_handler.get_attr_by_name( attr_name)[0] sale_item_handler.add_sale_item( order_id, attr_id, attributes.get(attr_name, '')) # 回访设置 if data.get("callbackTime"): dbname = "CallBack" key = "{},{},{},{},{},{}".format( "callbackTime", "phone", 'carId', "username", 'createdTime', 'state') value = "\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\'".format( data.get("callbackTime"), carPhone, carId, carUser, today, '0') self.dbhelp.InsertData(dbname, key, value) customer_handler.add_return_visit_data( data.get("callbackTime"), carPhone, carId, carUser, today) except Exception as add_error: print(add_error) raise ApiException(ErrorCode.ParameterMiss) try: # if True: # 打印 p = "defaultPrinter" # 打印机名称 html, pageHeight = self.preview_html(getData, True) Printer.printing(p, html, pageHeight) except: # raise ApiException(ErrorCode.PrinterError) pass return set_return_dicts({"orderNo": orderNo}) elif keyWord == 'preview': print('preview') html = self.preview_html(getData) print(html) return set_return_dicts(html) else: raise ApiException(ErrorCode.ErrorRequest) elif self.request.method == "GET": if not self.storeId: raise ApiException(ErrorCode.PCError) if keyWord == "detail": checkOrderId = getData.get("checkOrderId") if not checkOrderId: raise ApiException(ErrorCode.ParameterMiss) if self.connect: result_dict = SocketServer("orderdetail {} {}".format( self.storeId, checkOrderId)) else: result = get_sale_info_by_one_key( "orderCheckId", checkOrderId) resultList = list() result_dict = {} if result: createdTime = '' carId = '' carUser = '' carPhone = '' carModel = '' totalPrice = 0 pcId = '' orderNo = '' for data in result: attribute = OrderedDict(json.loads(data[8])) createdTime = data[0] carId = data[2] carUser = data[3] carPhone = data[4] carModel = data[5] price = data[16] pcId = data[9] orderNo = data[1] if pcId: totalPrice += price attribute['project'] = data[7] attribute['totalPrice'] = price attribute['orderNo'] = orderNo resultList.append(attribute) try: pc_sign = config.get_store_name() except: pc_sign = "" result_dict = { "msg": resultList, "totalPrice": totalPrice, "createdTime": createdTime, "carId": carId, "carUser": carUser, "carPhone": carPhone, "carModel": carModel, "orderNo": orderNo, "checkOrderId": checkOrderId, "pcSign": pc_sign, } if result_dict == 'restart': raise ApiException(ErrorCode.ReStartPC) # resultDict = {} return set_return_dicts(result_dict) else: raise ApiException(ErrorCode.ErrorRequest) except ApiException as e: return set_return_dicts(forWorker=e.error_result['forWorker'], code=e.error_result['errorCode'], forUser=e.error_result['forUser'])