def add(data, db_session, username): logger.info(LogMsg.START, username) schema_validate(data,ITEM_ADD_SCHEMA_PATH) logger.debug(LogMsg.SCHEMA_CHECKED) book_id = data.get('book_id') person_id = data.get('person_id') if person_id is None: logger.error(LogMsg.DATA_MISSING, 'person_id') if is_book_in_library(person_id, book_id, db_session): logger.error(LogMsg.ALREADY_IS_IN_LIBRARY, {'book_id': book_id}) raise Http_error(409, Message.ALREADY_EXISTS) book = get_book(book_id, db_session) if book is None: logger.error(LogMsg.NOT_FOUND, {'book_id': book_id}) raise Http_error(404, Message.NOT_FOUND) if book.type.name in ONLINE_BOOK_TYPES : if data.get('count') > 1: logger.error(LogMsg.BOOK_ONLINE_TYPE_COUNT_LIMITATION) raise Http_error(400, Message.ONLINE_BOOK_COUNT_LIMITATION) content_id = book_has_content(book_id,'Original',db_session) if not content_id: logger.error(LogMsg.CONTENT_NOT_FOUND,{'book_id':book_id}) raise Http_error(404,Message.BOOK_HAS_NO_CONTENT) if not is_generated(content_id): logger.error(LogMsg.CONTENT_NOT_GENERATED, {'content_id': content_id}) raise Http_error(404, Message.BOOK_NOT_GENERATED) model_instance = OrderItem() populate_basic_data(model_instance, username) logger.debug(LogMsg.POPULATING_BASIC_DATA) model_instance.order_id = data.get('order_id') model_instance.book_id = book_id model_instance.count = data.get('count') # TODO discount not imposed yet model_instance.discount = data.get('discount', 0.0) model_instance.description = data.get('description') model_instance.price_detail = data.get('price_detail') model_instance.unit_price = get_book_price_internal(model_instance.book_id, db_session) logger.debug(LogMsg.ORDER_ITEM_UNIT_PRICE, model_instance.unit_price) model_instance.net_price = calc_net_price(model_instance.unit_price, model_instance.count, model_instance.discount) logger.debug(LogMsg.ORDER_ITEM_NET_PRICE, model_instance.net_price) db_session.add(model_instance) logger.info(LogMsg.END) return model_instance
def create_order_items(self, order, cart_items, user): for cart_item in cart_items: order_item = OrderItem(order=order, product=cart_item.product, quantity=cart_item.quantity) order_item.save() assign_perm('orderitem.change_orderitem', user, order_item) assign_perm('orderitem.view_orderitem', user, order_item)
def orderitem(request): current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) schopcart = ShopCart.objects.filter(user_id=current_user.id) form = OrderForm(request.POST or None) form2 = OrderForm2(request.POST or None) total = 0 for rs in shopcart: total += rs.item.fiyat * rs.quantity if request.method == 'POST': if form.is_valid() and form2.is_valid(): # Send Credit card to bank, If the bank responds ok, continue, if not, show the error # .............. data = Order() data.first_name = form.cleaned_data[ 'first_name'] # get product quantity from form data.last_name = form.cleaned_data['last_name'] data.email = form.cleaned_data['email'] data.address = form2.cleaned_data['address'] data.city = form2.cleaned_data['city'] data.phone = form2.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = random.randint(100000000, 999999999) # ordercode= get_random_string(9).upper() # random cod data.code = ordercode data.save() for rs in shopcart: detail = OrderItem() detail.order_id = data.id # Order Id detail.item_id = rs.item_id detail.user_id = current_user.id detail.quantity = rs.quantity detail.beden = rs.beden detail.fiyat = rs.item.fiyat detail.save() return redirect(reverse('payment')) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() context = { 'shopcart': shopcart, 'total': total, 'form': form, 'form2': form2, 'schopcart': schopcart, } return render(request, 'order/order_form.html', context)
def test_order_exists(self): order_id = Order(id=1, total=20.00) order_id.save() order_item = OrderItem(book="Test book title", quantity=2, price=9.99, order=order_id) order_item.save() self.assertEqual(order_item.book, "Test book title") self.assertEqual(order_item.quantity, 2) self.assertEqual(order_item.price, 9.99)
def test_sub_total(self): ''' Tests that the sub total matches the book quantity multiplied by price ''' order_id = Order(id=1, total=10.00) order_id.save() sub_total = OrderItem(quantity=2, price=10.00, order=order_id) sub_total.save() self.assertEqual(sub_total.quantity * sub_total.price, 20.00)
def place_order(self, address_id): """ 1. check if all items is available 2. check if address is right 3. delete previous pending orders 4. then => create order and order_items 5. delete cart items """ items = self.items.all() for item in items: if item.product.is_active: pass else: return False try: address = self.user.addresses.get(id=address_id) except Address.DoesNotExist: print('not an address!') return False # DELETING ANY PENDING ORDERS print('dd') orders = Order.objects.filter(user=self.user, status="PENDING").delete() print(items) # PLACING ORDER and GROUPING for item in items: store = item.product.store amount = item.product.price * item.quantity try: order = Order.objects.get(store=store, user=self.user, status="PENDING") except Order.DoesNotExist: order = Order(store=store, user=self.user, status="PENDING", amount=0, address=address) order.save() order_item = OrderItem(order=order, product=item.product, quantity=item.quantity, amount=amount) order_item.save() # here is important to save order [to make sure amount will be added correctly to order object!] order.save() orders = Order.objects.filter(user=self.user, status="PENDING") items.delete() return orders.update(status="SUCCESS")
def add(data, db_session, username): logger.info(LogMsg.START, username) check_schema(['book_id', 'count', 'order_id', 'person_id'], data.keys()) logger.debug(LogMsg.SCHEMA_CHECKED) book_id = data.get('book_id') person_id = data.get('person_id') if person_id is None: logger.error(LogMsg.DATA_MISSING, 'person_id') if is_book_in_library(person_id, book_id, db_session): logger.error(LogMsg.ALREADY_IS_IN_LIBRARY, {'book_id': book_id}) raise Http_error(409, Message.ALREADY_EXISTS) book = get_book(book_id, db_session) if book is None: logger.error(LogMsg.NOT_FOUND, {'book_id': book_id}) raise Http_error(404, Message.NOT_FOUND) if book.type.name in ONLINE_BOOK_TYPES and data.get('count') > 1: logger.error(LogMsg.BOOK_ONLINE_TYPE_COUNT_LIMITATION) raise Http_error(400, Message.ONLINE_BOOK_COUNT_LIMITATION) model_instance = OrderItem() populate_basic_data(model_instance, username) logger.debug(LogMsg.POPULATING_BASIC_DATA) model_instance.order_id = data.get('order_id') model_instance.book_id = book_id model_instance.count = data.get('count') # TODO discount not imposed yet model_instance.discount = data.get('discount', 0.0) model_instance.description = data.get('description') model_instance.price_detail = data.get('price_detail') model_instance.unit_price = get_book_price_internal( model_instance.book_id, db_session) logger.debug(LogMsg.ORDER_ITEM_UNIT_PRICE, model_instance.unit_price) model_instance.net_price = calc_net_price(model_instance.unit_price, model_instance.count, model_instance.discount) logger.debug(LogMsg.ORDER_ITEM_NET_PRICE, model_instance.net_price) db_session.add(model_instance) logger.info(LogMsg.END) return model_instance
def test_order_exists(self): ''' Tests that an order can be crated an exists ''' order_id = Order(id=1, total=20.00) order_id.save() order_item = OrderItem(book="Test book title", quantity=2, price=10.00, order=order_id) order_item.save() self.assertEqual(order_item.book, "Test book title") self.assertEqual(order_item.quantity, 2) self.assertEqual(order_item.price, 10.00)
def create(self, validated_data): order_items = validated_data.pop("order_item") with transaction.atomic(): order = Order.objects.create(**validated_data) order_item = [] for item in order_items: varian_product = item.get("product") product = varian_product.product if varian_product.stock < item.get("quantity"): raise serializers.ValidationError( {"message": "you quantity beyond stock product "}) # update stock and sold product varian_product.stock = varian_product.stock - item.get( "quantity") varian_product.save() product.sold = product.sold + item.get("quantity") product.save() order_item.append(OrderItem(order=order, **item)) OrderItem.objects.bulk_create(order_item) return order
def post(self, request): u_redirect = email_and_search(request, 'cart') if u_redirect is not None: return u_redirect request.session['_coupon'] = request.POST.get('coupon') post = request.POST user = request.user items = models.CartItem.objects.filter(user=user) for key, value in post.items(): # updating items in cart if key[:5] == 'clear': items.delete() if key[:6] == 'delete': item = Item.objects.get(name=key[7:]) models.CartItem.objects.get(user=user, item=item).delete() if key[:6] == 'amount': item = Item.objects.get(name=key[7:]) add_item = models.CartItem.objects.get(user=user, item=item) add_item.amount = value if int(value) <= 20 else 20 add_item.save() if key[:4] == 'make': order = Order(user=user) order.save() for item in items: order_item = OrderItem(item=item.item, amount=item.amount) order_item.save() order.items.add(order_item.id) order.save() items.delete() return redirect('checkout') try: models.Coupon.objects.get(name=request.session.get('_coupon')) messages.success(request, 'Coupon applied') except models.Coupon.DoesNotExist: pass return redirect('cart')
def create_order_from_express_paypal(nvp_dict): """ Create order in DB with ordered items """ #create order #create items #return order object order = Order() order.email = nvp_dict.get('email') order.b_first_name = nvp_dict.get('firstname') order.b_last_name = nvp_dict.get('lastname') order.b_address_countryname = nvp_dict.get('shiptocountryname') order.b_address_countrycode = nvp_dict.get('shiptocountrycode') order.b_address_zip = nvp_dict.get('shiptozip') order.b_address_state = nvp_dict.get('shiptostate') order.b_address_city = nvp_dict.get('shiptocity') order.b_address_street = nvp_dict.get('shiptostreet') \ + nvp_dict.get('shiptostreet2', "") order.shipping_address_flag = False order.status = order.NEW_ORDER order.paypal_transaction_id = nvp_dict.get('transactionid') order.save() item_ids = [(key, value) for key, value in nvp_dict.iteritems() if key.startswith("l_paymentrequest_0_number")] print item_ids for index, i in enumerate(item_ids): product = Prize.objects.get(pk=i[1]) order_item = OrderItem() order_item.order_id = order.id order_item.product = product order_item.number = product.number order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index)) order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' + str(index)) order_item.save() return order
def save_order_items(nvp_dict, order): item_ids = [(key, value) for key, value in nvp_dict.iteritems() if key.startswith("l_paymentrequest_0_number")] print item_ids for index, i in enumerate(item_ids): product = Prize.objects.get(pk=i[1]) order_item = OrderItem() order_item.order_id = order.id order_item.product = product order_item.number = product.number order_item.name = product.name order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index)) order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' + str(index)) order_item.size, order_item.color \ = get_size_and_color_from_paypal(nvp_dict.get('l_paymentrequest_0_desc' + str(index))) print nvp_dict.get('l_paymentrequest_0_desc' + str(index)) order_item.save()
def checkout(self, order): """Copy all items on cart into order. Should be called in transaction to improve performance and keep integrity.""" for item in self.item_set.all(): if item.quantity <= 0 or item.off_shelf: raise CannotCheckoutItemException(item) OrderItem( order=order, product=item.product, quantity=item.quantity, price=item.price ).save()
def handle(self, *args, **options): filename = options['filename'] with open(filename) as json_file: data = json.load(json_file) for order in data: order_item_list = order.pop('items') order_saved = Order.objects.create(**order) order_item_model_list = [] for item in order_item_list: item['order_id'] = order_saved.order_number order_item = OrderItem(**item) order_item_model_list.append(order_item) order_saved.items.bulk_create(order_item_model_list)
def get_all(data, db_session, username=None): logger.info(LogMsg.START) if data.get('sort') is None: data['sort'] = ['creation_date-'] if username is not None: permissions, presses = get_user_permissions(username, db_session) has_permission([Permissions.ORDER_ITEM_GET_PREMIUM], permissions) logger.debug(LogMsg.PERMISSION_VERIFIED) result = OrderItem.mongoquery( db_session.query(OrderItem)).query(**data).end().all() res = [] for item in result: res.append(item_to_dict(item, db_session)) logger.debug(LogMsg.GET_SUCCESS, res) logger.info(LogMsg.END) return res
def order_add(request, template_name="/"): order = Order() order.date = datetime.datetime.now().strftime("%m/%d/%Y") order.last_updated = datetime.datetime.now().strftime("%m/%d/%Y") order.user = request.user order.ip_address = request.META['REMOTE_ADDR'] print(request.META['REMOTE_ADDR']) print('-----------------------------') print(request) order.transaction_id = 1 order.save() cart_item_list = cart.get_cart_items(request) for item in cart_item_list: order_item = OrderItem() order_item.product = item.product order_item.quantity = item.quantity order_item.price = item.price() order_item.order = order order_item.save() cart.clean(request) url = urlresolvers.reverse('my_account') return HttpResponseRedirect(url)
def get_all(data, db_session, username=None): logger.info(LogMsg.START) if data.get('sort') is None: data['sort'] = ['creation_date-'] if username is not None: logger.debug(LogMsg.PERMISSION_CHECK, username) validate_permissions_and_access(username, db_session, 'ORDER_ITEM_GET', access_level=Access_level.Premium) logger.debug(LogMsg.PERMISSION_VERIFIED, username) result = OrderItem.mongoquery( db_session.query(OrderItem)).query( **data).end().all() res = [] for item in result: res.append(item_to_dict(item, db_session)) logger.debug(LogMsg.GET_SUCCESS, res) logger.info(LogMsg.END) return res
def handle(self, *args, **options): """Create orders and order items""" start_datetime = "01.01.2018 09:00" orders_count = options['orders_count'][0] Order.objects.bulk_create([ Order( number=ind + 1, created_date=datetime.strptime(start_datetime, "%m.%d.%Y %H:%M") + timedelta(hours=ind) ) for ind in range(orders_count) ]) for order in Order.objects.all(): OrderItem.objects.bulk_create([ OrderItem( order=order, product_name=f"Товар-{randint(1, 100)}", product_price=randint(100, 9999), amount=randint(1, 10) ) for i in range(randint(1, 5)) ]) self.stdout.write(self.style.SUCCESS( f"Successfully created {orders_count} orders" ))
def test_string_representation(self): book_title = OrderItem(book="Test book title") self.assertEqual(str(book_title), book_title.book)
def test_sub_total(self): order_id = Order(id=1, total=9.99) order_id.save() sub_total = OrderItem(quantity=2, price=9.99, order=order_id) sub_total.save() self.assertEqual(sub_total.quantity * sub_total.price, 19.98)
def form_valid(self, form): self.object = form.save() # Fetch all products basket = self.request.session.get('basket', []) products_in_basket = [item.get('product') for item in basket] products = Product.objects.filter(pk__in=products_in_basket, active=True, shop__active=True).order_by('shop') products_dict = {product.pk: product for product in products} # Total cost & valid items list per shop shop_items_and_cost = dict.fromkeys( {product.shop for product in products}) for key in shop_items_and_cost: shop_items_and_cost[key] = { 'total_cost': Decimal(0.00), 'order_items': [], 'item_count': 0 } # Create orderItems for item in basket: product = products_dict[item.get('product')] count = item.get('count') # If product is not found, skip product if product is None: continue # If count is 0 or below, skip item if count < 1: continue order_item = OrderItem() order_item.product = product order_item.order = self.object order_item.count = count # Save the offer/on sale price if any, else use normal price order_item.price = product.offer_price if product.offer_price else product.price order_item.save() shop_items_and_cost[product.shop]['item_count'] += count shop_items_and_cost[product.shop]['total_cost'] += Decimal( order_item.subtotal()) shop_items_and_cost[product.shop]['order_items'].append(order_item) context = { 'order': self.object, 'shop_items_and_cost': shop_items_and_cost } html_message = render_to_string('emails/order_confirmation.html', context) txt_message = render_to_string('emails/order_confirmation.txt', context) subject = gettext('Order confirmation') self.object.status = Order.ORDERED email = EmailMultiAlternatives(subject, txt_message) email.from_email = settings.DEFAULT_FROM_EMAIL email.to = [self.object.email] email.attach_alternative(html_message, "text/html") email.content_subtype = 'html' email.mixed_subtype = 'related' with open('base/static/base/img/fb_logo.png', mode='rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', "<Foodbee_logo_long.png>") email.attach(image) email.send() # Clear session self.request.session.flush() return HttpResponseRedirect(self.get_success_url())
def create_order_from_direct_paypal(nvp_dict): """ Create order in DB with ordered items """ #create order #create items #return order object """ <QueryDict: {u'l_paymentrequest_0_number0': [4], u's_countrycode': [u'AX'], u'b_state': [u'sdf'], u'card_first_name': [u'sdf'], u's_last_name': [u'sdf'], u's_street': [u'sdf'], u'acct': [u'4239530610456015'], u'l_paymentrequest_0_amt0': [32], u'l_paymentrequest_0_name0': [u'Raw Edge Design Letters Print Black Polyester VEST'], u's_city': [u'sdf'], u's_state': [u'sdf'], u'version': [u'116.0'], u's_countryname': [u'Aland Islands'], u'build': [u'16770825'], u'cvv2': [u'123'], u'b_street': [u'dd'], u'email': [u'*****@*****.**'], u'l_paymentrequest_0_qty0': [2], u'b_countrycode': [u'AU'], u'b_countryname': [u'Afghanistan'], u'timestamp': [u'2015-06-14T10:22:07Z'], u'currencycode': [u'USD'], u'card_last_name': [u'sdf'], u's_zip': [u'dsf'], u'paymentrequest_0_amt': [64.0], u'phone': [u'sdf'], u'b_country': [u'1'], u'cardyear': [u'2020'], u'transactionid': [u'06M899763J781091D'], u'amt': [u'64.00'], u's_first_name': [u'sdf'], u'cvv2match': [u'M'], u'cardmonth': [u'05'], u'ack': [u'Success'], u'b_city': [u'sdf'], u'creditcardtype': [u'visa'], u'b_last_name': [u'dddddd'], u'b_zip': [u'sdf'], u'avscode': [u'X'], u'b_first_name': [u'sads'], u'correlationid': [u'dba9b733e476']}> """ order = Order() order.email = nvp_dict.get('email') order.phone = nvp_dict.get('phone', "") order.b_first_name = nvp_dict.get('b_first_name') order.b_last_name = nvp_dict.get('b_last_name') order.b_address_countryname = nvp_dict.get('b_countryname') order.b_address_countrycode = nvp_dict.get('b_countrycode') order.b_address_zip = nvp_dict.get('b_zip') order.b_address_state = nvp_dict.get('b_state') order.b_address_city = nvp_dict.get('b_city') order.b_address_street = nvp_dict.get('b_street') order.s_first_name = nvp_dict.get('s_first_name', "") order.s_last_name = nvp_dict.get('s_last_name', "") order.s_address_countryname = nvp_dict.get('s_countryname', "") order.s_address_countrycode = nvp_dict.get('s_countrycode', "") order.s_address_zip = nvp_dict.get('s_zip', "") order.s_address_state = nvp_dict.get('s_state', "") order.s_address_city = nvp_dict.get('s_city', "") order.s_address_street = nvp_dict.get('s_street', "") order.status = order.NEW_ORDER order.paypal_transaction_id = nvp_dict.get('transactionid') order.save() item_ids = [(key, value) for key, value in nvp_dict.iteritems() if key.startswith("l_paymentrequest_0_number")] #print item_ids for index, i in enumerate(item_ids): product = Prize.objects.get(pk=i[1]) order_item = OrderItem() order_item.order_id = order.id order_item.product = product order_item.number = product.number order_item.amount = nvp_dict.get('l_paymentrequest_0_amt' + str(index)) order_item.quantity = nvp_dict.get('l_paymentrequest_0_qty' + str(index)) order_item.save() return order
def create_order_item(item: Item, order: Order, amount: int): order_item = OrderItem(item=item, order=order, amount=amount) order_item.save()
def create_order(request): cart = Cart(request) items = map_cart_items(cart) order_items = [] if request.method == "POST": form = OrderCreateForm(request.POST) if form.is_valid(): with transaction.atomic(): # Bloque controlado por transaction order = form.save(commit=False) # Guarda una instancia previa al usar el commit=False de order. order.code = generate_unique_code() if cart.coupon: order.coupon = cart.coupon order.discount = cart.coupon.discount order.subtotal = cart.get_total_subtotal() # Suma Subtotales order.base12 = order.subtotal # Suma de items base12 order.iva = cart.get_total_subtotal() * Decimal(0.12) # calcular impuesto order.discount_value = round(Decimal(cart.get_discount()), 2) order.total = round(cart.get_total_price_after_discount() + Decimal(order.fee)) else: order.subtotal = cart.get_total_subtotal() order.base12 = order.subtotal order.iva = round(cart.get_total_subtotal() * Decimal(0.12)) # TODO: Dinamico order.total = round(order.subtotal + order.iva + Decimal(order.fee), 2) order.save() # Insert en BD. for item in cart: # order_items = [OrderItem1, OrderItem2, ....] order_items.append( OrderItem( order=order, product=item[1].get('product'), # Instancia de objecto producto price=item[1].get('price'), quantity=item[1].get('quantity') ) ) # OrderItem.objects.create( # order=order, # product=item[1].get('product'), # Instancia de objecto producto # price=item[1].get('price'), # quantity=item[1].get('quantity') # ) OrderItem.objects.bulk_create(order_items) # Borrar los items asociados a ese carrito cart.clear() # Metodo de notificacion via correo del cliente send_mail( "Commerce| Compra Exitosa", f"Su orden con codigo {order.code} ha generada exitosamente.", "*****@*****.**", [order.billing_email], fail_silently=False, ) return render(request, "order/order_created.html", {'order': order}) else: form = OrderCreateForm() return render( request, "order/order_form.html", { 'cart': cart, 'form': form, 'items': items } )
def edit_model(request,model,id,template_name=""): page=request.GET.get('page') if request.method == 'POST': print(request.POST) print('edit') if model == 'category': category = get_object_or_404(Category, id=id) postdata = request.POST.copy() category.name = postdata.get('name') category.slug = slug(category.name) category.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") category.description = postdata.get('description') is_active = postdata.get('is_active') if is_active == "True": category.is_active = True else: category.is_active = False category.save() print('edit category') elif model == 'subcategory': subcategory = get_object_or_404(SubCategory, id=id) subcategory.name = request.POST.get('name') subcategory.description = request.POST.get('description') subcategory.slug = slug(subcategory.name) is_active = request.POST.get('is_active') subcategory.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") if is_active=="True": subcategory.is_active = True else: subcategory.is_active = False subcategory.categories.clear() selected_c = json.loads(request.POST.get('selected_categories')) for s_c in selected_c: c = get_object_or_404(Category, slug=s_c) subcategory.categories.add(c) subcategory.save() print('edit subcategory') elif model == 'product': p = get_object_or_404(Product, id=id) postdata = request.POST.copy() p.name = postdata.get('name') product_name = postdata.get('name') p.brand = postdata.get('brand') p.sku = postdata.get('sku') p.price = postdata.get('price') p.old_price = postdata.get('old_price') p.quantity = postdata.get('quantity') p.description = postdata.get('description') user = get_object_or_404(MyUser, username=postdata.get('user')) p.user = user p.slug = slug(p.name) is_active = request.POST.get('is_active') if is_active=="True": p.is_active = True else: p.is_active = False p.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") if request.FILES: print('image_exist') ## delete image ### os.remove(MEDIA_ROOT+'images/products/thumbnails/'+p.image) os.remove(MEDIA_ROOT+'images/products/main/'+p.image) ################### p_main_file=request.FILES['img'] file_extention = os.path.splitext(str(request.FILES['img']))[1] # print(file_extention) # file_name = str(request.FILES['img']).split('.') # file_extention = file_name[len(file_name)-1] image_name = str(user)+'_'+p.name+file_extention p_thumbnail_file=request.FILES['img'] with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'wb+') as destination: if p_thumbnail_file.multiple_chunks(): for chunk in p_thumbnail_file.chunks(): destination.write(chunk) else: destination.write(p_thumbnail_file.read()) with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'rb+') as destination: image_file = destination.read() with open(MEDIA_ROOT+'images/products/main/'+image_name, 'wb+') as destination: destination.write(image_file) p.image=image_name else: print('image_empty') # p.save() p.subcategories.clear() selected_subc = json.loads(request.POST.get('selected_subcategories')) for p_subc in selected_subc: subc = get_object_or_404(SubCategory, slug=p_subc) p.subcategories.add(subc) p.save() print('edit product') elif model == 'myuser': user = get_object_or_404(MyUser, id=id) postdata = request.POST.copy() # print(postdata) user.username = postdata.get('name') user.first_name = postdata.get('first_name') user.last_name = postdata.get('last_name') user.date_of_birth = postdata.get('date_of_birth') user.address = postdata.get('address') user.telephone = postdata.get('telephone') # user.password = make_password(postdata.get('password')) is_active = postdata.get('is_active') if is_active=="True": user.is_active = True else: user.is_active = False is_staff = postdata.get('is_staff') if is_staff=="True": user.is_staff = True else: user.is_staff = False is_superuser = postdata.get('is_superuser') if is_superuser=="True": user.is_superuser = True else: user.is_superuser = False user.user_permissions.clear() selected_permissions= json.loads(request.POST.get('selected_permissions')) for s_p in selected_permissions: perm = get_object_or_404(Permission, codename=s_p) user.user_permissions.add(perm) user.save() print('edit myuser') elif model == 'order': order = get_object_or_404(Order, id=id) postdata = request.POST.copy() myuser = get_object_or_404(MyUser, username=postdata.get('user')) order.address = myuser.address order.phone = myuser.telephone order_status = get_object_or_404(OrderStatus, id= postdata.get('status')) order.status = order_status order.ip_address = postdata.get('ip_address') order.user = myuser order.transaction_id = postdata.get('transaction_id') order.last_updated = datetime.datetime.now().strftime("%m/%d/%Y") order.save() print(order.id); item = OrderItem.objects.filter(order=order) for i in item: i.delete() cart_items = cart.get_cart_items(request) for c in cart_items: orderitem = OrderItem() orderitem.product = c.product orderitem.price = c.price() orderitem.quantity = c.quantity orderitem.order = order orderitem.save() print('edit order') elif model == 'orderitem': orderitem = get_object_or_404(OrderItem, id=id) postdata = request.POST.copy() product = get_object_or_404(Product, slug=postdata.get('product')) orderitem.product = product orderitem.price = product.price orderitem.quantity = postdata.get('quantity') order = get_object_or_404(Order, id=postdata.get('order')) orderitem.order = order orderitem.save() print('edit orderitem') url = urlresolvers.reverse('model',kwargs = {'model':model})+'?page='+page return HttpResponseRedirect(url) # return show_model(request,model,page,'') else: app_list = permission_app(request) # print('_________________edit_permission_________________') if check_permission(request,'edit',model): if model == 'category': category = get_object_or_404(Category, id=id) elif model == 'subcategory': category = Category.objects.all() subcategory = get_object_or_404(SubCategory, id=id) print('subcategory') categories = [] for cate in subcategory.categories.all(): categories.append(slug(cate.name)) categories = json.dumps(categories) # print(categories) elif model == 'product': user_list = MyUser.objects.all() subcategory = SubCategory.objects.all() product = get_object_or_404(Product, id=id) subcategories = [] for subc in product.subcategories.all(): subcategories.append(slug(subc.name)) subcategories = json.dumps(subcategories) print('product') # print(subcategories) elif model == 'myuser': print('myuser') myuser = get_object_or_404(MyUser, id=id) user_permissions = myuser.get_all_permissions() all_permissions = Permission.objects.all() # for a in all_permissions: # print (a.codename) selected_permissions = [] for s_p in user_permissions: s_p_list = s_p.split('.') selected_permissions.append(s_p_list[1]) selected_permissions = json.dumps(selected_permissions) # print(selected_permissions) # print('--------permission------------') # print(all_permissions) elif model == 'order': user_list = MyUser.objects.all() order = get_object_or_404(Order, id=id) product = Product.objects.all() order_status = OrderStatus.objects.all() orderitem = OrderItem.objects.filter(order = order) print(orderitem) cart.clean(request) for o_i in orderitem: cart.add_orderitem_to_cart(o_i,request) cart_items = cart.get_cart_items(request) cart_items_list = [] for c in cart_items: # print(c) item = {} item.setdefault('image',c.image()) item.setdefault('name',c.name()) item.setdefault('quantity',c.quantity) price = str(c.price()) item.setdefault('price',price) total = str(c.total()) item.setdefault('total',total) item.setdefault('id',c.id) # print(item) cart_items_list.append(item) # print(order.status) # print(order.ORDER_STATUSES[0][1]) print('order') elif model == 'orderitem': product = Product.objects.all() order_list = Order.objects.all() orderitem = get_object_or_404(OrderItem, id=id) cart.clean(request) for o in orderitem: cart.add_orderitem_to_cart(o) cart_items = CartItem print('orderitem') # subcategories = SubCategory.objects.all() template_name = 'myadmin/edit/'+model+'.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request)) else: template_name = 'myadmin/err.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request))
def add_model(request,model,template_name=""): # show_model(request,model,template_name) # print(); result = ""; if request.method == 'POST': print('add') if request.POST.get('mode')=='add_cart_item': cart.add_to_cart(request) cart_items_list = [] cart_items = cart.get_cart_items(request) # serializers.serialize("json", ) cart_item_count = cart.cart_distinct_item_count(request) # result = {'cart_items' : cart_items ,'cart_item_count' : cart_item_count} # print(cart_item_count) for c in cart_items: # print(c) item = {} item.setdefault('image',c.image()) item.setdefault('name',c.name()) item.setdefault('quantity',c.quantity) price = str(c.price()) item.setdefault('unit_price',price) total = str(c.total()) item.setdefault('total_price',total) item.setdefault('id',c.id) # print(item) cart_items_list.append(item) # print(cart_items_list) # cart_items = serializers.serialize("json", cart_items_list) # print(cart_items) result = {'cart_items' : cart_items_list ,'cart_item_count' : cart_item_count} # print(json.dumps(result)) print('++++++++++++++++++++++++++++++') return HttpResponse(json.dumps(result),content_type='application/javascript; charset=utf-8') else: if model == 'people': name = request.POST.get('name') islug = slug(name) category = Category() category.name = name category.description = request.POST.get('description') is_active = request.POST.get('is_active') if is_active=="on": category.is_active = True else: category.is_active = False category.slug = islug category.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") category.created_at = datetime.datetime.now().strftime("%m/%d/%Y") category.save() result = "saved" print('add people') elif model == 'subcategory': subcategory = SubCategory() subcategory.name = request.POST.get('name') subcategory.description = request.POST.get('description') subcategory.slug = slug(subcategory.name) is_active = request.POST.get('is_active') subcategory.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") subcategory.created_at = datetime.datetime.now().strftime("%m/%d/%Y") if is_active=="on": subcategory.is_active = True else: subcategory.is_active = False subcategory.save() selected_c = json.loads(request.POST.get('selected_categories')) for s_c in selected_c: c = get_object_or_404(Category, slug=s_c) subcategory.categories.add(c) subcategory.save() print('add subcategory') elif model == 'product': p = Product() postdata = request.POST.copy() p.name = postdata.get('name','a') product_name = postdata.get('name','a') p.brand = postdata.get('brand') p.sku = postdata.get('sku') p.price = postdata.get('price') p.old_price = postdata.get('old_price') p.quantity = postdata.get('quantity') p.description = postdata.get('description') # print(postdata.get('user')) user = get_object_or_404(MyUser, username=postdata.get('user')) p.user = user p.slug = slug(p.name) is_active = request.POST.get('is_active') if is_active=="on": p.is_active = True else: p.is_active = False p.updated_at = datetime.datetime.now().strftime("%m/%d/%Y") p.created_at = datetime.datetime.now().strftime("%m/%d/%Y") if request.FILES: print('image_exist') p_main_file=request.FILES['img'] file_extention = os.path.splitext(str(request.FILES['img']))[1] # print(file_extention) # file_name = str(request.FILES['img']).split('.') # file_extention = file_name[len(file_name)-1] image_name = str(user)+'_'+p.name+file_extention p_thumbnail_file=request.FILES['img'] with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'wb+') as destination: if p_thumbnail_file.multiple_chunks(): for chunk in p_thumbnail_file.chunks(): destination.write(chunk) else: destination.write(p_thumbnail_file.read()) with open(MEDIA_ROOT+'images/products/thumbnails/'+image_name, 'rb+') as destination: image_file = destination.read() with open(MEDIA_ROOT+'images/products/main/'+image_name, 'wb+') as destination: destination.write(image_file) p.image=image_name else: print('image_empty') p.image='default' p.save() selected_subc = json.loads(request.POST.get('selected_subcategories')) for p_subc in selected_subc: subc = get_object_or_404(SubCategory, slug=p_subc) p.subcategories.add(subc) p.save() print('add product') elif model == 'myuser': user = MyUser() postdata = request.POST.copy() user.username = postdata.get('name') user.first_name = postdata.get('first_name') user.last_name = postdata.get('last_name') ##########change date format###########YYYY-MM-DD # date_of_birth = postdata.get('date_of_birth') # date_list = date_of_birth.split('/') # join_str = '-' # user.date_of_birth = join_str.join(date_list) user.date_of_birth = postdata.get('date_of_birth') ######################################## user.address = postdata.get('address','a') user.telephone = postdata.get('telephone') user.password = make_password(postdata.get('password')) user.is_active = True user.is_staff = True user.save() print('add myuser') elif model == 'order': order = Order() postdata = request.POST.copy() myuser = get_object_or_404(MyUser, username=postdata.get('user')) print(postdata) order.address = myuser.address order.phone = myuser.telephone order_status = get_object_or_404(OrderStatus, id=postdata.get('status')) print(order_status.name) order.status = order_status order.ip_address = postdata.get('ip_address') # user = get_object_or_404(MyUser, username=postdata.get('user')) order.user = myuser order.transaction_id = postdata.get('transaction_id') order.last_updated = datetime.datetime.now().strftime("%m/%d/%Y") order.save() print(order.id); cart_items = cart.get_cart_items(request) for c in cart_items: orderitem = OrderItem() orderitem.product = c.product orderitem.price = c.price() orderitem.quantity = c.quantity orderitem.order = order orderitem.save() print('add order') elif model == 'orderitem': orderitem = OrderItem() postdata = request.POST.copy() product = get_object_or_404(Product, slug=postdata.get('product')) orderitem.product = product orderitem.price = product.price orderitem.quantity = postdata.get('quantity') order = get_object_or_404(Order, id=postdata.get('order')) orderitem.order = order orderitem.save() print('add orderitem') # return show_model(request,model,'') url = urlresolvers.reverse('model',kwargs = {'model':model}) return HttpResponseRedirect(url) else: app_list = permission_app(request) # print('_________________addpermission_________________') if check_permission(request,'add',model): if model == 'people': print('category') elif model == 'subcategory': category = Category.objects.all() print('subcategory') elif model == 'product': user_list = MyUser.objects.all() subcategory = SubCategory.objects.all() print('product') print(subcategory) elif model == 'myuser': print('myuser') elif model == 'order': cart.clean(request) user_list = MyUser.objects.all() product = Product.objects.all() order_status = OrderStatus.objects.all() # print(request.GET) # print('-------------------------------') # cart.add_to_cart(request) # cart_items = serializers.serialize("json", cart.get_cart_items(request)) # cart_item_count = cart.cart_distinct_item_count(request) # result = {'cart_items' : cart_items ,'cart_item_count' : cart_item_count} # print(result) # print('++++++++++++++++++++++++++++++=') # return HttpResponse(json.dumps(result),content_type='application/javascript; charset=utf-8') print('order') elif model == 'orderitem': product = Product.objects.all() order_list = Order.objects.all() print('orderitem') # subcategories = SubCategory.objects.all() template_name = 'myadmin/add/'+model+'.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request)) else: template_name = 'myadmin/err.html' return render_to_response(template_name, locals(),context_instance=RequestContext(request))
def success(request): from order.utils import generate_order_pdf from django.template.loader import render_to_string from django.core import mail from django.core.mail import EmailMultiAlternatives, EmailMessage from django.contrib.auth.models import Group try: order = request.session['order'] except KeyError: raise Http404 if order.user != request.user: raise Http404 cart = get_cart(request) cart = archive_cart(cart) order.cart = cart.id order.save() del request.session['cart'] voucher = request.session['voucher'] if 'voucher' in request.session else None items = ArchivedCartItem.objects.filter(archived_cart=cart) for item in items: order_item = OrderItem() order_item.order = order order_item.product = item.product order_item.quantity = item.quantity order_item.discount_total = item.discount_total order_item.gross_total = item.gross_total order_item.net_total = item.net_total order_item.save() #Update sold figure item.product.sold += item.quantity item.product.save() order.status = 1 order.save() pdf = generate_order_pdf(request.get_host(), order, voucher) subject = _('EMPOR Order Confirmation') html_content = render_to_string('order/email.html', { 'order': order, 'items': items, 'voucher': voucher, 'STATIC_URL': settings.STATIC_URL, 'host': request.get_host() }) text_content = render_to_string('order/email.txt', { 'order': order, 'voucher': voucher, 'items': items, 'host': request.get_host() }) connection = mail.get_connection() connection.open() message = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL, [order.user.email]) message.attach_alternative(html_content, 'text/html') filename = order.order_id message.attach(filename.encode('utf-8'), pdf, 'application/pdf') group = Group.objects.get(name='Service').user_set.only('email') subject = 'EMPOR - 新訂單 %s' % order.order_id group_email = [ user.email for user in group ] notification = EmailMessage(subject, html_content, settings.DEFAULT_FROM_EMAIL, group_email) notification.content_subtype = 'html' connection.send_messages([message, notification]) connection.close() if 'voucher' in request.session: del request.session['voucher'] return redirect('order-thankyou')
def order_thanks(request): """購入 > 完了""" if request.method != 'POST': return redirect('order:order_list') # セッション情報取得 session_form_cart_data = request.session.get('cart_data') session_form_user_data = request.session.get('user_data') if session_form_cart_data is None: # セッション切れや、セッションが空でURL直接入力したら入力画面にリダイレクト。 return redirect('order:order_list') # 金額初期値 subtotal = 0 total_tax = 0 subtotal_in_tax = 0 ship_cost = 0 total_price = 0 # POSTから購入商品情報をリスト化 cart_data = [] product_list = Product.objects.all().filter(public=1).order_by('id') for product in product_list: product_cnt = session_form_cart_data[('product_%d' % product.id)] # 購入数 if int(product_cnt) > 0: # 小計金額に加算 product_total = int(product.price) * int(product_cnt) subtotal += product_total cart_data.append({ 'product_cnt': product_cnt, 'id': product.id, 'name': product.name, 'product_total': "{:,}".format(product_total), 'product_total_val': product_total, 'image': product.image }) total_tax = int(round((subtotal * 0.1))) # 消費税 subtotal_in_tax = int(subtotal) + int(total_tax) # 消費税込み金額 # 送料 if subtotal_in_tax < 5000: ship_cost = 800 # 総合計金額 total_price = int(subtotal_in_tax) + int(ship_cost) order_code = random.randrange(10000000, 99999999) main_context = {} order_items = [] # DB登録order order = Order( status=1, order_code=order_code, name=session_form_user_data['name'], kana=session_form_user_data['kana'], tel=session_form_user_data['tel'], mail=session_form_user_data['mail'], zip=session_form_user_data['zip'], address_1=session_form_user_data['address_1'], subtotal=subtotal, total_tax=total_tax, ship_cost=ship_cost, total_price=total_price, ) Order.save(order) # DB登録orderitem for data in cart_data: print(data['id']) product = Product.objects.filter(id=data['id'])[0] orderitem = OrderItem( order=order, product=product, name=product.name, price=product.price, count=data['product_cnt'], subtotal=data['product_total_val'], ) order_items.append(orderitem) OrderItem.save(orderitem) # メールテキスト print(order) print(order.name) main_context['order'] = order main_context['order_items'] = order_items # メール配信 subject = 'タイトル' from_email = '*****@*****.**' recipient_list = ['*****@*****.**'] message = render_to_string('order/tmpl-mail.txt', main_context, request) email = EmailMessage(subject, message, from_email, recipient_list) email.send() context = { 'order_code': order_code, } # セッション削除 request.session.flush() return render(request, 'order/order_thanks.html', context)
def create_order_item(self, order: Order): order_item = OrderItem(item=self._item, order=order, amount=self._amount) order_item.save()
def handle(self, *args, **options): file_path = args[0] if not os.path.isfile(file_path): self.stdout.write('File %s not exists' % args[0]) json_file = open(file_path) orders = json.loads(json_file.read()) for order in orders: print(order['id']) try: user = User.objects.get(username=str(order['user_id'])) except User.DoesNotExist: continue try: new_order = Order.objects.get(pk=order['id']) except Order.DoesNotExist: print('Does.NotExist') new_order = Order(user=user, total_price=0) new_order.city = order['city'] print(order['address']) new_order.address_street = order['address'][:63] new_order.total_price = float(order['total']) #new_order.payment_method = order['payment_method'] new_order.phone = order['phone'][:31] new_order.address_zipcode = order['zip_code'] new_order.add_time = order['timestamp'] new_order.user = user client_name = client_name_len = None if order['fullname']: client_name = order['fullname'].split(' ') else: client_name = None client_name_len = len(client_name) if client_name else 0 client_first_name = client_second_name = client_last_name = None if client_name_len > 0: client_last_name = client_name[0] if client_name_len > 1: client_first_name = client_name[1] if client_name_len > 2: client_second_name = client_name[2] new_order.client_name = client_first_name or "" new_order.client_second_name = client_second_name new_order.client_last_name = client_last_name new_order.save() items = order['items'] for item in items: new_item = OrderItem() new_item.order = new_order new_item.scale = item['scale'] new_item.name = item['title'] #new_item. = item['url'] new_item.price = float(item['price']) new_item.article = item['article'] new_item.quantity = item['quantity'] new_item.manufacturer = item['manufacturer'] try: new_item.item = Item.objects.get(article=new_item.article) except Item.DoesNotExist: continue new_item.save() # order['shipping_method'] # order['comments'] # discount = order['discount'] # order['state'] # order['total_without_discount'] # order['shipping_price'] # # order['fullname'] #