Ejemplo n.º 1
0
def pre_check():
    result = False
    local_code = config.get_local_register_code()

    if common.compare_local_code_with_remote_register(local_code):
        result = True

    return result
Ejemplo n.º 2
0
    def worker(self, keyword, get_data):
        try:
            if self.request.method == 'POST':
                if keyword == "code":
                    code = get_data.get("code", "").strip()

                    local_code = config.get_local_register_code()
                    if code != "" and local_code == 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'])
Ejemplo n.º 3
0
def print_html(printer):
    try:
        if not myconnect:
            raise ApiException(ErrorCode.ErrorRequest)
        code = config.get_local_register_code()
        url = domain + "store/api/detail?code={}".format(code)
        req = requests.get(url=url)
        result_data = json.loads(req.text)
    except Exception as e:
        logger.error(e.__str__())

        store = config.get_local_store_info()

        result_data = {
            'data': {
                "pcId": store.id(),
                "pcPhone": store.phone(),
                "pcAddress": store.address(),
                "pcSign": store.name(),
            },
            'code': 200
        }
    mustSet = ['数量', '单价', '小计', '总价', '单位', '备注']

    if result_data.get("code") != 200:
        storeName = ""
        pcAddress = ""
        pcPhone = ""
    else:
        storeName = result_data.get("data").get("pcSign", "")
        pcAddress = result_data.get("data").get("pcAddress", "")
        pcPhone = result_data.get("data").get("pcPhone", "")
    result = get_sale_info_by_one_key("orderCheckId", selectOrderNo)

    font_size = config.get_print_font_size()

    # *{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(font_size) + "pt;}" + ".bigWord{font-size:" + str(
            font_size * 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)
Ejemplo n.º 4
0
    def preview_html(self, get_data, get_height=False):
        if get_data.get("createdTime"):
            today = get_data.get("createdTime")
        else:
            today = datetime.now()

        if get_data.get("orderNo"):
            order_no = get_data.get("orderNo")
        else:
            order_no = sale_handler.get_sale_order_no(today)

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

        car_id = get_data.pop("carId", "1")
        car_phone = get_data.pop("carPhone", "1")
        store_name = get_data.pop("pcSign", "1")

        try:
            if not self.connect:
                raise ApiException(ErrorCode.ErrorRequest)
            code = config.get_local_register_code()
            url = domain + "store/api/detail?code={}".format(code)
            req = requests.get(url=url)
            result_data = json.loads(req.text)
        except Exception as exception:
            logger.error(exception)
            store = config.get_local_store_info()

            result_data = {
                'data': {
                    "pcId": store.id(),
                    "pcPhone": store.phone(),
                    "pcAddress": store.address(),
                    "pcSign": store.name(),
                },
                'code': 200
            }
        if result_data.get("code") != 200:
            store_address = ""
            store_phone = ""
        else:
            store_address = result_data.get("data").get("pcAddress", "")
            store_phone = result_data.get("data").get("pcPhone", "")

        font_size = config.get_print_font_size()

        header = """<html>
    <head>
        <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(
            font_size) + "pt;}" + "\n            .bigWord{font-size: " + str(
                font_size *
                1.5) + "pt;\n            }" + "\n        </style>\n   </head>"

        # 总长度要减去备注和名称,因为名称长度另外设置,备注不打印
        td_width = 19
        logger.info('begin body')
        body = """\n    <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=store_name, carId=car_id, createdTime=today.strftime("%Y-%m-%d %H:%M:%S"),
                    carPhone=car_phone, orderNo=order_no)

        logger.info('begin make attribute')
        target_content = ""
        sequence = 1
        total_price = 0
        page_height = 100
        td_indent = '''                    '''
        tr_indent = '''                '''
        for order in parameter:
            attribute = order.get("attribute")
            base_height = 180

            # 按照系统给定的打印顺序排序
            need_print_attributes = attribute_handler.get_all_need_print_attr()

            # 拼接打印预览的表格头部和值
            key_td_str = td_indent + '''<td colspan=''' + str(
                td_width) + '''" align="center">{key}</td>'''
            value_td_str = td_indent + '''<td colspan="''' + str(
                td_width) + '''" align="center">{value}</td>'''
            first_key_str = td_indent + '''<td colspan="5" align="center">序</td>'''
            first_value_str = td_indent + '''<td rowspan="{seq_row_span}" colspan="5" align="center">{seq}</td>'''

            value_td_list = [key_td_str.format(key=order.get("project"))]
            key_td_list = [value_td_str.format(value='名称')]
            for print_attr in need_print_attributes:
                key = print_attr['name']
                value = attribute.get(key, '')

                # 是否必须显示,如果是,即便为空也要打印,否则不为空且值不为'-'才打印
                is_required = print_attr['is_required']
                if not is_required and (not value or value == '-'
                                        ) or print_attr['print_order'] == 1000:
                    continue

                key_td_list.append(key_td_str.format(key=key))
                value_td_list.append(value_td_str.format(value=value))

            row_num = len(key_td_list)

            # 补齐最后一行空缺的单元格
            for i in range(5 - row_num % 5):
                key_td_list.append(key_td_str.format(key=''))
                value_td_list.append(value_td_str.format(value=''))

            # 序号列合并行数
            seq_row_span = int(row_num / 5 + 1) * 2

            # 打印所需的高度
            page_height += int(row_num / 5 + 1) * 60 + base_height

            # 拼凑消费项目打印所需HTML
            logger.info('拼凑消费项目打印所需HTML')
            first_value_str = first_value_str.format(seq_row_span=seq_row_span,
                                                     seq=sequence)
            key_content = tr_indent + '''<tr style="font-weight:800">\n'''
            value_content = tr_indent + '''<tr style="font-weight:800">\n'''
            for index, td_str in enumerate(key_td_list):

                if not index:
                    key_content += first_key_str + '\n'
                    value_content += first_value_str + '\n'

                key_content += td_str + '\n'
                value_content += value_td_list[index] + '\n'

                if not (index + 1) % 5:
                    target_content += key_content + tr_indent + '''</tr>\n'''
                    target_content += value_content + tr_indent + '''</tr>\n'''
                    key_content = tr_indent + '''<tr style="font-weight:800">\n'''
                    value_content = tr_indent + '''<tr style="font-weight:800">\n'''

            separator = tr_indent + """<tr><td colspan="100" height="20px"> </td></tr>\n"""
            total_price_content = tr_indent + """<tr><td colspan="95">总价:{total_price}</td></tr>\n""" \
                .format(total_price=attribute.get('总价', ""))

            target_content += total_price_content
            target_content += separator

            sequence += 1
            total_price += float(attribute.get('总价', 0))

        logger.info('end make attribute')
        total_price = str(total_price)
        cn = cncurrency(total_price)

        logger.info('拼凑消费项目总计消费HTML')
        foot = tr_indent + '''<tr>
                    <td style="height:35px" colspan="70">合计人名币(大写):{cn}</td>
                    <td style="height:35px"  colspan="30">小写:{total_price}</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, total_price=total_price, storeName=store_name, pcPhone=store_phone, pcAddress=store_address)

        html = header + body + target_content + foot
        logger.info('add str end')
        if get_height:
            return html, page_height
        else:
            return html
Ejemplo n.º 5
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'])
Ejemplo n.º 6
0
    def change_state(self):
        remarks = self.remark.text().strip()
        if not remarks:
            QtWidgets.QMessageBox.information(self.submit_set, "提示", "请输入备注")
        else:
            today = datetime.now()
            get_data = {}
            order_no = sale_handler.get_order_no(today)
            get_data["orderNo"] = order_no
            get_data["createdTime"] = today
            get_data["carUser"] = self.car_user
            get_data["carId"] = self.car_id
            get_data["carPhone"] = self.car_phone

            car_user = get_data.get("carUser", '-')
            user_id = get_data.get("userId", '-')
            worker_id = get_data.get("workerId", "-")
            pc_id = get_data.get("pcId", "-")
            car_phone = get_data.get("carPhone", "-")
            car_model = get_data.get("carModel", "-")
            car_id = get_data.get("carId", "-")
            pc_sign = get_data.get("pcSign", '-')
            worker_name = get_data.get("workerName", '-')
            order_check_id = get_uuid1()
            order_id = get_uuid1()
            save_data = {
                'createdTime':
                get_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(),
                'attribute':
                json.dumps({"回访备注": remarks}),
                'project':
                get_data.get('project', '-'),
                'id':
                order_id
            }

            sale_handler.add_sale_detail(save_data)

            # 更新回访状态,标记已回访
            customer_handler.update_return_visit_state(self.id, '1')

            # 如果填写了二次回访时间,则写入一条待回访数据
            if self.do_set_next_date.isChecked():
                # 回访设置
                time_str = self.next_date.text()
                time_list = time_str.split('/')
                # XP上的时间是以-分割的
                if len(time_list) < 3:
                    time_list = time_str.split("-")
                # 有时候年份会在以后一个,如:03-25-2016,此时查询数据将出错,因此要判断一下
                if len(time_list[2]) == 4:
                    mon = time_list[0]
                    day = time_list[1]
                    time_list[0] = time_list[2]
                    time_list[1] = mon
                    time_list[2] = day

                time_str = ""
                for t in time_list:
                    if len(t) < 2:
                        t = "0" + t
                    time_str += t + "-"
                time_str = time_str[:-1]
                customer_handler.add_return_visit_data(time_str, car_phone,
                                                       car_id, car_user, today)

            self.close()
Ejemplo n.º 7
0
    def export_sale_detail(self, start_time, end_time, remote=False):
        now = get_now()
        file_name = now + ".xls"

        # 获取消费信息
        sale_detail_list = []
        if remote:
            # 获取远程信息
            code = config.get_local_register_code()
            keyword = "xiaofei {} {} {}".format(code, start_time, end_time)
            # python3传递的是bytes,所以要编码
            try:
                sale_detail_list = SocketServer(keyword)
            except Exception as e:
                logger.error(e.__str__())
                logger.error('traceback.format_exc():\n{}'.format(
                    traceback.format_exc()))
        else:
            sale_detail_list = self.database_handler.GetXiaoFeiTable(
                start_time, end_time, Table=False)

        # 填入数据
        if sale_detail_list:
            # 插入信息
            sale_detail_list.sort(key=lambda obj: obj[2], reverse=True)
            order_check_id = None
            merge_list = list()
            temp_msg = dict()
            temp = list()
            # 设置表头
            title_list = [
                "检索ID", '订单号', u'消费时间', "消费门店", u"车牌号", u"车主姓名", u"联系电话",
                u"车型", u"操作人员", u"消费项目"
            ]

            table_len = len(title_list)
            header = ['数量', '单价', '小计', '总价', '单位', '备注']
            for data in sale_detail_list:
                try:
                    attribute = json.loads(data[10])
                    for k, v in attribute.items():
                        if k not in header:
                            header.append(k)
                except Exception as e:
                    logger.error(e.__str__())
                    logger.error('traceback.format_exc():\n{}'.format(
                        traceback.format_exc()))
                    continue
            title_list = title_list + header
            all_table_len = len(title_list)

            wb = xlwt.Workbook()
            ws = wb.add_sheet('消费列表', cell_overwrite_ok=True)
            title = set_style('Arial', 250, True, True)
            default = set_style('SimSun', 180, True, True, True)
            top = set_style('Times New Roman', 350, True, True)
            # 前两个参数表示需要合并的行范围,后两个参数表示需要合并的列范围
            # 合并单元格作为大标题,水平居中即可
            start_time = format_time(start_time)[:10]
            end_time = format_time(end_time)[:10]
            ws.write_merge(0, 0, 0, all_table_len - 1,
                           '门店系统:{}至{}'.format(start_time, end_time), top)

            # 设置标题
            for i in range(all_table_len):
                # 设置单元格宽度
                ws.col(i).width = 265 * 20
                # 插入标题
                ws.write(1, i, title_list[i], title)

            # 从第二行开始插
            row = 2

            for data in sale_detail_list:
                if order_check_id:
                    # 如果记录的订单号与当前数据的订单号不同,则进行录入并修改记录订单号
                    if order_check_id != data[0]:
                        order_check_id = data[0]

                        # 因为订单号变了所以之前的缓存清空,换成这个订单号的索引
                        temp = [row]
                    else:
                        # 若已经缓存了2个索引则代表此订单号有>2个商品,所以更新第二个索引保留第一个索引
                        if len(temp) >= 2:
                            temp[1] = row
                        else:
                            temp.append(row)
                else:
                    # 若第一次进来,此时订单号是None,进行录入
                    order_check_id = data[0]
                    temp.append(row)

                # 插入信息
                for j in range(table_len):
                    ws.write(row, j, data[j], default)
                    if j == table_len - 1:
                        # 最后一个的时候遍历填入数据
                        try:
                            j += 1
                            attribute = json.loads(data[j])
                            for k in header:
                                ws.write(row, j, attribute.get(k, ""), default)
                                j += 1
                        except Exception as e:
                            logger.error(e.__str__())
                            logger.error('traceback.format_exc():\n{}'.format(
                                traceback.format_exc()))
                            continue
                row += 1
                # 如果已经缓存了2个数字,则代表有重复的订单号,所以此时进行记录并合并
                if len(temp) >= 2:
                    temp_msg[temp[0]] = MakeTempMsg(data)
                    merge_list.append(temp)

            if len(temp) >= 2:
                merge_list.append(temp)
                temp_msg[temp[0]] = MakeTempMsg(data)
            for hb in merge_list:
                ws.write_merge(hb[0], hb[1], 0, 0,
                               temp_msg[hb[0]].get("checkOrderId"), default)
                ws.write_merge(hb[0], hb[1], 1, 1,
                               temp_msg[hb[0]].get("orderNo"), default)
                ws.write_merge(hb[0], hb[1], 2, 2,
                               temp_msg[hb[0]].get("createdTime"), default)
                ws.write_merge(hb[0], hb[1], 3, 3,
                               temp_msg[hb[0]].get("pcSign"), default)
                ws.write_merge(hb[0], hb[1], 4, 4,
                               temp_msg[hb[0]].get("carId"), default)
                ws.write_merge(hb[0], hb[1], 5, 5,
                               temp_msg[hb[0]].get("carUser"), default)
                ws.write_merge(hb[0], hb[1], 6, 6,
                               temp_msg[hb[0]].get("carPhone"), default)
                ws.write_merge(hb[0], hb[1], 7, 7,
                               temp_msg[hb[0]].get("carModel"), default)
                ws.write_merge(hb[0], hb[1], 8, 8,
                               temp_msg[hb[0]].get("workerName"), default)

            if not os.path.exists(savePath):
                os.mkdir(savePath)
            wb.save(savePath + file_name)

            return file_name
        else:
            return False