Exemplo n.º 1
0
def create_order_delivery(delivery_info: dict):
    """
    创建一个订单配送记录
    :param delivery_info:
    :return:
    """
    delivery = Delivery(**delivery_info)
    delivery.save()
    return delivery
Exemplo n.º 2
0
def cart_order_complete(request, total_price, username, phonenumber, address,
                        uid, delivery_message):
    delivery_lis = []
    cart_ref = db.collection("users").document(uid).collection('cart')
    cart_alldoc = cart_ref.stream()

    for doc in cart_alldoc:
        cart = Cart.from_dict(doc.to_dict())
        doc_ref = db.collection("delivery")
        doc_ref_random = db.collection("delivery").document()
        doc_ref_random.set(
            Delivery(cart.brand, cart.name, cart.sizedic, total_price,
                     username, phonenumber, address,
                     firestore.SERVER_TIMESTAMP, "배송전", "", "", uid,
                     delivery_message, cart.downloadurl,
                     cart.documentId).to_dict())

        user_doc = db.collection("users").document(uid).collection(
            "delivery").document(doc_ref_random.id)
        user_doc.set(
            Delivery(cart.brand, cart.name, cart.sizedic, total_price,
                     username, phonenumber, address,
                     firestore.SERVER_TIMESTAMP, "배송전", "", "", uid,
                     delivery_message, cart.downloadurl,
                     cart.documentId).to_dict())
        delievery_par = Delivery.from_dict(
            Delivery(cart.brand, cart.name, cart.sizedic, cart.price, username,
                     phonenumber, address, firestore.SERVER_TIMESTAMP, "배송전",
                     "", "", uid, delivery_message, cart.downloadurl,
                     cart.documentId).to_dict())
        # delivery=Delivery.from_dict(delivery_docs.to_dict())
        delivery_lis.append(delievery_par)
        #print(delivery_lis)
    #for문끝

    def delete_collection(coll_ref, batch_size):
        deldocs = coll_ref.limit(batch_size).stream()
        deleted = 0

        for doc in deldocs:
            print(f'Deleting doc {doc.id} => {doc.to_dict()}')
            doc.reference.delete()
            deleted = deleted + 1

        if deleted >= batch_size:
            return delete_collection(coll_ref, batch_size)

    delete_collection(cart_ref, 3)

    return render(request, 'getdata.html', {'delivery_lis': delivery_lis})
Exemplo n.º 3
0
def modify(request):
    documentId=request.POST.get('documentId')
    deliverystate=request.POST.get('deliveryState')
    deliverycode=request.POST.get('deliverycode')
    deliverynum=request.POST.get('deliverynum')
 
    doc_ref=db.collection("delivery").document(documentId)
    doc=doc_ref.get()
    if doc.exists:
        delivery=Delivery.from_dict(doc.to_dict())
  
        option="s:"+str(delivery.option['s'])+"m:"+str(delivery.option['m'])+"l:"+str(delivery.option['l'])+"xl:"+str(delivery.option['xl'])
        # doc_ref.set(
        # Delivery(delivery.brandname,delivery.product_name,checkbox,name,sex,zipcode,adress,adressdetail).to_dict()
        # )
        doc_ref.update({u'deliverystate': deliverystate})
        doc_ref.update({u'deliverycode': deliverycode})
        doc_ref.update({u'deliverynum': deliverynum})
        user_uid=delivery.uid
        user_ref=db.collection("users").document(user_uid).collection("delivery").document(documentId)
        user_ref.update({u'deliverystate': deliverystate})
        user_ref.update({u'deliverycode': deliverycode})
        user_ref.update({u'deliverynum': deliverynum})
        

    else:
        print(u'No such document!')

    doc2=doc_ref.get()
    if doc2.exists:
        delivery2=Delivery.from_dict(doc2.to_dict())
        print(type(delivery2.option))
        print(delivery2.option['s'])
        option2="s:"+str(delivery2.option['s'])+"m:"+str(delivery2.option['m'])+"l:"+str(delivery2.option['l'])+"xl:"+str(delivery2.option['xl'])
        # doc_ref.set(
        # Delivery(delivery.brandname,delivery.product_name,checkbox,name,sex,zipcode,adress,adressdetail).to_dict()
        # )
        
    else:
        print(u'No such document!')


    
    #url="admin/delivery/home/detail/"+documentId+"/"
    return render(request,"admin_delivery_modify.html",{'delivery':delivery2,'option':option2,'id':documentId})
Exemplo n.º 4
0
def getdata(request, option, price, username, phonenum, address, uid,
            delivery_message, product_id):

    delivery_lis = []

    prd_ref = db.collection(u'product').document(product_id)

    prd_docs = prd_ref.get()

    dictionary = literal_eval(option)

    if prd_docs.exists:
        products = Product.from_dict(prd_docs.to_dict())
        img = products.downloadurl
        brandname = products.brand
        product_name = products.name

        doc_ref = db.collection("delivery")
        doc_ref_random = db.collection("delivery").document()
        doc_ref_random.set(
            Delivery(brandname, product_name, dictionary, price, username,
                     phonenum, address, firestore.SERVER_TIMESTAMP, "배송전", "",
                     "", uid, delivery_message, img, product_id).to_dict())
        user_doc = db.collection("users").document(uid).collection(
            "delivery").document(doc_ref_random.id)
        user_doc.set(
            Delivery(brandname, product_name, dictionary, price, username,
                     phonenum, address, firestore.SERVER_TIMESTAMP, "배송전", "",
                     "", uid, delivery_message, img, product_id).to_dict())

        delievery_par = Delivery.from_dict(
            Delivery(brandname, product_name, dictionary, price, username,
                     phonenum, address, firestore.SERVER_TIMESTAMP, "배송전", "",
                     "", uid, delivery_message, img, product_id).to_dict())
        # delivery=Delivery.from_dict(delivery_docs.to_dict())
        delivery_lis.append(delievery_par)
        #print(delivery_lis)

        #유저에서 딜리버리 가져오기

    else:
        print(u'No such document!')

    return render(request, 'getdata.html', {'delivery_lis': delivery_lis})
Exemplo n.º 5
0
def createBill(request):
    data = json.loads(request.body)
    cartID = data['cartID']
    action = data['action']
    cart = Shopping_cart.objects.get(cart_id=cartID)
    customer = Customer.objects.get(customer_id=cart.customer_id_id)
    tradesman = Tradesman.objects.get(employer_id= randrange(6))
    cart_pro = Cart_product.objects.all()
    total = cart.total
    bill = Bill.objects.all()
    day = date.today()
    dt = day.strftime("%Y-%m-%d")
    m=0
    if len(bill) != 0:
        for q in bill:
            if m < q.bill_number:
                m = q.bill_number
        m=m+1
        print('Bill_number',m)
        print('Date',dt)
        print('Customer',customer)
        print('Cart',cart)
        print('Total',total)
        if action == 'create':
            bill1 = Bill(bill_number = m, bill_date = dt, customer_id = customer, cart_id = cart, total = total)
            delivery1 = Delivery(delivery_id = m,bill_number = bill1,customer_id = customer,employer_id = tradesman,delivery_date = dt)
            for cp in cart_pro:
                if cp.cart_id_id == cart.cart_id:
                    bk = Backup(cart_product_id = cp.cart_product_id ,amount = cp.amount , price_total = cp.price_total,cart= cp.cart_id, product=cp.product_id, total = total)
                    bk.save()
                    cp.delete()
            cart.total=0
            cart.save()

        bill1.save()
        delivery1.save()
    else:
        m=1
        if action == 'create':
            bill1 = Bill(bill_number = m, bill_date = dt, customer_id = customer, cart_id = cart, total = total)
            delivery1 = Delivery(delivery_id = m,bill_number = bill1,customer_id = customer,employer_id = tradesman,delivery_date = dt)
            for cp in cart_pro:
                if cp.cart_id_id == cart.cart_id:
                    bk = Backup(cart_product_id = cp.cart_product_id ,amount = cp.amount , price_total = cp.price_total,cart= cp.cart_id, product=cp.product_id, total = total)
                    bk.save()
                    cp.delete()
            cart.total=0
            cart.save()

        bill1.save()
        delivery1.save()

    return JsonResponse('The bill was added', safe= False)
Exemplo n.º 6
0
    def request_submit(cls, delivery: Delivery, config):

        if config['City'] not in delivery.to.settlement and config['City'] not in delivery.to.region:
            return False

        data = {
            'matter': config['Matter'],
            'total_weight_kg': 1,
            'insurance_amount': str(delivery.order.items_cost),
            'payment_method': 'non_cash',
            'points': [
                {
                    'address': config['WarehouseAddress'],
                    'contact_person': {
                        'phone': config['WarehousePhone']
                    }
                },
                {
                    'address': delivery.to.value,
                    'contact_person': {
                        'phone': filter_phone(delivery.recipient.phone)
                    }
                }
            ]
        }

        response = requests.post(
            cls.endpoint + '/create-order',
            headers={
                'Content-Type': 'application/json',
                'X-DV-Auth-Token': config['AuthToken']
            },
            data=json.dumps(data).encode('utf-8')
        )
        result = response.json()

        if response.status_code == 200:
            delivery.external_id = result['order']['order_id']
            delivery.status = Delivery.SUBMITTED
            delivery.save(update_fields=['external_id', 'status'])
        else:
            return None
Exemplo n.º 7
0
def detail(request,id):
    doc_ref=db.collection("delivery").document(id)
    doc=doc_ref.get()
    if doc.exists:
        delivery=Delivery.from_dict(doc.to_dict())
        print(type(delivery.option))
        print(delivery.option['s'])
        option="s:"+str(delivery.option['s'])+"m:"+str(delivery.option['m'])+"l:"+str(delivery.option['l'])+"xl:"+str(delivery.option['xl'])
    else:
        print(u'No such document!')
    return render(request,"admin_delivery_modify.html",{'delivery':delivery,'option':option,'id':id})
Exemplo n.º 8
0
def review_write(request,delivery_uid):
    delivery_ref=db.collection("delivery").document(delivery_uid)
    delivery_doc=delivery_ref.get()
    if delivery_doc.exists:
        delivery=Delivery.from_dict(delivery_doc.to_dict())
        return render(request, 'reviewIndex.html',{"delivery_uid":delivery_uid,"delivery":delivery})
        

    else:
        print(u'No such document!')
    return render(request, 'reviewIndex.html',{"delivery_uid":delivery_uid})
Exemplo n.º 9
0
 def post(self, request, format=None):
     agents = Delivery_Agent.objects.all().filter(on_delivery=False)
     node = Point(float(request.POST['x']),
                  float(request.POST['y']),
                  srid=4326)
     location_list = list()
     agent_list = list()
     selected_agent = Delivery_Agent.objects.annotate(
         distance=Distance('location', node)).order_by('distance').first()
     selected_agent.on_delivery = True
     selected_agent.save()
     delivery = Delivery()
     delivery.customer = Customer.objects.get(user=request.user)
     delivery.delivery_agent = selected_agent
     delivery.pickup_location = node
     delivery.location = selected_agent.location
     delivery.start_time = datetime.datetime.now()
     delivery.total_distance = selected_agent.location.distance(node) * 100
     delivery.save()
     content = {'agent': selected_agent.user.username}
     return Response(content)
Exemplo n.º 10
0
    def refresh_delivery(cls, delivery: Delivery):
        config = cls.get_config(delivery.type.shop_id)

        response = requests.get(
            cls.endpoint + '/orders',
            headers={
                'X-DV-Auth-Token': config['AuthToken']
            },
            params={
                'order_id': delivery.external_id
            }
        )
        result = response.json()

        if response.status_code == 200:
            status = result['orders'][0]['status']
            print(f'Доставка по заказу {delivery.order_id}, статус {status}')
            if status == 'available' and delivery.status == Delivery.SUBMITTED:
                delivery.status = Delivery.APPROVED
            elif status == 'active' and delivery.status == Delivery.APPROVED:
                delivery.status = Delivery.IN_DELIVERY
            elif status == 'completed':
                delivery.status = Delivery.COMPLETED
            elif status == 'canceled':
                delivery.status = Delivery.CANCELED
            delivery.save(update_fields=['status'])
Exemplo n.º 11
0
def home(request):
    adminemail="Dumstruck"
    adminpass="******"
    email=request.POST.get('email')
    passw=request.POST.get('pass')
    if adminemail != email or passw != adminpass  :
        try :
            request.session['admin_delivey_uid']
            delivery_lis=[]
            delivery_id=[]
            delivery_ref=db.collection("delivery")
            delivery_docs=delivery_ref.stream()
            for doc in delivery_docs:
                #print(f'{doc.id} => {doc.to_dict()}')
                delivery=Delivery.from_dict(doc.to_dict())
                delivery_lis.append(delivery)
                delivery_id.append(doc.id)
            comb_lis=zip(delivery_lis,delivery_id)
            return render(request,"admin_delivery_home.html",{"e":email,'comb_lis':comb_lis})

        except:
            message="Invalid credentials"
            return render(request,"admin_delivery_login.html",{"messg":message})
    else :
        request.session['admin_delivey_uid']=adminemail
        delivery_lis=[]
        delivery_id=[]
        delivery_ref=db.collection("delivery")
        delivery_docs=delivery_ref.stream()
        for doc in delivery_docs:
            #print(f'{doc.id} => {doc.to_dict()}')
            delivery=Delivery.from_dict(doc.to_dict())
            delivery_lis.append(delivery)
            delivery_id.append(doc.id)

        comb_lis=zip(delivery_lis,delivery_id)
        return render(request,"admin_delivery_home.html",{"e":email,'comb_lis':comb_lis})
Exemplo n.º 12
0
def orderinfo(request):

    uid=None
    try:
        print("카트"+request.session['uid'])
        uid=request.session['uid']
        user_doc=db.collection("users").document(uid).collection("delivery")
        user_alldocs=user_doc.stream()
        print("??")
        deliverylist=[]
        doc_id_lis=[]
        krtime_lis=[]
        option_lis=[]
        
        for doc in user_alldocs:

            option=""
            delivery=Delivery.from_dict(doc.to_dict())
            
           
            ustime=str(delivery.timestamp)[0:10]

            print("도큐아이디"+str(doc.id))


            ##옵션 만들기
            
            if delivery.option['s'] !=0:
                option+="S:"+str(delivery.option['s'])+"  "
            if delivery.option['m'] !=0:
                option+="M:"+str(delivery.option['m'])+"  "
            if delivery.option['l'] !=0:
                option+="L:"+str(delivery.option['l'])+"  "
            if delivery.option['xl'] !=0:
                option+="XL:"+str(delivery.option['xl'])+"  "

            print(option)
           

            krtime_lis.append(ustime)
            deliverylist.append(delivery)
            doc_id_lis.append(doc.id)
            option_lis.append(option)
        
        comb_lis=zip(deliverylist,doc_id_lis,krtime_lis,option_lis)
        
        return render(request, 'orderinfo.html',{'uid':uid,'comb_lis':comb_lis})
    except:
        return render(request, 'signin.html',{'uid':uid})
Exemplo n.º 13
0
    def request_delivery_submit(cls, delivery: Delivery, config):
        response = requests.post(cls.endpoint + '/orders/submit',
                                 headers={
                                     'Content-Type': 'application/json',
                                     'Authorization': config['OAuth']
                                 },
                                 data=json.dumps({
                                     'orderIds': [delivery.external_id]
                                 }).encode('utf-8'))

        success = False
        if response.status_code == 200:
            result = response.json()[0]
            if result['status'] == 'SUCCESS':
                delivery.status = Delivery.SUBMITTED
                success = True
            else:
                delivery.status = Delivery.ERROR
                log.error(result)
            delivery.save(update_fields=['status'])
        else:
            log.error(response.json())

        return success
Exemplo n.º 14
0
def nonmember_lookup_action(request) :
    uid=None
    
    tel=request.POST.get('tel')
    uid=tel
    user_doc=db.collection("users").document(uid).collection("delivery")
    user_alldocs=user_doc.stream()
    print("??")
    deliverylist=[]
    for doc in user_alldocs:
        delivery=Delivery.from_dict(doc.to_dict())
        #print(delivery)
        deliverylist.append(delivery)
        
    return render(request, 'orderinfo.html',{'deliverylist':deliverylist})
Exemplo n.º 15
0
def cartfinishedpay(request, total_price, username, phonenumber, address, uid,
                    delivery_message):
    uid = None
    try:
        print("카트" + request.session['uid'])
        uid = request.session['uid']
        user_doc = db.collection("users").document(uid).collection("delivery")
        user_alldocs = user_doc.stream()
        print("??")
        deliverylist = []
        for doc in user_alldocs:
            delivery = Delivery.from_dict(doc.to_dict())
            #print(delivery)
            deliverylist.append(delivery)

        return render(request, 'orderinfo.html', {
            'uid': uid,
            'deliverylist': deliverylist
        })
    except:
        return render(request, 'signin.html', {'uid': uid})
Exemplo n.º 16
0
    def request_delivery_draft(cls, delivery: Delivery, config):
        optimal_option = cls.request_optimal(delivery.type, delivery.to,
                                             delivery.order.items_cost, config)
        assert optimal_option is not None

        complete_address = cls.get_complete_address(delivery.to, config)
        if not complete_address:
            log.error('Unknown address for delivery')
            delivery.status = Delivery.ERROR
            delivery.save(update_fields=['status'])
            return False

        pickup_point_id = None
        if delivery.type.type in ['POST', 'COURIER']:
            if delivery.type.extra['useClosestPickup']:
                pickup_point_id = cls.get_closest_pickup(
                    delivery, optimal_option['pickupPointIds'],
                    delivery.to.latitude, delivery.to.longitude, config)
            else:
                pickup_point_id = delivery.extra['pickupPointId']

        package = Package.objects.for_delivery(delivery)
        if not package:
            log.error("No matching package")
            delivery.status = Delivery.ERROR
            delivery.save(update_fields=['status'])
            return False

        shipment_date = cls.get_shipment_date().isoformat()

        data = {
            'senderId':
            config['ShopId'],
            'externalId':
            delivery.order.id
            if not settings.DEBUG else f'DEBUG_{delivery.order.id}',
            'comment':
            f'Доставка по заказу {delivery.order.id}',
            'deliveryType':
            delivery.type.type,
            'recipient':
            convert_recipient(delivery.recipient, delivery.to,
                              complete_address['geoId'], pickup_point_id),
            'cost': {
                'manualDeliveryForCustomer': 0,
                'paymentMethod': 'PREPAID',
                'assessedValue': delivery.order.items_cost,
                'fullyPrepaid': True
            },
            'contacts': [{
                'type': 'RECIPIENT',
                'phone': delivery.recipient.phone,
                'firstName': delivery.recipient.first_name,
                'lastName': delivery.recipient.last_name,
            }],
            'deliveryOption':
            convert_option(optimal_option),
            'shipment': {
                'type': 'WITHDRAW',
                'date': shipment_date,
                'warehouseFrom': config['WarehouseId'],
                'partnerTo': optimal_option['shipments'][0]['partner']['id'],
            },
            'places': [{
                'externalId':
                delivery.order.id,
                'dimensions':
                convert_package(package),
                'items': [
                    convert_order_item(order_item) for order_item in
                    delivery.order.items.prefetch_related('item').all()
                ]
            }]
        }

        response = requests.post(cls.endpoint + '/orders',
                                 headers={
                                     'Content-Type': 'application/json',
                                     'Authorization': config['OAuth']
                                 },
                                 data=json.dumps(data).encode('utf-8'))

        if response.status_code == 200:
            delivery.external_id = response.json()
            delivery.extra['shipment_id'] = int(
                optimal_option['shipments'][0]['partner']['id'])
            delivery.extra['shipment_date'] = shipment_date
            delivery.save(update_fields=['status', 'external_id', 'extra'])
            return True
        else:
            log.error(
                f'Ошибка интеграции Яндекс.Доставки по заказу {delivery.order.id}: {response.json()}'
            )
            delivery.status = Delivery.ERROR
            delivery.save(update_fields=['status'])
            return False
Exemplo n.º 17
0
def detail(request,documentId):
    #테스트
    uid=None
    com_lis=[]
    recentview_lis=[]
    print("홈시작")
    try:
        recentview_lis=request.session['RecentView']
    except:
        print("recentview 없음")
    if len(recentview_lis)<6 :
        recentview_lis.append(documentId)
        my_set = set(recentview_lis)
        my_list = list(my_set)
        request.session['RecentView']=my_list
    else :
        recentview_lis.pop(0)
        recentview_lis.append(documentId)
        my_set = set(recentview_lis)
        my_list = list(my_set)
        request.session['RecentView']=my_list
    try:
        print("홈에서"+request.session['uid'])
        uid=request.session['uid']
    except:
        print("로그인안댐")
    doc_ref=db.collection(u'product').document(documentId)
    doc = doc_ref.get()
    products=None
    review_lis=[]
    user_lis=[]
    delivery_lis=[]
    if doc.exists:
        print(u'Document data: {}'.format(doc.to_dict()))
        products=Product.from_dict(doc.to_dict())
        review_ref=db.collection(u'product').document(documentId).collection('review')
        review_alldocs=review_ref.stream()
       

        for doc in review_alldocs:
            review=Review.from_dict(doc.to_dict())
            print(review.text)
            review_lis.append(review)
            #review user
            review_user_ref=db.collection(u'users').document(review.user_uid)
            review_user_doc=review_user_ref.get()
            if review_user_doc.exists:
                user=UserModel.from_dict(review_user_doc.to_dict())
                user_lis.append(user)
            #review delivery
            review_delivery_ref=db.collection(u'delivery').document(review.delivery_uid)
            review_delivery_doc=review_delivery_ref.get()
            if review_delivery_doc.exists:
                delivery=Delivery.from_dict(review_delivery_doc.to_dict())
                delivery_lis.append(delivery)
            com_lis=zip(review_lis,user_lis,delivery_lis)





    else:
        print(u'No such document!')

    
   

    return render(request,"detail.html",{'products':products,'documentId':documentId,'uid':uid,'com_lis':com_lis })