Exemplo n.º 1
0
 def wrapper(self, request, *args, **kwargs):
     pk = kwargs.get('pk')
     instance = None
     if pk:
         try:
             instance = model_class.objects.get(pk=pk)
         except TypeError:
             return APIResponse(success=False, msg='serializer_class类型错误')
         except Exception as ex:
             return APIResponseNotFound(msg='未找到')
     serializer = serializer_class(data=request.data, instance=instance, user=request.user, request=request)
     if not serializer.is_valid():
         errors = [key + ':' + value[0] for key, value in serializer.errors.items() if isinstance(value, list)]
         if errors:
             error = errors[0]
             error = error.lstrip(':')
         else:
             for key, value in serializer.errors.items():
                 if isinstance(value, dict):
                     key, value = value.popitem()
                     error = key + ':' + value[0]
                     break
         return APIResponse(success=False, msg=error)
     kwargs['serializer'] = serializer
     kwargs['instance'] = instance
     return view_func(self, request, *args, **kwargs)
Exemplo n.º 2
0
def payment_order(serializer, guest_id):
    trade_no = serializer.data['trade_no']
    pay_type = serializer.data['pay_type']
    order_sn = serializer.data['order_sn']
    order = Order.objects.get(order_sn=order_sn)
    order_operation = OrderOperationRecord.objects.filter(order_sn=order_sn, status=2)
    if order_operation:
        response = APIResponse(data={}, success=False, msg='订单[%s]已经支付,无需重复支付' % order_sn)
        return response
    orders = OrderDetail.objects.filter(order=order.id, status=1)
    OrderPayment.objects.create(order_sn=order_sn, pay_type=pay_type, trade_no=trade_no, pay_status=2)
    OrderOperationRecord.objects.create(order_sn=order_sn, status=2, operator=guest_id,
                                        execution_detail='用户[%s]对订单[%s]执行支付操作,使用[%s]方式支付' % (
                                            guest_id, order_sn, PAY_TYPE[pay_type]), progress='已支付')
    for order in orders:
        # OrderOperationRecord.objects.create(order_sn=order.son_order_sn, status=2, operator=guest_id,
        #                                     execution_detail=PAY_TYPE[pay_type], progress='已支付')
        # # 创建一条系统记录
        # OrderOperationRecord.objects.create(order_sn=order.son_order_sn, status=4, operator=0,
        #                                     execution_detail='接单提醒', progress='已支付')
        OrderOperationRecord.objects.create(order_sn=order.son_order_sn, status=2, operator=guest_id,
                                            execution_detail='用户[%s]对订单[%s]执行支付操作,使用[%s]方式支付' % (
                                                guest_id, order.son_order_sn, PAY_TYPE[pay_type]), progress='已支付')
        OrderPayment.objects.create(order_sn=order.son_order_sn, pay_type=pay_type, trade_no=trade_no, pay_status=2)
        order.status = 3
        order.save()
    response = APIResponse(data={}, success=True, msg='订单支付状态修改成功')
    return response
Exemplo n.º 3
0
def predict_image(request):
    url = request.data.get('url', '')
    if not url:
        response = APIResponse(success=False, data={}, msg='url为必填字段')
        return response
    if 'http' not in url:
        url = CDN_HOST + url
    file_path = download(url)
    if not file_path:
        response = APIResponse(success=False,
                               data={},
                               msg='图片地址(%s)不存在' % CDN_HOST + url)
        return response
    try:
        predictions = turi.predict(file_path)
    except Exception as e:
        print(e)
        logger.info(e)
        clear_file(file_path)
        response = APIResponse(success=False,
                               msg='该文件格式无法进行解码(原因:非标准编码的图片格式/或图片格式有损)')
        return response
    if not WeldingImage.objects.filter(url=url):
        welding = WeldingImage.objects.create(url=url,
                                              predict_label=predictions)
    else:
        welding = WeldingImage.objects.filter(url=url).first()
    clear_file(file_path)
    data = {'predict': predictions, 'id': welding.id}
    response = APIResponse(success=True, data=data)
    return response
Exemplo n.º 4
0
def deal_supplier_operation(abnormal_type, order_sn, original_delivery_time,
                            expect_date_of_delivery, operator, serializer, remarks):
    # 无货
    if abnormal_type == 1:
        order_detail = OrderDetail.objects.get(son_order_sn=order_sn)
        now = datetime.now()
        order_operation = OrderOperationRecord.objects.filter(order_sn=order_sn).order_by('-add_time')
        time_consuming = float(now.timestamp() - order_operation[0].add_time.timestamp())
        OrderOperationRecord.objects.create(order_sn=order_sn, status=8,
                                            operator=operator,
                                            execution_detail='供应商[%s]执行订单[%s]申请无货操作' %
                                                             (order_detail.supplier_id, order_sn),
                                            progress='待接单,无货', time_consuming=time_consuming, is_abnormal=True)
        try:
            abnormal_order = AbnormalOrder.objects.get(order_sn=order_sn, abnormal_type=1)
            abnormal_order.is_deal = 1
            abnormal_order.remarks = remarks
            abnormal_order.save()
        except Exception as e:
            AbnormalOrder.objects.create(order_sn=order_sn, abnormal_type=1, remarks=remarks, is_deal=1)
        order_detail.status = 13
        order_detail.save()
    else:
        order_detail = OrderDetail.objects.get(son_order_sn=order_sn)
        expect_date_of_delivery = datetime.strptime(expect_date_of_delivery, '%Y-%m-%d')
        original_delivery_time = (order_detail.add_time + timedelta(
            days=order_detail.max_delivery_time))
        if expect_date_of_delivery <= original_delivery_time:
            response = APIResponse(success=False, data={}, msg='传入的时间有误')
            return response
        order_detail.max_delivery_time = (expect_date_of_delivery - original_delivery_time).days
        now = datetime.now()
        order_operation = OrderOperationRecord.objects.filter(order_sn=order_sn).order_by('-add_time')
        time_consuming = float(now.timestamp() - order_operation[0].add_time.timestamp())
        OrderOperationRecord.objects.create(order_sn=order_sn, status=10,
                                            operator=operator,
                                            execution_detail='供应商[%s]执行订单[%s]申请延期操作' %
                                                             (order_detail.supplier_id, order_sn),
                                            progress='申请延期', time_consuming=time_consuming, is_abnormal=True)
        try:
            abnormal_order = AbnormalOrder.objects.get(order_sn=order_sn, abnormal_type=2)
            abnormal_order.remarks = remarks
            abnormal_order.is_deal = 1
            abnormal_order.remarks = remarks
            abnormal_order.original_delivery_time = original_delivery_time
            abnormal_order.expect_date_of_delivery = expect_date_of_delivery
            abnormal_order.save()
        except Exception as e:
            AbnormalOrder.objects.create(order_sn=order_sn, abnormal_type=2, remarks=remarks, is_deal=1,
                                         original_delivery_time=original_delivery_time,
                                         expect_date_of_delivery=expect_date_of_delivery)
        order_detail.status = 8
        order_detail.save()
    response = APIResponse(success=True, data={})
    return response
Exemplo n.º 5
0
    def post(self, request):
        # 如果extras是json就转str存入数据库
        if 'extras' in request.data.keys():
            if isinstance(request.data['extras'], dict):
                request.data['extras'] = json.dumps(request.data['extras'])

        serializer = ImportRecordSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return APIResponse(rescode=res_code['success'],
                               data=serializer.data)
        return APIResponse(rescode=res_code['error'], data=serializer.errors)
Exemplo n.º 6
0
def get_son_order_detail(instance, guest_id):
    data = []
    _instance = instance
    instance = Order.objects.filter(pk=instance.order)
    if instance[0].guest_id != int(guest_id):
        response = APIResponse(success=False, data={})
        return response
    result = {}
    receipt = Receipt.objects.get(pk=instance[0].receipt)
    result['receipt_title'] = receipt.title
    result['account'] = receipt.account
    result['tax_number'] = receipt.tax_number
    result['telephone'] = receipt.telephone
    result['bank'] = receipt.bank
    result['company_address'] = receipt.company_address
    result['receipt_type'] = receipt.receipt_type
    result['guest_id'] = instance[0].guest_id
    result['total_money'] = instance[0].total_money
    result['add_time'] = instance[0].add_time.date()
    now = datetime.now()
    delta = timedelta(days=7)
    count_down = instance[0].add_time + delta - now
    result['order_sn'] = instance[0].order_sn
    result['count_down'] = count_down
    sub_order = []
    __dict = {}
    abnormal_delay_order = AbnormalOrder.objects.filter(order_sn=_instance.son_order_sn,
                                                        abnormal_type=2,
                                                        is_deal=2, is_pass=True)
    abnormal_no_order = AbnormalOrder.objects.filter(order_sn=_instance.son_order_sn,
                                                     abnormal_type=1,
                                                     is_deal=2, is_pass=True)
    if not abnormal_delay_order and _instance.status == 8:
        _status = '待接单'
    elif not abnormal_no_order and _instance.status == 13:
        _status = '待接单'
    else:
        _status = ORDER_STATUS[_instance.status]
    pay_status = OrderPayment.objects.filter(order_sn=_instance.son_order_sn).order_by('-add_time')[
        0].pay_status
    __dict['son_order_sn'] = _instance.son_order_sn
    __dict['number'] = _instance.number
    __dict['univalent'] = _instance.univalent
    __dict['max_delivery_time'] = _instance.max_delivery_time
    __dict['order_status'] = _status
    __dict['pay_status'] = PAY_STATUS[pay_status]
    sub_order.append(__dict)
    result['sub_order'] = sub_order
    data.append(result)
    response = APIResponse(success=True, data=data)
    return response
Exemplo n.º 7
0
def refund_detail(order_detail, data):
    order_refund = OrderRefund.objects.filter(order_sn=order_detail.son_order_sn).order_by('-add_time')
    refund_info = {}
    if order_refund:
        order_refund = order_refund[0]
        refund_info['order_sn'] = order_refund.order_sn
        refund_info['refund_sn'] = order_refund.refund_sn
        refund_info['returns_sn'] = order_refund.returns_sn
        refund_info['amount'] = order_refund.amount
        refund_info['status'] = order_refund.status
        refund_info['freight'] = 0.0
        refund_info['add_time'] = int(order_refund.add_time.timestamp())
    operation_record = []
    for operation in OrderOperationRecord.objects.filter(status__in=[11, 12, 13, 14], order_sn=order_detail.son_order_sn):
        _op = {}
        _op['order_sn'] = operation.order_sn
        _op['status'] = operation.status
        _op['execution_detail'] = operation.execution_detail
        _op['progress'] = operation.progress
        _op['time_consuming'] = operation.time_consuming
        _op['add_time'] = int(operation.add_time.timestamp())
        operation_record.append(_op)
    data['refund_info'] = refund_info
    data['operation_record'] = operation_record
    response = APIResponse(success=True, data=data, msg='退款单详情')
    return response
Exemplo n.º 8
0
def switch_get(module, request):
    if module in ProofingModuleList:
        data = proofing_record_get(request)
    else:
        data = 'Need a parameter of module.'
        return APIResponse(rescode=res_code['error'], data=data)
    return data
Exemplo n.º 9
0
def supplier_confirm_order(order_sn):
    order_returns = OrderReturns.objects.filter(order_sn=order_sn, status=1).order_by('-add_time')
    if order_returns:
        order_return = order_returns[0]
        # 执行退款逻辑
        headers = {'content-type': 'application/json',
                   'user-agent': "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}
        parameters = json.dumps({'order_sn': order_return.order_sn})
        try:
            response = requests.post(ORDER_API_HOST + '/api/refund', data=parameters, headers=headers)
            response_dict = json.loads(response.text)
        except Exception as e:
            logger.info('ID生成器连接失败!!!')
            response = APIResponse(success=False, data={}, msg='ID生成器连接失败!!!')
            return response
        if response_dict['rescode'] != '10000':
            response = APIResponse(success=False, data={}, msg='ID生成器出错!!!')
            return response
        refund_sn = response_dict['data']['tk_order_id']

        order_return.status = 2
        order_return.save()
        order_detail = OrderDetail.objects.get(son_order_sn=order_return.order_sn)
        order_detail.status = 10
        order_detail.save()
        supplier_id = order_detail.supplier_id
        now = datetime.now()
        order_operation = OrderOperationRecord.objects.filter(order_sn=order_sn).order_by('-add_time')
        time_consuming = float(now.timestamp() - order_operation[0].add_time.timestamp())
        OrderOperationRecord.objects.create(order_sn=order_return.order_sn, status=14,
                                            operator=supplier_id,
                                            execution_detail='供应商[%s]执行订单[%s]确认收货操作' %
                                                             (order_detail.supplier_id, order_sn),
                                            progress='已收货', time_consuming=time_consuming)

        OrderRefund.objects.create(order_sn=order_detail.son_order_sn, refund_sn=refund_sn,
                                   returns_sn=order_return.returns_sn, amount=order_detail.subtotal_money, status=1)
        OrderOperationRecord.objects.create(order_sn=order_return.order_sn, status=11,
                                            operator=0,
                                            execution_detail='系统自动生成退款单',
                                            progress='退款中', time_consuming=time_consuming)
        # 通知财务系统开始退款逻辑
        pass
        response = APIResponse(success=True, data={}, msg='供应商确认收货成功,生成退款单成功')
    else:
        response = APIResponse(success=False, data={}, msg='用户尚未填写物流信息,不能执行确认收货操作')
    return response
Exemplo n.º 10
0
def user_confirm_order(instance, guest_id):
    if not isinstance(instance, OrderDetail):
        response = APIResponse(success=False, data={})
        return response
    if instance.status != 5:
        response = APIResponse(success=False, data={}, msg='当前状态不允许执行确认收货操作')
        return response
    now = datetime.now()
    order_operation = OrderOperationRecord.objects.filter(order_sn=instance.son_order_sn).order_by('-add_time')
    time_consuming = float(now.timestamp() - order_operation[0].add_time.timestamp())
    OrderOperationRecord.objects.create(order_sn=instance.son_order_sn, status=7, operator=guest_id,
                                        execution_detail='用户[%s]对订单[%s]执行确认收货操作' % (guest_id, instance.son_order_sn),
                                        progress='确认收货', time_consuming=time_consuming)
    instance.status = 6
    instance.save()
    response = APIResponse(success=True, data={}, msg='确认收货操作成功')
    return response
Exemplo n.º 11
0
def update_real_label(self, request):
    pk = self.kwargs.get('pk')
    real_label = request.data.get('label', '')
    welding = WeldingImage.objects.get(pk=pk)
    welding.real_label = real_label
    welding.save()
    response = APIResponse(success=True, msg='标记成功', data={})
    return response
Exemplo n.º 12
0
 def get(self, request):
     module = request.query_params.get('module')
     if module:
         module_prefix = module.split('_')[0]
         response = switch_get(module_prefix, request)
     else:
         data = 'Need a parameter of module.'
         return APIResponse(rescode=res_code['error'], data=data)
     return response
Exemplo n.º 13
0
def proc_post(data):
    try:
        module = data['module']
    except Exception as e:
        data = 'Need input a parameter of module.'
        return APIResponse(rescode=res_code['error'], data=data)
    module_prefix = module.split('_')[0]
    data, status = switch_post(module_prefix, data)
    return data, status
Exemplo n.º 14
0
def switch_get(module, request):
    if module in OrderModuleList:
        data = order_record_get(request)
    elif module in UserModuleList:
        data = user_record_get(request)
    elif module in ProductModuleList:
        data = product_record_get(request)
    elif module in FinanceModuleList:
        data = finance_record_get(request)
    elif module in SlnModuleList:
        data = sln_record_get(request)
    elif module in AggregatorCaseModuleList:
        data = aggregator_case_record_get(request)
    else:
        data = 'Need a parameter of module.'
        return APIResponse(rescode=res_code['error'], data=data)
    return data
Exemplo n.º 15
0
def aggregator_case_record_get(request):
    logs = AggregatorCaseRecord.objects.all()
    offset = safe_int(request.query_params.get('offset', 0))
    limit = safe_int(request.query_params.get('limit', 15))
    limit = get_limit(limit)

    module = request.query_params.get('module')
    action_flag = request.query_params.get('action_flag')
    key = request.query_params.get('key')
    platform = request.query_params.get('platform')
    start_time = request.query_params.get('start_time')
    end_time = request.query_params.get('end_time')

    if module:
        logs = logs.filter(module=module)
    if key:
        logs = logs.filter(key=key)
    if platform:
        logs = logs.filter(platform=platform)
    if action_flag:
        logs = logs.filter(action_flag=action_flag)
    if start_time and end_time:
        start_time += ' 00:00:00'
        end_time += ' 23:59:59'
        logs = logs.filter(create_time__gte=start_time).filter(
            create_time__lte=end_time)

    total = logs.count()
    logs = logs.order_by('-create_time')[offset:offset + limit]

    serializer = AggregatorCaseRecordSerializer(logs, many=True)

    # extras转为dict
    for data in serializer.data:
        if check_json_format(data['extras']):
            data['extras'] = json.loads(data['extras'])
        data['create_time'] = time.mktime(
            time.strptime(data['create_time'], '%Y-%m-%dT%H:%M:%S.%f'))

    response = APIResponse(success=True, data=serializer.data)
    # 分页数据
    response[CONTENT_RANGE] = '{0}-{1}'.format(offset, offset + len(logs))
    response[CONTENT_TOTAL] = total
    return response
Exemplo n.º 16
0
def get_mother_order_detail(instance, serializer):
    result = serializer.data
    receipt = Receipt.objects.get(pk=serializer.data['receipt'])
    result['receipt_title'] = receipt.title
    result['account'] = receipt.account
    result['tax_number'] = receipt.tax_number
    result['telephone'] = receipt.telephone
    result['bank'] = receipt.bank
    result['company_address'] = receipt.company_address
    result['receipt_type'] = receipt.receipt_type
    order_detail = OrderDetail.objects.filter(order=int(instance.id))
    sub_order = []
    for _order in order_detail:
        _sub_order = {}
        abnormal_delay_order = AbnormalOrder.objects.filter(order_sn=_order.son_order_sn,
                                                            abnormal_type=2,
                                                            is_deal=2)
        abnormal_no_order = AbnormalOrder.objects.filter(order_sn=_order.son_order_sn,
                                                         abnormal_type=1,
                                                         is_deal=2)
        if not abnormal_delay_order and _order.status == 8:
            _status = '待接单'
        elif not abnormal_no_order and _order.status == 13:
            _status = '待接单'
        else:
            _status = ORDER_STATUS[_order.status]
        _sub_order['id'] = _order.id
        _sub_order['order_sn'] = _order.son_order_sn
        _sub_order['supplier_id'] = _order.supplier_id
        _sub_order['goods_id'] = _order.goods_id
        _sub_order['model'] = _order.model
        _sub_order['brand'] = _order.brand
        _sub_order['status'] = _status
        _sub_order['number'] = _order.number
        _sub_order['univalent'] = _order.univalent
        _sub_order['price_discount'] = _order.price_discount
        _sub_order['delivery_time'] = _order.delivery_time
        _sub_order['add_time'] = _order.add_time
        sub_order.append(_sub_order)
        # 优化方法
        # sub_order.append(model_to_dict(_order))
    result['sub_order'] = sub_order
    response = APIResponse(data=result, success=True)
    return response
Exemplo n.º 17
0
    def get(self, request):
        logs = ExportRecord.objects.all()
        offset = safe_int(request.query_params.get('offset', 0))
        limit = safe_int(request.query_params.get('limit', 15))
        limit = get_limit(limit)

        file_name = request.query_params.get('file_name')
        status = request.query_params.get('status')
        operator_name = request.query_params.get('operator_name')
        start_time = request.query_params.get('start_time')
        end_time = request.query_params.get('end_time')

        if file_name:
            logs = logs.filter(file_name=file_name)
        if status:
            logs = logs.filter(status=status)
        if operator_name:
            logs = logs.filter(operator_name=operator_name)
        if start_time and end_time:
            start_time += ' 00:00:00'
            end_time += ' 23:59:59'
            logs = logs.filter(create_time__gte=start_time).filter(
                create_time__lte=end_time)

        total = logs.count()
        logs = logs.order_by('-create_time')[offset:offset + limit]

        serializer = ExportRecordSerializer(logs, many=True)

        # extras转为dict
        for data in serializer.data:
            if check_json_format(data['extras']):
                data['extras'] = json.loads(data['extras'])
            data['create_time'] = time.mktime(
                time.strptime(data['create_time'], '%Y-%m-%dT%H:%M:%S.%f'))

        response = APIResponse(success=True, data=serializer.data)
        # 分页数据
        response[CONTENT_RANGE] = '{0}-{1}'.format(offset, offset + len(logs))
        response[CONTENT_TOTAL] = total
        return response
Exemplo n.º 18
0
def returns_detail(order_detail, data):
    # 退货信息
    order_return = OrderReturns.objects.filter(order_sn=order_detail.son_order_sn).order_by('-add_time')
    return_deal = ReturnsDeal.objects.filter(order_sn=order_detail.son_order_sn).order_by('-add_time')
    return_info = {}
    return_logistics = {}
    if order_return:
        order_return = order_return[0]
        return_deal = return_deal[0]
        return_info['returns_sn'] = order_return.returns_sn
        return_info['order_sn'] = order_return.order_sn
        return_info['remarks'] = order_return.order_sn
        return_info['status'] = order_return.status
        return_info['returns_time'] = int(return_deal.add_time.timestamp())
        return_info['returns_money'] = order_detail.subtotal_money
        return_info['remarks'] = return_deal.remarks
        return_logistics['receiver'] = order_return.receiver
        return_logistics['address'] = order_return.address
        return_logistics['logistics_company'] = order_return.logistics_company
        return_logistics['logistics_number'] = order_return.logistics_number
        return_logistics['logistics_type'] = 2
        return_logistics['mobile'] = order_return.mobile
        return_logistics['sender'] = order_return.sender
    data['return_info'] = return_info
    data['return_logistics'] = return_logistics
    operation_record = []
    for operation in OrderOperationRecord.objects.filter(status__in=[12, 13], order_sn=order_detail.son_order_sn):
        _op = {}
        _op['order_sn'] = operation.order_sn
        _op['status'] = operation.status
        _op['execution_detail'] = operation.execution_detail
        _op['progress'] = operation.progress
        _op['time_consuming'] = operation.time_consuming
        _op['add_time'] = int(operation.add_time.timestamp())
        operation_record.append(_op)
    data['operation_record'] = operation_record
    response = APIResponse(success=True, data=data, msg='退货单详情')
    return response
Exemplo n.º 19
0
def returns_order(instance, status, guest_id, remarks):
    if not isinstance(instance, OrderDetail):
        response = APIResponse(success=False, data={}, msg='ID有误或参数错误')
        return response
    if instance.status != 6:
        response = APIResponse(success=False, data={}, msg='当前状态不允许退货')
        return response
    if status == 2:
        # 状态
        # 获取退货单号逻辑
        order_sn = instance.son_order_sn
        headers = {'content-type': 'application/json',
                   'user-agent': "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}
        parameters = json.dumps({'order_sn': order_sn})
        try:
            response = requests.post(ORDER_API_HOST + '/api/rejected', data=parameters, headers=headers)
            response_dict = json.loads(response.text)
        except Exception as e:
            logger.info('ID生成器连接失败!!!')
            response = APIResponse(success=False, data={}, msg='ID生成器连接失败!!!')
            return response
        logger.info(message='生成退货ID返回结果: %s' % response_dict)
        if response_dict['rescode'] != '10000':
            response = APIResponse(success=False, data={}, msg='ID生成器出错!!!')
            return response
        returns_sn = response_dict['data']['th_order_id']
        now = datetime.now()
        order_operation = OrderOperationRecord.objects.filter(order_sn=order_sn).order_by('-add_time')
        time_consuming = float(now.timestamp() - order_operation[0].add_time.timestamp())
        OrderOperationRecord.objects.create(order_sn=order_sn, status=12, operator=guest_id,
                                            execution_detail='用户[%s]对订单[%s]执行申请退货操作' % (
                                                guest_id, order_sn), progress='已支付',
                                            time_consuming=time_consuming)
        # 生成待审核退货单
        OrderReturns.objects.create(order_sn=order_sn, returns_sn=returns_sn, status=3)
        # 生成待审核后台数据
        ReturnsDeal.objects.create(order_sn=instance.son_order_sn, is_deal=1, remarks=remarks, return_type=1,
                                   return_sn=returns_sn)
        instance.status = 11
        instance.save()
        response = APIResponse(success=True, data={}, msg='退货申请提交成功等待审核')
        return response
    else:
        response = APIResponse(success=False, data={})
        return response
Exemplo n.º 20
0
 def post(self, request):
     if RUN_MODE == "PRODUCT":
         proc_post.delay(request.data)
     else:
         test_post.delay(request.data)
     return APIResponse(success=True)
Exemplo n.º 21
0
def online_generation_order(data, request):
    data = re.sub('\'', '\"', data)
    now = datetime.now()
    date = now.date()
    delta = timedelta(days=15)
    due_time = date + delta
    try:
        data = json.loads(data)
        # 商品信息
        goods_info = data['goods_info']
        goods_id_list = []
        number_list = []
        for info in goods_info:
            goods_id_list.append(int(info['goods_id']))
            number_list.append(int(info['number']))
        # 收货人
        receiver = data['receiver']
        # 电话
        mobile = data['mobile']
        # 省
        province = data['province']
        # 市
        city = data['city']
        # 区
        district = data['district']
        # 详细地址
        address = data['address']
        # 备注
        remarks = data['remarks']
        # 买家ID
        guest_id = request.user.id
        # guest_id = 2
        # 这里后续需要加上获取佣金比例的逻辑 暂时先用 0.0 替代
        ratio = 0.0
        order_status = 1
        headers = {'content-type': 'application/json',
                   'user-agent': "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}
        parameters = json.dumps({})
        try:
            response = requests.post(ORDER_API_HOST + '/api/order', data=parameters, headers=headers)
            response_dict = json.loads(response.text)
        except Exception as e:
            logger.info('ID生成器连接失败!!!')
            response = APIResponse(success=False, data={}, msg='ID生成器连接失败!!!')
            return response
        if response_dict['rescode'] != '10000':
            return response
        # 获取商品信息
        try:
            parameters = {'goods_ids': goods_id_list, 'quantities': number_list}
            goods_response = requests.get(GOODS_API_HOST + '/api/service/checkout/goods', parameters, headers=headers)
            goods_dict = json.loads(goods_response.text)
        except Exception as e:
            logger.info('ID生成器连接失败!!!')
            response = APIResponse(success=False, data={}, msg='ID生成器连接失败!!!')
            return response
        if goods_dict['rescode'] != '10000':
            return goods_response
        # 母订单号
        mother_order_sn = response_dict['data']['order_sn']
        goods_data = []
        for goods in goods_dict['data'].values():
            _ = {}
            try:
                parameters = json.dumps({'order_id': mother_order_sn})
                response = requests.post(ORDER_API_HOST + '/api/order', data=parameters, headers=headers)
            except Exception as e:
                logger.info('生成子订单出错')
                # response = APIResponse(success=False, data={}, msg='请求ID生成器出错')
                return response
            son_order_sn = json.loads(response.text)['data']['order_sn']
            supplier_id = goods['supplier_id']
            try:
                response = requests.get(SUPPLIER_API_HOST + '/api/service/suppliers/%s' % safe_int(supplier_id))
                supplier_info = json.loads(response.text)
            except Exception as e:
                logger.info('查询供应商信息出错')
                response = APIResponse(success=False, data={}, msg='查询供应商信息出错')
                return response
            if supplier_info['rescode'] != '10000':
                return supplier_info
            _['univalent'] = goods['price']
            _['supplier_name'] = supplier_info['data']['company']
            _['price_discount'] = 0.0
            _['goods_id'] = goods['goods_id']
            _['supplier_id'] = supplier_id
            _['goods_name'] = goods['goods_name']
            _['model'] = goods['partnumber']
            _['goods_unit'] = goods['sales_unit']
            res = re.match(r'\d+', goods['lead_time'])
            _['max_delivery_time'] = int(res.group()) if res else 7
            _['brand'] = goods['brand_name']
            _['goods_sn'] = goods['gno']
            _['number'] = goods['quantity']
            _['product_place'] = goods['prodution_place']
            _['son_order_sn'] = son_order_sn
            goods_data.append(_)
        # 发票信息
        if data['receipt_type'] == 3:
            receipt = Receipt.objects.create(receipt_type=data['receipt_type'])
        else:
            receipt = Receipt.objects.create(
                title=data['title'],
                account=data['account'],
                tax_number=data['tax_number'],
                telephone=data['telephone'],
                bank=data['bank'],
                company_address=data['company_address'],
                receipt_type=data['receipt_type'],
            )
        # 创建母订单信息, 母订单类型订单不存在母订单
        mother_order = Order.objects.create(receipt=receipt.id, remarks=remarks, receiver=receiver, mobile=mobile,
                                            guest_id=guest_id, order_sn=mother_order_sn, address=address,
                                            province=province, city=city, district=district)
        # 增加母订单状态信息
        OrderOperationRecord.objects.create(order_sn=mother_order.order_sn, status=1, operator=guest_id,
                                            execution_detail='提交订单', progress='未支付')
        # 增加初始订单支付信息
        OrderPayment.objects.create(order_sn=mother_order_sn, pay_status=1)
        total_money = 0.0
        for _data in goods_data:
            # parameters = json.dumps({'order_id': mother_order_sn})
            # response = requests.post(ORDER_API_HOST + '/api/order', data=parameters, headers=headers)
            # order_sn = json.loads(response.text)['data']['order_sn']
            price_discount = float(_data.get('price_discount', 0.0))
            subtotal_money = float(_data['univalent']) * float(_data['number']) * (1.0 - price_discount)
            total_money += subtotal_money
            _order = OrderDetail.objects.create(
                order=mother_order.id,
                son_order_sn=_data['son_order_sn'],
                supplier_id=_data['supplier_id'],
                goods_id=_data['goods_id'],
                goods_sn=_data['goods_sn'],
                goods_name=_data['goods_name'],
                goods_unit=_data['goods_unit'],
                product_place=_data['product_place'],
                model=_data['model'],
                brand=_data['brand'],
                number=int(_data['number']),
                univalent=float(_data['univalent']),
                subtotal_money=subtotal_money,
                commission=subtotal_money * ratio,
                price_discount=price_discount,
                status=order_status,
                max_delivery_time=_data['max_delivery_time'],
                due_time=due_time
            )
            # 增加子订单状态信息
            OrderOperationRecord.objects.create(order_sn=_order.son_order_sn, status=1, operator=guest_id,
                                                execution_detail='用户[%s]提交订单' % guest_id, progress='未支付')
            OrderPayment.objects.create(order_sn=_order.son_order_sn, pay_status=1)
        mother_order.total_money = total_money
        mother_order.save()
    except json.JSONDecodeError as e:
        logger.info("{msg: 请求参数异常}")
        response = APIResponse(success=False, data={}, msg='请求参数异常')
        return response
    result = {
        'id': mother_order.id,
        'mother_order_sn': mother_order_sn,
        'add_time': mother_order.add_time,
        'address': mother_order.address,
        'receipt_title': receipt.title,
        'receipt_type': RECEIPT_TYPE[receipt.receipt_type],
        'status': order_status
    }
    response = APIResponse(success=True, data=result, msg='创建订单信息成功')
    return response
Exemplo n.º 22
0
def generation_order(data):
    data = re.sub('\'', '\"', data)
    now = datetime.now()
    date = now.date()
    delta = timedelta(days=15)
    due_time = date + delta
    try:
        data = json.loads(data)
        # 发票信息
        if data[0]['receipt_type'] == 3:
            receipt = Receipt.objects.create(receipt_type=data[0]['receipt_type'])
        else:
            receipt = Receipt.objects.create(
                title=data[0]['title'],
                account=data[0]['account'],
                tax_number=data[0]['tax_number'],
                telephone=data[0]['telephone'],
                bank=data[0]['bank'],
                company_address=data[0]['company_address'],
                receipt_type=data[0]['receipt_type'],
            )
        # 收货人
        receiver = data[0]['receiver']
        # 电话
        mobile = data[0]['mobile']
        # 收货地址
        address = data[0]['address']
        # 备注
        remarks = data[0]['remarks']
        # 买家ID
        guest_id = data[0]['guest_id']
        # 这里后续需要加上获取佣金比例的逻辑 暂时先用 0.0 替代
        ratio = 0.0
        order_status = 1
        headers = {'content-type': 'application/json',
                   'user-agent': "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}
        parameters = json.dumps({})
        try:
            response = requests.post(ORDER_API_HOST + '/api/order', data=parameters, headers=headers)
            response_dict = json.loads(response.text)
        except Exception as e:
            logger.info('ID生成器连接失败!!!')
            response = APIResponse(success=False, data={}, msg='ID生成器连接失败!!!')
            return response
        # 母订单号
        mother_order_sn = response_dict['data']['order_sn']
        # 创建母订单信息, 母订单类型订单不存在母订单
        mother_order = Order.objects.create(receipt=receipt.id, remarks=remarks, receiver=receiver, mobile=mobile,
                                            guest_id=guest_id, order_sn=mother_order_sn, address=address)
        # 增加母订单状态信息
        OrderOperationRecord.objects.create(order_sn=mother_order.order_sn, status=1, operator=guest_id,
                                            execution_detail='提交订单', progress='未支付')
        # 增加初始订单支付信息
        OrderPayment.objects.create(order_sn=mother_order_sn, pay_status=1)
        total_money = 0.0
        for _data in data:
            parameters = json.dumps({'order_id': mother_order_sn})
            response = requests.post(ORDER_API_HOST + '/api/order', data=parameters, headers=headers)
            order_sn = json.loads(response.text)['data']['order_sn']
            price_discount = float(_data.get('price_discount', 0.0))
            subtotal_money = float(_data['univalent']) * float(_data['number']) * (1.0 - price_discount)
            total_money += subtotal_money
            _order = OrderDetail.objects.create(
                order=mother_order.id,
                son_order_sn=order_sn,
                supplier_id=_data['supplier_id'],
                goods_id=_data['goods_id'],
                model=_data['model'],
                brand=_data['brand'],
                number=int(_data['number']),
                univalent=float(_data['univalent']),
                subtotal_money=subtotal_money,
                commission=subtotal_money * ratio,
                price_discount=price_discount,
                status=order_status,
                max_delivery_time=_data['max_delivery_time'],
                due_time=due_time
            )
            # 增加子订单状态信息
            OrderOperationRecord.objects.create(order_sn=_order.son_order_sn, status=1, operator=guest_id,
                                                execution_detail='用户[%s]提交订单' % guest_id, progress='未支付')
            OrderPayment.objects.create(order_sn=_order.son_order_sn, pay_status=1)
        mother_order.total_money = total_money
        mother_order.save()
    except json.JSONDecodeError as e:
        logger.info("{msg: 请求参数异常}")
        response = APIResponse(success=False, data={}, msg='请求参数异常')
        return response
    result = {
        'id': mother_order.id,
        'mother_order_sn': mother_order_sn,
        'add_time': mother_order.add_time,
        'address': mother_order.address,
        'receipt_title': data[0]['title'],
        'receipt_type': RECEIPT_TYPE[receipt.receipt_type],
        'status': ORDER_STATUS[order_status]
    }
    response = APIResponse(success=True, data=result, msg='创建订单信息成功')
    return response
Exemplo n.º 23
0
def deal_returns_order(order_details, returns_status, returns_sn, start_time='', end_time='', is_type=1):
    data = []
    order_returns = OrderReturns.objects.filter(order_sn__in=[obj.son_order_sn for obj in order_details])
    # returns_deal = ReturnsDeal.objects.filter(order_sn__in=[obj.son_order_sn for obj in order_details],
    #                                           return_type=is_type).exclude(
    #     order_sn__in=[obj.order_sn for obj in order_returns]
    # )
    if is_type == 2:
        order_refund = OrderRefund.objects.filter(order_sn__in=[obj.son_order_sn for obj in order_details])
    if returns_sn:
        order_returns = order_returns.filter(returns_sn=returns_sn)
    if returns_status:
        order_returns = order_returns.filter(status=returns_status)
    if start_time:
        start_time += ' 23:59:59'
        order_returns = order_returns.filter(add_time__gte=start_time)
    if end_time:
        end_time += ' 23:59:59'
        order_returns = order_returns.filter(add_time__lte=end_time)
    for order_return in order_returns:
        result = {}
        order_detail = order_details.filter(son_order_sn=order_return.order_sn)
        returns_deal = ReturnsDeal.objects.filter(return_sn=order_return.returns_sn)
        if not order_detail:
            response = APIResponse(success=False, data={}, msg='退货信息异常')
            return response
        # if not order_return:
        #     response = APIResponse(success=False, data={}, msg='没有退货申请记录,请联系管理员')
        #     return response
        order_detail = order_detail[0]
        result['id'] = order_detail.id
        result['goods_name'] = order_detail.goods_name
        result['goods_unit'] = order_detail.goods_unit
        result['order_sn'] = order_detail.son_order_sn
        result['subtotal_money'] = order_detail.subtotal_money
        result['model'] = order_detail.model
        result['brand'] = order_detail.brand
        result['number'] = order_detail.number
        result['univalent'] = order_detail.univalent
        result['returns_sn'] = order_return.returns_sn
        result['is_deal'] = True if returns_deal and returns_deal[0].is_deal == 2 else False
        result['status'] = order_return.status if is_type !=2 else order_refund[0].status
        result['returns_time'] = int(order_return.add_time.timestamp())
        if is_type == 2:
            result['refund_time'] = int(order_refund[0].add_time.timestamp()) if order_refund else ''
            result['refund_sn'] = order_refund[0].refund_sn if order_refund else ''
        data.append(result)
    # if returns_deal:
    #     for _deal in returns_deal:
    #         result = {}
    #         order_detail = order_details.filter(son_order_sn=_deal.order_sn)
    #         if not order_detail:
    #             response = APIResponse(success=False, data={})
    #             return response
    #         order_detail = order_detail[0]
    #         result['id'] = order_detail.id
    #         result['goods_name'] = order_detail.goods_name
    #         result['goods_unit'] = order_detail.goods_unit
    #         result['order_sn'] = order_detail.son_order_sn
    #         result['subtotal_money'] = order_detail.subtotal_money
    #         result['model'] = order_detail.model
    #         result['brand'] = order_detail.brand
    #         result['number'] = order_detail.number
    #         result['univalent'] = order_detail.univalent
    #         result['returns_sn'] = ''
    #         result['status'] = ''
    #         result['returns_time'] = ''
    #         if is_type == 2:
    #             result['refund_time'] = ''
    #             result['refund_sn'] = ''
    #         data.append(result)
    msg = '全部退货单' if is_type == 1 else '全部退款单'
    response = APIResponse(success=True, data=data, msg=msg)
    return response