Example #1
0
    def import_sale_detail(self, file_name, widget):
        bk = xlrd.open_workbook(file_name)
        try:
            sh = bk.sheet_by_name("消费列表")
        except Exception as e:
            print(e)
            sh = bk.sheet_by_name("Sheet1")
        rows = sh.nrows
        temp = list()
        title_list = ['检索ID', 'orderNo', 'createdTime', "pcSign", "carId", "carUser", "carPhone", "carModel",
                      "workerName", "project"]
        user_list = ["carId", "carUser", "carPhone", "carModel"]
        must_len = len(title_list)
        title = sh.row_values(1)

        match_result = self._is_from_export(str(sh.row_values(0)[0]))

        progress_dialog = QProgressDialog(widget)
        progress_dialog.setWindowTitle("导入中")
        from PyQt5.QtCore import Qt
        progress_dialog.setWindowModality(Qt.WindowModal)
        progress_dialog.setMinimumDuration(4)
        progress_dialog.setWindowTitle(widget.tr("请等待"))
        progress_dialog.setLabelText(widget.tr("导入中..."))
        progress_dialog.setCancelButtonText(widget.tr("取消"))
        progress_dialog.setRange(0, rows - 3)
        progress_dialog.show()
        if True:
            p = 0
            msg_list = list()
            for i in range(2, rows):
                # 用正则表达式判断第一行数据内容,从而判断是否用软件导出的EXCEL文档
                if match_result:
                    # 若是用软件导出的则
                    if progress_dialog.wasCanceled():
                        break
                    progress_dialog.setValue(p)
                    p += 1
                    try:
                        # if True:
                        save_data = dict()
                        row_data = sh.row_values(i)
                        if i < rows - 1:
                            temp2 = sh.row_values(i + 1)
                        else:
                            temp2 = None

                        if not temp2 and temp2[0] == '':
                            # 合并了单元格则合并内容是空,将后面不是空的内容进行缓存,合并的内容会在最后一条信息中显示,
                            # 此时一并进行录入
                            temp.append(row_data)
                        else:

                            # if row_data[0] != '':
                            if temp:
                                order_check_id = temp[0][0]
                            else:
                                order_check_id = row_data[0]
                            check_order = get_sale_info_by_one_key("orderCheckId", order_check_id)
                            # 有此订单的就不保存了
                            if not check_order:
                                if temp:
                                    temp.append(row_data)
                                    all_msg = temp[0]
                                    # 接入信息后录入
                                    for j in range(len(temp)):
                                        if j != 0:
                                            msg = temp[j]
                                            attribute = {}
                                            for ki in range(len(title)):

                                                all_msg[ki] = str(all_msg[ki])
                                                msg[ki] = str(msg[ki])
                                                if ki < must_len:
                                                    temp_key = title_list[ki]
                                                    if temp_key in ['orderNo', 'carPhone']:
                                                        all_msg[ki] = all_msg[ki].replace('.0', "")
                                                        msg[ki] = msg[ki].replace('.0', "")
                                                    if title_list[ki] in ["project"]:
                                                        save_data[temp_key] = msg[ki]
                                                    else:
                                                        if temp_key == "检索ID":
                                                            temp_key = "orderCheckId"
                                                        save_data[temp_key] = all_msg[ki]
                                                else:
                                                    if row_data[ki] == "" or row_data[ki] == "-":
                                                        continue
                                                    attribute[title[ki]] = msg[ki]

                                            save_data['attribute'] = json.dumps(attribute)
                                            save_data['id'] = get_order_id()
                                            sale_handler.add_sale_info(save_data)

                                        row_data = all_msg
                                attribute = {}
                                user_save = {}
                                for ki in range(len(title)):
                                    row_data[ki] = str(row_data[ki])
                                    if ki < must_len:
                                        if title_list[ki] in ['orderNo', 'carPhone']:
                                            row_data[ki] = row_data[ki].replace('.0', "")
                                        key = title_list[ki]
                                        if key == "检索ID":
                                            key = "orderCheckId"
                                        save_data[key] = row_data[ki]
                                        # 保存用户信息
                                        if key in user_list:
                                            user_save[key] = row_data[ki]

                                    else:
                                        if row_data[ki] == "" or row_data[ki] == "-":
                                            continue
                                        attribute[title[ki]] = row_data[ki]

                                user = check_customer(user_save.get("carPhone"),
                                                      user_save.get("carId"))
                                if not user:
                                    # 没有此用户则添加
                                    key = "userName,carPhone,carModel,carId,createdTime"
                                    value = "'{}','{}','{}','{}','{}'".format(user_save.get("carUser"),
                                                                              user_save.get("carPhone"),
                                                                              user_save.get("carModel"),
                                                                              user_save.get("carId"), get_now())
                                    try:
                                        self.database_handler.InsertData("User", key, value)
                                    except Exception as e:
                                        print(e)
                                        pass

                                save_data['attribute'] = json.dumps(attribute)
                                save_data['id'] = get_order_id()
                                sale_handler.add_sale_info(save_data)

                            # 清空缓存
                            temp = list()

                    except Exception as e:
                        print(e)
                        continue
                else:
                    # 若不是用软件导出的EXCEL文档则
                    # 先整理参数,全部变成列表,列表里面是字典,字典的key就是title
                    try:
                        row_data = sh.row_values(i)
                        temp_data = dict()

                        for k in range(len(title)):
                            temp_data[title[k]] = row_data[k]
                        msg_list.append(temp_data)
                    except Exception as e:
                        print(e)
                        continue

            if not match_result:
                save_list = defaultdict(list)
                for msg in msg_list:
                    if not msg.get("消费时间") or not msg.get("车牌号"):
                        continue

                    key = msg.get("消费时间") + msg.get("车牌号")
                    save_list[key].append(msg)

                # 插入信息
                must = ["订单号", "接待门店", "车牌号", "车主姓名", "联系电话", "车型", "操作人员", "消费项目", "消费时间"]
                for k, v in save_list.items():
                    if progress_dialog.wasCanceled():
                        break
                    progress_dialog.setValue(p)
                    p += 1
                    order_check_id = get_order_id()
                    # 对同一个订单进行录入
                    user_save = {}
                    for tempDict in v:
                        order_no = str(tempDict.pop("订单号")) if tempDict.get("订单号", "") != "" else "-"
                        pc_sign = tempDict.pop("接待门店", "") if tempDict.get("接待门店", "") != "" else "-"
                        car_id = tempDict.pop("车牌号") if tempDict.get("车牌号") != "" else "-"
                        car_user = tempDict.pop("车主姓名", "") if tempDict.get("车主姓名", "") != "" else "-"
                        car_phone = str(tempDict.pop("联系电话", "-")).replace(".0", "") if tempDict.get("联系电话",
                                                                                                     "") != "" else "-"
                        car_model = tempDict.pop("车型", "") if tempDict.get("车型", "") != "" else "-"
                        worker_name = tempDict.pop("操作人员", "") if tempDict.get("操作人员", "") != "" else "-"
                        project = tempDict.pop("消费项目", "") if tempDict.get("消费项目", "") != "" else "-"
                        created_time = str(tempDict.pop("消费时间")).replace(".", "-")
                        # 保存用户信息
                        user_save["carId"] = car_id if car_id != '-' else ""
                        user_save["carUser"] = car_user if car_user != '-' else ""
                        user_save["carPhone"] = (car_phone if car_phone != '-' else "").replace(".0", "")
                        user_save['carModel'] = car_model if car_model != '-' else ""

                        if order_no != "-":
                            check_order = get_sale_info_by_one_key("orderNo", order_no)
                            if check_order:
                                break

                        save_data = {
                            "orderNo": order_no.replace(".0", ""),
                            "createdTime": created_time,
                            "pcSign": pc_sign,
                            "carId": car_id,
                            "carUser": car_user,
                            "carPhone": car_phone,
                            "carModel": car_model,
                            "workerName": worker_name,
                            "project": project,
                            "orderCheckId": order_check_id,
                            "id": get_order_id(),
                        }
                        temp_attribute = tempDict

                        attribute = dict()
                        for key, value in temp_attribute.items():
                            if k not in must:
                                if value == "":
                                    continue
                                attribute[key] = str(value)
                        try:
                            gsf = float(attribute.get("工时费")) if attribute.get("工时费") != "" else 0
                            sl = float(attribute.get("数量")) if attribute.get("数量") != "" else 0
                            dj = float(attribute.get("单价")) if attribute.get("单价") != "" else 0
                            attribute["总价"] = gsf + sl * dj
                        except Exception as e:
                            print(e)
                            pass
                        save_data["attribute"] = json.dumps(attribute)
                        sale_handler.add_sale_info(save_data)

                    if user_save.get("carId") and user_save.get("carPhone"):
                        # 当有用户信息的时候判断是否需要自动添加
                        user = check_customer(user_save.get("carPhone"), user_save.get("carId"))
                        if not user:
                            # 没有此用户则添加
                            key = "userName,carPhone,carModel,carId,createdTime"
                            value = "'{}','{}','{}','{}','{}'".format(user_save.get("carUser"),
                                                                      user_save.get("carPhone"),
                                                                      user_save.get("carModel"), user_save.get("carId"),
                                                                      get_now())
                            try:
                                self.database_handler.InsertData("User", key, value)
                            except Exception as e:
                                print(e)
                                pass
            # 最后全部导入
            progress_dialog.setValue(rows - 3)
            progress_dialog.close()
Example #2
0
    def order(self, keyword, para_data):
        try:
            if self.request.method == 'POST':
                if keyword == "add":
                    today = datetime.now()

                    order_no = get_sale_order_no(today)

                    para_data["orderNo"] = order_no
                    para_data["createdTime"] = today
                    print(keyword)
                    try:
                        car_user = para_data.get("carUser")
                        user_id = para_data.get("userId")
                        worker_id = para_data.get("workerId")
                        pc_id = para_data.get("pcId")
                        car_phone = para_data.get("carPhone")
                        car_model = para_data.get("carModel")
                        car_id = para_data.get("carId")
                        pc_sign = para_data.get("pcSign")
                        worker_name = para_data.get("workerName")
                        order_check_id = get_uuid1()
                        save_data = {
                            'createdTime':
                            para_data.get("createdTime").strftime(
                                "%Y-%m-%d %H:%M:%S"),
                            'userId':
                            user_id,
                            'pcId':
                            pc_id,
                            'pcSign':
                            pc_sign,
                            'carId':
                            car_id,
                            'workerName':
                            worker_name,
                            'workerId':
                            worker_id,
                            'carUser':
                            car_user,
                            'carPhone':
                            car_phone,
                            'carModel':
                            car_model,
                            "orderNo":
                            order_no,
                            "orderCheckId":
                            order_check_id,
                            'code':
                            config.get_local_register_code(),
                        }

                        parameter = para_data.get("parameter", [])
                        if type(parameter) == str:
                            parameter = json.loads(parameter)

                        page = 0
                        for data in parameter:
                            page += 1
                            order_id = get_uuid1()

                            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')
                            logger.info(attributes)
                            try:
                                unit = attributes.get('单位', '')
                                unit_price = float(attributes.get('单价', ''))
                                number = int(attributes.get('数量', ''))
                                subtotal = float(attributes.get('小计', ''))
                                total = float(attributes.get('总价', ''))
                                note = attributes.get('备注', '')
                                model = attributes.get('型号', '')
                                brand = attributes.get('品牌', '')
                            except Exception as attribute_deal_error:
                                logger.error(attribute_deal_error)
                                unit = ''
                                unit_price = 0.0
                                number = 0
                                subtotal = 0.0
                                total = 0.0
                                note = ''
                                model = ''
                                brand = ''

                            temp = {
                                'project':
                                data.get('project'),
                                'id':
                                order_id,
                                'attribute':
                                json.dumps(attributes, ensure_ascii=False),
                                'serviceId':
                                second_service_id,
                                'unit':
                                unit,
                                'unit_price':
                                unit_price,
                                'number':
                                number,
                                'subtotal':
                                subtotal,
                                'total':
                                total,
                                'note':
                                note
                            }
                            db_transaction_util.begin()
                            logger.info('增加销售数据')
                            logger.info(temp.__str__())
                            logger.info(save_data.__str__())
                            sale_id = sale_handler.add_sale_info(
                                dict(temp, **save_data))

                            service_attributes = service_handler.get_attribute_by_service(
                                second_service_id)
                            all_required_attr = attribute_handler.get_all_required_attributes(
                            )
                            required_attr_list = []
                            for attr in all_required_attr:
                                required_attr_list.append(attr[1])

                            logger.info('增加销售扩展属性')
                            for srv_attr in service_attributes:
                                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(
                                        sale_id, attr_id,
                                        attributes.get(attr_name, ''))

                            # 库存信息更新
                            logger.info('更新库存信息')
                            stock_service.refresh_stock_info(
                                sale_id, brand, model, number, unit,
                                second_service_id)

                            # 回访设置
                            if data.get("callbackTime"):
                                logger.info('增加回访信息')
                                customer_handler.add_return_visit_data(
                                    data.get("callbackTime"), car_phone,
                                    car_id, car_user, today)
                            db_transaction_util.commit()
                    except Exception as add_error:
                        logger.error(add_error)
                        logger.error('traceback.format_exc():\n{}'.format(
                            traceback.format_exc()))
                        db_transaction_util.rollback()
                        raise ApiException(ErrorCode.ParameterMiss)

                    try:
                        p = "defaultPrinter"  # 打印机名称
                        html, page_height = self.preview_html(para_data, True)
                        logger.info('\n' + html)
                        Printer.printing(p, html, page_height)
                    except:
                        pass

                    return set_return_dicts({"orderNo": order_no})

                elif keyword == 'preview':
                    html = self.preview_html(para_data)
                    logger.info('\n' + 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":

                    check_order_id = para_data.get("checkOrderId")
                    if not check_order_id:
                        raise ApiException(ErrorCode.ParameterMiss)

                    if self.connect:
                        result_dict = SocketServer("orderdetail {} {}".format(
                            self.storeId, check_order_id))

                    else:
                        result = get_sale_info_by_one_key(
                            "orderCheckId", check_order_id)
                        result_list = list()

                        result_dict = {}
                        if result:
                            created_time = ''
                            car_id = ''
                            car_user = ''
                            car_phone = ''
                            car_model = ''
                            total_price = 0
                            order_no = ''
                            for data in result:
                                attribute = OrderedDict()
                                for attr in sale_item_handler.get_item_info_buy_sale_id(
                                        data['sale_id']):
                                    attribute[
                                        attr['name']] = attr['attribute_value']
                                logger.info('销售数据属性调整后的记录:' +
                                            attribute.__str__())
                                created_time = data['createdTime']
                                car_id = data['carId']
                                car_user = data['carUser']
                                car_phone = data['carPhone']
                                car_model = data['carModel']
                                price = data['unit_price']
                                pc_id = data['pcId']
                                order_no = data['orderNo']
                                if pc_id:
                                    total_price += price
                                    attribute['project'] = data['project']
                                    attribute['totalPrice'] = price
                                    attribute['orderNo'] = order_no
                                    result_list.append(attribute)

                            try:
                                pc_sign = config.get_store_name()
                            except:
                                pc_sign = ""
                            result_dict = {
                                "msg": result_list,
                                "totalPrice": total_price,
                                "createdTime": created_time,
                                "carId": car_id,
                                "carUser": car_user,
                                "carPhone": car_phone,
                                "carModel": car_model,
                                "orderNo": order_no,
                                "checkOrderId": check_order_id,
                                "pcSign": pc_sign,
                            }

                    if result_dict == 'restart':
                        raise ApiException(ErrorCode.ReStartPC)
                    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'])
Example #3
0
def ImportExcel(fileName, self):
    # 用于正则判断是否是用软件导出的excel文档
    pattern = re.compile(r"^门店系统:\d{4}[-/]\d{2}[/-]\d{2}至\d{4}[-/]\d{2}[/-]\d{2}$")
    # matchs = pattern.match()
    bk = xlrd.open_workbook(fileName)
    try:
        sh = bk.sheet_by_name("消费列表")
    except:
        sh = bk.sheet_by_name("Sheet1")
    nrows = sh.nrows
    temp = list()
    titleList = ['检索ID', 'orderNo', 'createdTime', "pcSign", "carId", "carUser", "carPhone", "carModel", "workerName",
                 "project"]
    userList = ["carId", "carUser", "carPhone", "carModel"]
    mustlen = len(titleList)
    check = str(sh.row_values(0)[0])
    matchs = pattern.match(check)
    title = sh.row_values(1)
    progress_dialog = QProgressDialog(self)
    progress_dialog.setWindowTitle("导入中")
    progress_dialog.setWindowModality(Qt.WindowModal)
    progress_dialog.setMinimumDuration(4)
    progress_dialog.setWindowTitle(self.tr("请等待"))
    progress_dialog.setLabelText(self.tr("导入中..."))
    progress_dialog.setCancelButtonText(self.tr("取消"))
    progress_dialog.setRange(0, nrows - 3)
    progress_dialog.show()
    if True:
        p = 0
        msgList = list()
        for i in range(2, nrows):
            # 用正则表达式判断第一行数据内容,从而判断是否用软件导出的EXCEL文档
            if matchs:
                # 若是用软件导出的则
                if progress_dialog.wasCanceled():
                    break
                progress_dialog.setValue(p)
                p += 1
                try:
                    # if True:
                    saveData = dict()
                    row_data = sh.row_values(i)
                    if i < nrows - 1:
                        temp2 = sh.row_values(i + 1)
                    else:
                        temp2 = None

                    if temp2 != None and temp2[0] == '':
                        # 合并了单元格则合并内容是空,将后面不是空的内容进行缓存,合并的内容会在最后一条信息中显示,
                        # 此时一并进行录入
                        temp.append(row_data)
                    else:

                        # if row_data[0] != '':
                        if temp:
                            orderCheckId = temp[0][0]
                        else:
                            orderCheckId = row_data[0]
                        checkOrder = get_sale_info_by_one_key("orderCheckId", orderCheckId)
                        # 有此订单的就不保存了
                        if not checkOrder:
                            if temp:
                                temp.append(row_data)
                                allMsg = temp[0]
                                # 接入信息后录入
                                for i in range(len(temp)):
                                    if i != 0:
                                        msg = temp[i]
                                        attribute = {}
                                        for ki in range(len(title)):

                                            allMsg[ki] = str(allMsg[ki])
                                            msg[ki] = str(msg[ki])
                                            if ki < mustlen:
                                                tempK = titleList[ki]
                                                if tempK in ['orderNo', 'carPhone']:
                                                    allMsg[ki] = allMsg[ki].replace('.0', "")
                                                    msg[ki] = msg[ki].replace('.0', "")
                                                if titleList[ki] in ["project"]:
                                                    saveData[tempK] = msg[ki]
                                                else:
                                                    if tempK == "检索ID":
                                                        tempK = "orderCheckId"
                                                    saveData[tempK] = allMsg[ki]
                                            else:
                                                if row_data[ki] == "" or row_data[ki] == "-":
                                                    continue
                                                attribute[title[ki]] = msg[ki]

                                        saveData['attribute'] = json.dumps(attribute)
                                        saveData['id'] = get_uuid1()
                                        dbhelp.add_sale_info(saveData)

                                    row_data = allMsg
                            attribute = {}
                            userSave = {}
                            for ki in range(len(title)):
                                row_data[ki] = str(row_data[ki])
                                if ki < mustlen:
                                    if titleList[ki] in ['orderNo', 'carPhone']:
                                        row_data[ki] = row_data[ki].replace('.0', "")
                                    key = titleList[ki]
                                    if key == "检索ID":
                                        key = "orderCheckId"
                                    saveData[key] = row_data[ki]
                                    # 保存用户信息
                                    if key in userList:
                                        userSave[key] = row_data[ki]

                                else:
                                    if row_data[ki] == "" or row_data[ki] == "-":
                                        continue
                                    attribute[title[ki]] = row_data[ki]

                            user = check_customer(userSave.get("carPhone"), userSave.get("carId"))
                            if not user:
                                # 没有此用户则添加
                                key = "userName,carPhone,carModel,carId,createdTime"
                                value = "'{}','{}','{}','{}','{}'".format(userSave.get("carUser"),
                                                                          userSave.get("carPhone"),
                                                                          userSave.get("carModel"),
                                                                          userSave.get("carId"), get_now())
                                try:
                                    # pass
                                    dbhelp.InsertData("User", key, value)
                                except:
                                    pass

                            saveData['attribute'] = json.dumps(attribute)
                            saveData['id'] = get_uuid1()
                            sale_handler.add_sale_info(saveData)

                        # 清空缓存
                        temp = list()
                        # if i == nrows - 1:
                    # 此时是最后一组,则要进行录入

                    # else:
                    #     #合并了单元格则合并内容是空,将后面不是空的内容进行缓存,合并的内容会在最后一条信息中显示,此时一并进行录入
                    #     temp.append(row_data)
                except:
                    continue
            else:
                # 若不是用软件导出的EXCEL文档则

                # for i in range(2,nrows):
                # 先整理参数,全部变成列表,列表里面是字典,字典的key就是title
                try:
                    row_data = sh.row_values(i)
                    tempData = dict()

                    for k in range(len(title)):
                        tempData[title[k]] = row_data[k]
                    msgList.append(tempData)
                except:
                    continue

        if not matchs:
            saveList = defaultdict(list)
            for msg in msgList:
                if not msg.get("消费时间") or not msg.get("车牌号"):
                    continue

                key = msg.get("消费时间") + msg.get("车牌号")
                saveList[key].append(msg)

            # 插入信息
            must = ["订单号", "接待门店", "车牌号", "车主姓名", "联系电话", "车型", "操作人员", "消费项目", "消费时间"]
            for k, v in saveList.items():
                if progress_dialog.wasCanceled():
                    break
                progress_dialog.setValue(p)
                p += 1
                orderCheckId = get_uuid1()
                # 对同一个订单进行录入
                userSave = {}
                for tempDict in v:
                    orderNo = str(tempDict.pop("订单号")) if tempDict.get("订单号", "") != "" else "-"
                    pcSign = tempDict.pop("接待门店", "") if tempDict.get("接待门店", "") != "" else "-"
                    carId = tempDict.pop("车牌号") if tempDict.get("车牌号") != "" else "-"
                    carUser = tempDict.pop("车主姓名", "") if tempDict.get("车主姓名", "") != "" else "-"
                    carPhone = str(tempDict.pop("联系电话", "-")).replace(".0", "") if tempDict.get("联系电话",
                                                                                                "") != "" else "-"
                    carModel = tempDict.pop("车型", "") if tempDict.get("车型", "") != "" else "-"
                    workerName = tempDict.pop("操作人员", "") if tempDict.get("操作人员", "") != "" else "-"
                    project = tempDict.pop("消费项目", "") if tempDict.get("消费项目", "") != "" else "-"
                    createdTime = str(tempDict.pop("消费时间")).replace(".", "-")
                    # 保存用户信息
                    userSave["carId"] = carId if carId != '-' else ""
                    userSave["carUser"] = carUser if carUser != '-' else ""
                    userSave["carPhone"] = (carPhone if carPhone != '-' else "").replace(".0", "")
                    userSave['carModel'] = carModel if carModel != '-' else ""

                    if orderNo != "-":
                        checkOrder = get_sale_info_by_one_key("orderNo", orderNo)
                        if checkOrder:
                            break

                    saveData = {
                        "orderNo": orderNo.replace(".0", ""),
                        "createdTime": createdTime,
                        "pcSign": pcSign,
                        "carId": carId,
                        "carUser": carUser,
                        "carPhone": carPhone,
                        "carModel": carModel,
                        "workerName": workerName,
                        "project": project,
                        "orderCheckId": orderCheckId,
                        "id": get_uuid1(),
                    }
                    tempAttribute = tempDict

                    attribute = dict()
                    for k, v in tempAttribute.items():
                        if k not in must:
                            if v == "":
                                # v = '-'
                                continue
                            attribute[k] = str(v)
                    try:
                        gsf = float(attribute.get("工时费")) if attribute.get("工时费") != "" else 0
                        sl = float(attribute.get("数量")) if attribute.get("数量") != "" else 0
                        dj = float(attribute.get("单价")) if attribute.get("单价") != "" else 0
                        attribute["总价"] = gsf + sl * dj
                    except:
                        pass
                    saveData["attribute"] = json.dumps(attribute)
                    dbhelp.add_sale_info(saveData)

                if userSave.get("carId") and userSave.get("carPhone"):
                    # 当有用户信息的时候判断是否需要自动添加
                    user = check_customer(userSave.get("carPhone"), userSave.get("carId"))
                    if not user:
                        # 没有此用户则添加
                        key = "userName,carPhone,carModel,carId,createdTime"
                        value = "'{}','{}','{}','{}','{}'".format(userSave.get("carUser"), userSave.get("carPhone"),
                                                                  userSave.get("carModel"), userSave.get("carId"),
                                                                  get_now())
                        try:
                            # pass
                            dbhelp.InsertData("User", key, value)
                        except:
                            pass
        # 最后全部导入
        progress_dialog.setValue(nrows - 3)
        progress_dialog.close()
Example #4
0
    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'])