Пример #1
0
    def update(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:
            #logger.debug('params=%s' % request.POST)
            if id:
                ext_posted_data = simplejson.loads(request.POST.get('items'))
                attrs = self.flatten_dict(ext_posted_data)
                return backend.logic.customer.item.update(Profile.getProfile(request.user), attrs, id)

            else:
                return backend.logic.customer.item.update(Profile.getProfile(request.user), request.POST, id)

        except Exception, err:
            if str(err).startswith( 'Duplicate UPC' ):
                logger.info(err)
                ready_data_false['errors'] = str(err)  # 'Error Saving Product'
            else:
                logger.error(err)
                ready_data_false['errors'] = 'Error Saving Product, Contact Administrator'
                ready_data_false['e'] = str(err)

            return ready_data_false
Пример #2
0
def confirm_registration(request: Request, ) -> Response:
    """
    Confirm user registration using sent token.
    :param request: contains confirmation token in query params.
    :return: response whether request is successful.
    """

    token = request.query_params.get("token")

    try:
        payload = RefreshToken(token=token, ).payload
    except TokenError:
        return Response(
            data={
                "message": "Token is invalid or expired.",
            },
            status=HTTP_400_BAD_REQUEST,
        )

    id_ = int(payload["id"])

    Profile.mark_active(id_=id_, )

    return Response(
        data={"message": "Email is verified, registration completed."},
        status=HTTP_200_OK,
    )
Пример #3
0
def register(request):
    if request.method == 'POST':
        uform = UserRegisterForm(request.POST)
        pform = ProfileRegisterForm(request.POST)
        if uform.is_valid() and pform.is_valid():
            new_username = uform.cleaned_data['username']
            uform.save()
            new_user = User.objects.get(username=new_username)
            pdata = pform.cleaned_data
            account = Profile(user=new_user,
                              fname=pdata['fname'],
                              lname=pdata['lname'],
                              number=pdata['number'],
                              address=pdata['address'],
                              gender=pdata['gender'],
                              graduation_year=getGrad(pdata['grade']),
                              section=pdata['section'],
                              code=pdata['code'],
                              medium=pdata['medium'],
                              shift=pdata['shift'],
                              form_teacher=pdata['form_teacher'])
            account.save()
            messages.success(
                request,
                "Your account has been successfully created. You can now log in."
            )
            return redirect('login')
            # add a message saying ur account has been created
            # redirect to the login page
    else:
        uform = UserRegisterForm()
        pform = ProfileRegisterForm()

    context = {'uform': uform, 'pform': pform}
    return render(request, 'frontend/register.html', context)
Пример #4
0
def register_user(request: Request, ) -> Response:
    """
    Register new user.
    :param request: contains e-mail and password.
    :return: response whether request is successful.
    """

    email: str = request.data.get("email")
    email = BaseUserManager.normalize_email(email).lower()
    phone_number: str = request.data.get("phone_number", "")
    password: str = request.data.get("password")

    if not email or not password:
        return Response(
            data={"message": "No email or password provided."},
            status=HTTP_400_BAD_REQUEST,
        )

    if Profile.exists(email):
        return Response(
            data={"message": "User with such email already exists."},
            status=HTTP_400_BAD_REQUEST,
        )

    user = Profile.register(
        email=email,
        password=password,
    )

    queue = get_according_notification_queue(
        prefix="sms" if phone_number else "email", )

    body = make_confirmation_message(
        view=confirm_registration,
        confirmation_token=RefreshToken.for_user(user),
    )

    message_queue_provider.send_confirmation(
        queue=queue,
        recipient=phone_number if phone_number else email,
        subject="Registration confirmation",
        body=body,
    )

    device = "phone" if phone_number else "email address"

    return Response(
        data={
            "message":
            f"User created successfully, "
            f"check your {device} for confirmation link.",
        },
        status=HTTP_200_OK,
    )
Пример #5
0
def register_admin(request: Request, ) -> Response:
    """
    Register new admin.
    :param request: contains email and password with admin token in header.
    :return: response whether request is successful.
    """

    token_from_request = request.META.get("HTTP_AUTHORIZATION",
                                          "").split("Bearer ")[-1]

    try:
        token = AccessToken(token_from_request)
        profile = Profile.objects.get(user_id=token["id"])
        if profile.role != Admin:
            raise PermissionError
    except (TokenError, PermissionError):
        return Response(
            data={
                "message": "Invalid credentials.",
            },
            status=HTTP_401_UNAUTHORIZED,
        )

    email: str = request.data.get("email")
    email = BaseUserManager.normalize_email(email).lower()
    password: str = request.data.get("password")

    if not email or not password:
        return Response(
            data={"message": "No email or password provided."},
            status=HTTP_400_BAD_REQUEST,
        )

    if Profile.exists(email):
        return Response(
            data={"message": "User with such email already exists."},
            status=HTTP_400_BAD_REQUEST,
        )

    Profile.register(
        email=email,
        password=password,
        role=Admin,
        is_active=True,
    )

    return Response(
        data={
            "message": "Admin created successfully.",
        },
        status=HTTP_201_CREATED,
    )
Пример #6
0
    def __init__(self, **kwargs):
        self.request  = kwargs['request']
        self.req_params = kwargs['req_params']

        #internal variables
        self._method    = 'GET'
        self._success = True
        self._reasons = []
        self._params  = {}
        
        """This is a list of all attributes that will be added to self._params"""
        # request, profile, parent_user_id', user, name, description, start, limit
        # dir, sent, callback, number_like, date_lte, date_gte, upc, categoryOnly, vendor_id,
        # price, product, date, number, verified,
        # show_best, show_disabled, search, total_units, total_units_per_package, order_qt

        self._params['request'] = self.request    
        currentProfile = Profile.getProfile(self.request.user)
        self._params['profile'] = currentProfile
        self._params['parent_user_id'] = currentProfile.parent_user.id
        self._params['user'] = self.request.user.id # TODO: REMOVE, can get user from profile


        #default grid params
        self._start = 0
        self._limit = 17

        #memcache
        #self.mc = settings.MCCLIENT

        self.worker()
Пример #7
0
    def update(self, request, id=None):

        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        currentProfile  = Profile.getProfile(request.user)

        ext_posted_data = simplejson.loads(request.POST.get('items'))
        attrs = self.flatten_dict(ext_posted_data)

        try:
            del attrs['id']
        except KeyError:
            pass

        item = Item.objects.get(pk=attrs['item_id'])
        try:
            del attrs['item_id']
        except KeyError:
            pass
        obj, created = self.model.objects.get_or_create(user=currentProfile.parent_user, item=item)
        comp = self.model.objects.filter(user=currentProfile.parent_user, item=item).update(**attrs)
        ready_data_true['items'] = obj.list()
        ready_data_true['total'] = 1

        return ready_data_true
Пример #8
0
def index(request):
    import re

    deploy = False
    #deploy = True

    if request.user.is_authenticated():
        currentProfile = Profile.getProfile(request.user)
        
        #if logger.isEnabledFor(logging.INFO):
            #logger.info('AUTHORIZED user(%s) from IP: %s, HOST: %s' % (request.user, request.META['REMOTE_ADDR'],  request.META['HTTP_HOST']))


        role = currentProfile.role
        # if role == 1 - Admin
        if role == '1':
            main_css_path = ''
            return render(request, 'admin_app/index.html', {'role': role, 'main_css_path': main_css_path,  'username':request.user.username, 'user_id':request.user.id}, content_type="text/html")
        # role = 5 - Vendor Salesman
        if role == '5':
            main_css_path = 'vs_resources/'
            return render(request, 'vsalesman_app/index.html', {'profile': currentProfile, 'role': role, 'main_css_path': main_css_path, 'email': request.user.email, 'username':request.user.username, 'user_id':request.user.id}, content_type="text/html")
        if role == '2' or role == '3' or role == '4': # role = 4 - Vendor
            try:
                s = Settings.objects.get(user=currentProfile.user)
            except ObjectDoesNotExist, err:
                s = Settings.createDefaultSettings(currentProfile.user)

            main_css_path = 'mobile_resources/'
            if re.search( r'iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm|silk', request.META['HTTP_USER_AGENT'].lower(), re.I):
                return render(request, 'touch/index.html', {'profile': currentProfile,'settings': Settings.objects.get(user=request.user)}, content_type="text/html")
            else:
                main_css_path = ''
                return render(request, 'cust_app/index.html', {'profile': currentProfile,'settings': s,'role': role, 'main_css_path': main_css_path, 'email': request.user.email, 'username':request.user.username, 'user_id':request.user.id}, content_type="text/html")
Пример #9
0
    def delete(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false


        # TODO: Check if current profile allowed to delete orders
        currentProfile  = Profile.getProfile(request.user)
        
        if id:
            try:
                order = Order.objects.get(pk=id, user=currentProfile.parent_user)
                itemProduct = order.product
                item_id = str(order.item.id)
                itemProduct.delete()
                order.delete()
                updateBestPriced(None, None, item_id)
                return ready_data_true
            except ObjectDoesNotExist:
                ready_data_false['errors'] = "id doesn't exist, id=" + str(id)
                return ready_data_false

        else:
            ready_data_false['errors'] = 'id is required, id=' + str(id)
            return ready_data_false
Пример #10
0
    def update(self, request, id=None):

        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        currentProfile = Profile.getProfile(request.user)

        if request.POST.get('action')== 'zero_prices':
            # TODO: check if user allowed to zero Prices
            # user wants to zero all prices for given vendor products
            # the process may take some time, so use thread
            # updateBestPriced will be done at the end of zeroVendorPrices method
            try:
                vendor_id = request.POST.get('vendor_id')
                if not vendor_id:
                    ready_data_false['msg'] = 'vendor_id is required'
                    return ready_data_false

                Thread(target=zeroVendorPrices, kwargs={"vendor_id":vendor_id, "user":currentProfile.parent_user}).start()
                return ready_data_true

            except Exception, err:
                logger.error(err)
                ready_data_false['msg'] = err
                return ready_data_false
Пример #11
0
    def delete(self, request, id=None):
        
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        currentProfile  = Profile.getProfile(request.user)
        # TODO: Need To Check if Current Profile allowed to perform this action
        
        reason = []
        if id:
            product = self.model.objects.get(pk=id, user=currentProfile.parent_user)
            product.delete()
            return ready_data_true
                
        else:
            if 'vendor_id' in request.GET:
                vendor_id = request.GET['vendor_id']
                products = self.model.objects.filter(vendor=vendor_id, user=currentProfile.parent_user)
                capacity = len(products)
                products.delete()
            else:
                products = self.model.objects.filter(user = currentProfile.parent_user)
                capacity = len(products)
                products.delete()

            ready_data_true['message'] = u'%s products was deleted' % capacity
            return ready_data_true
Пример #12
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:
            currentProfile = Profile.getProfile( request.user)

            start = 0
            limit = 1000 # will most likely get all vendors
            try:
                start    = int(request.GET['start'])
                limit    = int(request.GET['limit'])
            except Exception:
                pass # do nothing default values for start and limit already set
            search = None

            return Vendor.getVendors(currentProfile.parent_user, id, search, start, limit)

        except Exception, err:
            logger.error(err)
            ready_data_false['errors'] = err
            return ready_data_false
Пример #13
0
def signup(request):
    if request.user.is_authenticated:
        return redirect('/')
    if request.method == 'POST':
        form = Sign_up_form(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            profile = Profile(user=user)
            profile.save()
            login(request, user)
            return redirect('/')
    else:
        form = Sign_up_form()
    return render(request, 'registration/signup.html', {'form': form})
Пример #14
0
    def read(self, request, id=None):

        ready_data_true = {"success": True}
        ready_data_false = {"success": False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:
            currentProfile = Profile.getProfile(request.user)

            item_id = request.GET.get("item_id")
            ready_data_false["item_id"] = item_id  # for debug

            if item_id:
                item_id = int(item_id)
                count = Ingredient.objects.filter(user=currentProfile.parent_user, item=item_id).count()
                ingredients = Ingredient.objects.select_related("item", "item__unit").filter(
                    user=currentProfile.parent_user, item=item_id
                )[0:count]

                retData = []
                for ingredient in ingredients:
                    try:
                        recipeItem = Item.objects.get(pk=ingredient.recipe_item_id)
                    except ObjectDoesNotExist:  # if recipe doesn't exist, ingredients should of been deleted when item was deleted
                        ingredient.delete()
                        continue
                    sales = Sales.objects.filter(
                        user=currentProfile.parent_user, item=ingredient.recipe_item_id
                    ).order_by("-date_to")[0:1]
                    qt_sold_last_week = 0
                    if len(sales) == 1:
                        if ingredient.qt:
                            qt_sold_last_week = sales[0].qt_sold * ingredient.qt
                    data = {}
                    # data['recipe_item_id']  = ingredient.recipe_item_id
                    data["item_name"] = recipeItem.name
                    data["upc"] = recipeItem.upc
                    data["unit_name"] = ingredient.item.unit.name
                    data["qt_used"] = replace(ingredient.qt)
                    data["qt_sold_last_week"] = replace(qt_sold_last_week)

                    retData.append(data)

                count = Ingredient.objects.filter(user=currentProfile.parent_user, item=item_id).count()
                ready_data_true["items"] = retData
                ready_data_true["total"] = count
                return ready_data_true

            else:
                raise Exception("recipe_item_id is required")

        except Exception, err:
            logger.error(err)
            ready_data_false["errors"] = err
            return ready_data_false
Пример #15
0
def signup(request):
    required_data = ["username", "password", "firstname", "lastname"]
    data = json.loads(request.body)
    for key in required_data:
        if key not in data:
            return HttpResponse("Missing data to create user.", status=401)
    if User.objects.filter(username=data["username"]):
        return HttpResponse("Username already in use.", status=409)
    try:
        validate_password(data["password"])
    except:
        return HttpResponse("Password is not strong enough.", status=400)
    new_user = User(username=data["username"])
    new_user.set_password(data["password"])
    new_user.save()
    new_profile = Profile(first_name=data["firstname"],
                          last_name=data["lastname"])
    new_profile.user = new_user
    new_profile.save()
    return HttpResponse("User created successfully.")
Пример #16
0
    def read(self, request, id=None):
        # Return Relationships for current user.
        # if id in request, return that specific Relationship
        # This method only for user Admin
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false
            
        try:
            if not request.user.is_authenticated():
                #return rc.FORBIDDEN
                ready_data_false["error"] = "Authorization is failed"
                return ready_data_false

            currentProfile = Profile.getProfile(request.user)
            if currentProfile.get_role_display() != 'Admin': # User must be Admin
                ready_data_false['error'] = 'Not Allowed'
                return ready_data_false

            if 'start' in request.GET:
                start = int(request.GET.get('start'))
            else:
                start = 0

            if 'limit' in request.GET:
                limit = int(request.GET.get('limit'))
            else:
                limit = 25

            customer = vendor = None
            if 'customer' in request.GET:
                customer = request.GET.get('customer')
                count = self.model.objects.filter(customer=customer).count()
                ready_data_true['items'] =  self.model.objects.select_related('customer', 'vendor').filter(customer=customer)[start:start+limit]
                ready_data_true['total'] = count

            elif 'vendor' in request.GET:
                vendor = request.GET.get('vendor')
                count = self.model.objects.filter(vendor=vendor).count()
                ready_data_true['items'] =  self.model.objects.select_related('customer', 'vendor').filter(vendor=vendor)[start:start+limit]
                ready_data_true['total'] = count

            else:
                ready_data_false['errors'] = 'no customer or vendor arguments defined' # should not get here
                return ready_data_false

            return ready_data_true
            
        except Exception, err:
            ready_data_false['errors'] = err
            return ready_data_false
Пример #17
0
    def Verify(self, request, context):
        try:
            token = UntypedToken(request.token)
            profile = Profile.objects.get(user_id=token["id"])
            profile.has_valid_token = True
        except TokenError as e:
            print(e)
            profile = Profile(user=User())

        profile_serializer = ProfileProtoSerializer(profile)

        return profile_serializer.message
Пример #18
0
    def create(self, request):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        currentProfile = Profile.getProfile( request.user)

        try:
            ext_posted_data = simplejson.loads(request.POST.get('items'))
            attrs = self.flatten_dict(ext_posted_data)

            req = check(request, id=None, attrs=attrs)

            if req == True:
                reason=[]
                item = self.model.objects.create(\
                    name = replace(attrs['name']), \
                    category_id = attrs['category_id'], \
                    unit_id = attrs['unit_id'], \
                    upc = replace(attrs['upc']), \
                    upc_2 = replace(attrs['upc_2']), \
                    upc_3 = replace(attrs['upc_3']), \
                    upc_case = replace(attrs['upc_case']), \
                    notes=replace(attrs['notes']), \
                    image_url=attrs['image_url'], \
                    qt_in_stock=0, \
                    qt_to_stock=0, \
                    min_qt_in_stock=2, \
                    enabled=True, \
                    sales_price=0, \
                    loc_stock = u'',\
                    loc_ret_dept = u'',\
                    loc_ret_col = u'',\
                    loc_ret_row = u'',\
                    inventory_no_count = False,\
                    so_ignore_no_sales = False,\
                    so_do_not_order = False,\
                    so_always_order = 0,\
                    user=currentProfile.parent_user)
                ready_data_true['items'] = item.list(item.id)
                return ready_data_true
            else:
                ready_data_false['errors'] = req
                return ready_data_false
        except Exception, err:
            logger.error(err)
            logger.error('REQUEST: %s' % str(request) )
            ready_data_false['errors'] = err.message
            ready_data_false['name'] = replace(attrs['name'])
            return ready_data_false
Пример #19
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false
        
        try:
            currentProfile = Profile.getProfile(request.user)

            params = {}
            params['start'] = request.GET.get('start')
            params['limit'] = int(request.GET.get('limit'))
            if params['limit'] <= 0:
                params['limit'] = 1

            params['item_id'] = request.GET.get('item_id') # if item_id is given, no other params are needed
            if params['item_id'] == None: # if no item_id is given, get location
                params['loc_ret_dept'] = request.GET.get('loc_ret_dept')

                params['date_from'] = request.GET.get('date_from')
                if params['date_from'] != None:
                    date_from_index = params['date_from'].find('T')
                    params['date_from'] = params['date_from'][0:date_from_index]
                    params['date_from']  = params['date_from']  + " 00:00:00"

                params['date_to'] = request.GET.get('date_to')
                if params['date_to'] != None:
                    date_to_index = params['date_to'].find('T')
                    params['date_to'] = params['date_to'][0:date_to_index]
                    params['date_to']  = params['date_to']  + " 23:59:59"


            return backend.logic.report.shrinkage.shrinkageReport(Profile.getProfile(request.user), params)

        except Exception, err:
            logger.error('Exception: %s' % err)
            ready_data_false['error'] = err
            return ready_data_false
Пример #20
0
def index(request):
    currentProfile = Profile.getProfile(request.user)
    parent_user_id = currentProfile.parent_user.id

    if 'purchase_id' in request.GET :
        purchase_id = request.GET['purchase_id']
    else:
        return { "success": False, "total": 0, "errors": "purchase_id is Required" }


    #logger.info('purchase_id:%s, parent_user_id: %s' % (purchase_id,parent_user_id))

    
    purchaseDetails = PurchaseDetail.objects.select_related('item').filter(purchase=purchase_id, user=parent_user_id)
    #count = PurchaseDetail.objects.get(id=purchase_id, user=parent_user_id).count()

    i = 0

    for purchaseDetail in purchaseDetails:
        #logger.info(str(purchaseDetail.list()))
        if purchaseDetail.inventory_updated:
            continue
        try:
            # update qt in stock
            if purchaseDetail.item.inventory_no_count:
                purchaseDetail.inventory_updated = True
                purchaseDetail.save()
                i = i + 1
                continue
            else:
                if purchaseDetail.item.qt_in_stock is None:
                    qt_in_stock = purchaseDetail.total_units
                else:
                    qt_in_stock = purchaseDetail.item.qt_in_stock + purchaseDetail.total_units

            if qt_in_stock < 0:
                qt_in_stock = 0
            purchaseDetail.item.qt_in_stock = qt_in_stock
            purchaseDetail.inventory_updated = True
            #logger.info('qt_in_stock: %s' % (qt_in_stock))
            purchaseDetail.item.save()
            purchaseDetail.save()

            if settings.HGM == True: # UPDATE qt_in_stock in WWW
                updateWwwQtInStock(purchaseDetail.item)
                
            i = i + 1

        except Exception, err:
            logger.error(err)
            continue # continue the loop even if there was a problem with 1 of the records
Пример #21
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}


        if not request.user.is_authenticated():
            #return rc.FORBIDDEN
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false
            

        if 'start' in request.GET:
            start       = int(request.GET.get('start'))
        else:
            start = 0

        if 'limit' in request.GET:
            limit       = int(request.GET.get('limit'))
        else:
            limit = 25
                    
        if 'search' in request.GET:
            search  = str(request.GET.get('search'))
        else:
            search = ''

        try:
            currentProfile = Profile.getProfile(request.user)
            if id:
                # allowed only if they have relationship
                if not backend.logic.util.profile_ids_are_related( id, currentProfile.id):
                    ready_data_false['errors'] = 'No Relationship found'
                    #ready_data_false['debug profile'] = str(id) + ' ' + str(currentProfile.id)
                    return ready_data_false
                else:
                    try:
                        ready_data_true['items'] = Profile.objects.get(pk=id).list()
                        return ready_data_true
                    except DoesNotExist:
                        ready_data_false['errors'] = u'Profile not found by ID'
                        return ready_data_false
            else:
                if currentProfile.get_role_display() == 'Admin':
                    try:
                        return backend.logic.admin.profile.getAllProfiles(currentProfile, search, start, limit)
                    except Exception, err:
                        logger.error(err)
                        ready_data_false['errors'] = u'%s' % err
                        return ready_data_false

                else:
Пример #22
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:
            return backend.logic.report.inventory.inventoryReport(Profile.getProfile(request.user))

        except Exception, err:
            logger.error('Exception: %s' % err)
            ready_data_false['error'] = err
            return ready_data_false
Пример #23
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false
        
        try:
            currentProfile = Profile.getProfile(request.user)

            params = {}
            params['start'] = request.GET.get('start')
            params['limit'] = int(request.GET.get('limit'))
            if params['limit'] <= 0:
                params['limit'] = 1


            return backend.logic.report.profit.profitReport(Profile.getProfile(request.user), request.GET)

        except Exception, err:
            logger.error('Exception: %s' % err)
            ready_data_false['error'] = err
            return ready_data_false
Пример #24
0
def profile_register_email(request, email):
    subscriber_uuid = request.headers['Subscriber-Uuid']
    # Assumption: for 1 subscriber, there's only 1 zone subscription for 1 day
    profile = Profile.register(subscriber_uuid=subscriber_uuid, email=email)
    validation_url = BASE_VALIDATION + profile.key_validation
    msg = "Profile Register OK"
    tmp = {
        "id": profile.id,
        "ts": profile.ts,
        "subscriber_uuid": profile.subscriber_uuid,
        "email": profile.email,
        "validation_url": validation_url,
        "validated": profile.validated
    }
    return generate_dict_response_ok(request, msg, [tmp])
Пример #25
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:
            currentProfile = Profile.getProfile(request.user)

            item_id     = request.GET.get('item_id')
            action     = request.GET.get('action')

            start = 0
            limit = 100 # will most likely get all credits
            try:
                start    = int(request.GET['start'])
                if start < 0:
                    start = 0
                limit    = start + int(request.GET['limit'])
                if limit <= 0:
                    limit = 1
            except Exception:
                pass # do nothing default values for start and limit already set
            search = None

            if id:
                try:
                    ready_data_true['items'] = self.model.objects.select_related('vendor', 'item').get(pk=id)
                    ready_data_true['total'] = 1
                    return ready_data_true
                except Exception, err:
                    ready_data_false['errors'] = err.message
                    return ready_data_false
            elif item_id:
                item_id = int(request.GET['item_id'])
                ready_data_false['item_id'] = str(item_id)
                credits = self.model.objects.select_related('vendor', 'item'). \
                    filter(user=currentProfile.parent_user, item__id=item_id).order_by('-date_requested')[start:limit]
                data = []
                for credit in credits:
                    data.append(credit.list())

                ready_data_true['items'] = data
                ready_data_true['total'] = len(ready_data_true['items'])
                return ready_data_true
Пример #26
0
    def update(self, request, id=None):
        
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            #return rc.FORBIDDEN
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        ext_posted_data = simplejson.loads(request.POST.get('items'))
        attrs = self.flatten_dict(ext_posted_data)

        try:
            del attrs['id']
        except KeyError:
            pass
        try:
            del attrs['password']
        except KeyError:
            pass

        reason=[]
        if id:
            req = check(request, id, attrs=attrs)
            if req == True:
                try:
                    currentProfile = Profile.getProfile(request.user)
                    if str(id) == str(currentProfile.id) or currentProfile.get_role_display() == 'Admin' :
                        Profile.objects.filter(pk=id).update(**attrs)
                        profile = Profile.objects.get(pk=id)
                    else:
                        ready_data_false['error'] = 'Not Allowed'
                        return ready_data_false
                except Exception, err:
                    ready_data_false['errors'] = err
                    return ready_data_false

                if profile.get_role_display() == 'Vendor' or profile.get_role_display() == 'Vendor salesmen':
                    updateVendorDependencies(profile)
                ready_data_true['items'] = profile
                return ready_data_true
            else:
                ready_data_false['errors'] = req
                ready_data_false['debug_attrs'] = attrs
                return ready_data_false
Пример #27
0
    def update(self, request, id=None):

        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        if id:
            try:
                currentProfile = Profile.getProfile(request.user)
                item_id = None
                vendor_id = None
                ext_posted_data = simplejson.loads(request.POST.get('items'))
                attrs = self.flatten_dict(ext_posted_data)

                try:
                    del attrs['id']
                except KeyError:
                    pass

                try:
                    item_id = attrs['item_id']
                    del attrs['item_id']
                except KeyError:
                    pass

                try:
                    vendor_id = attrs['vendor_id']
                    attrs['vendor'] = attrs['vendor_id']
                    del attrs['vendor_id']
                except KeyError:
                    pass

                table = self.model.objects.select_related('vendor', 'item').filter(pk=id).update(**attrs)

                ready_data_true['items'] = table
                ready_data_true['total'] = 1
                ready_data_true['attrs'] = attrs
                return ready_data_true

            except Exception, err:
                ready_data_false['errors'] = str(err)
                return ready_data_false
Пример #28
0
    def create(self, request):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:    
            currentProfile = Profile.getProfile(request.user)
            item_id = None
            vendor_id = None
            ext_posted_data = simplejson.loads(request.POST.get('items'))
            attrs = self.flatten_dict(ext_posted_data)

            try:
                del attrs['id']
            except KeyError:
                pass

            try:
                item_id = attrs['item_id']
                del attrs['item_id']
            except KeyError:
                pass

            try:
                date_time = attrs['date_time']
                attrs['date_time'] = datetime.now()
            except KeyError:
                pass

            attrs['reason'] = replace(attrs['reason'])

            table = self.model.objects.create(user=currentProfile.parent_user, item_id=item_id, **attrs)

            ready_data_true['items'] = table
            ready_data_true['total'] = 1
            return ready_data_true

        except Exception, err:
            logger.error(err)
            ready_data_false['errors'] = err
            return ready_data_false
Пример #29
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:
            currentProfile = Profile.getProfile(request.user)

            if 'item_id' in request.GET:
                item_id     = int(request.GET.get('item_id'))

            start = 0
            limit = 100 # will most likely get all records
            try:
                start    = int(request.GET['start'])
                limit    = start + int(request.GET['limit'])
            except Exception:
                pass # do nothing default values for start and limit already set
            search = None

            if id:
                try:
                    ready_data_true['items'] = self.model.objects.select_related('vendor', 'item').get(pk=id)
                    ready_data_true['total'] = 1
                    return ready_data_true
                except Exception, err:
                    ready_data_false['errors'] = err.message
                    return ready_data_false
            elif item_id:
                ready_data_false['item_id'] = str(item_id)
                table = self.model.objects.select_related( 'item'). \
                    filter(user=currentProfile.parent_user, item__id=item_id).order_by('-date_time')[start:limit]
                count = self.model.objects.filter(user=currentProfile.parent_user, item__id=item_id).count()
                data = []
                for a in table:
                    data.append(a.list())

                ready_data_true['items'] = data
                ready_data_true['total'] = count
                return ready_data_true
Пример #30
0
    def delete(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false
            
        try:
            params = {}
            params['item_id'] = id
            logger.debug('params=%s' % params)

            return backend.logic.customer.item.delete(Profile.getProfile(request.user), params)

        except Exception, err:
            logger.error(err)
            ready_data_false['errors'] = 'Error Deleting Product'
            return ready_data_false
Пример #31
0
    def read(self, request, id=None):

        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}
        
        currentProfile  = Profile.getProfile(request.user)
        
        if id:
            item_id = id
            item = Item.objects.get(pk=item_id)
            obj, created = self.model.objects.get_or_create(user=currentProfile.parent_user, item=item)

            ready_data_true['items'] = obj.list()
            ready_data_true['total'] = 1
            return ready_data_true
        else:
            item_id = request.GET.get('item_id')
            comp = self.model.objects.filter(user=currentProfile.parent_user, item=item_id)
            ready_data_true['items'] = comp[0].list()
            ready_data_true['total'] = 1
            return ready_data_true
Пример #32
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false
        
        try:
            params = {}
            params['loc_ret_dept'] = request.GET.get('loc_ret_dept')
            params['num_of_weeks'] = request.GET.get('num_of_weeks')
            params['start'] = request.GET.get('start')
            params['limit'] = request.GET.get('limit')

            return backend.logic.report.sales.salesReport(Profile.getProfile(request.user), params)

        except Exception, err:
            logger.error('Exception: %s' % err)
            ready_data_false['error'] = err
            return ready_data_false
Пример #33
0
    def read(self, request, id=None):

        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false


        try:
            currentProfile = Profile.getProfile(request.user)

            recipe_item_id     = request.GET.get('recipe_item_id')
            ready_data_false['recipe_item_id'] = recipe_item_id # for debug

            if recipe_item_id:
                recipe_item_id = int(recipe_item_id)
                count = self.model.objects.filter(user=currentProfile.parent_user, recipe_item_id=recipe_item_id).count()
                ingredients = self.model.objects.select_related('item', 'item__unit'). \
                    filter(user=currentProfile.parent_user, recipe_item_id=recipe_item_id)[0:count]

                data = []
                for ingredient in ingredients:
                    data.append(ingredient.list())

                ready_data_true['items'] = data
                ready_data_true['total'] = count
                return ready_data_true

            else:
                raise Exception('recipe_item_id is required')

        except Exception, err:
            logger.error(err)
            ready_data_false['errors'] = err
            return ready_data_false
Пример #34
0
    def create(self, request):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}
        
        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        ext_posted_data = simplejson.loads(request.POST.get('items'))
        attrs = self.flatten_dict(ext_posted_data)

        try:
            currentProfile = Profile.getProfile(request.user)

            obj = self.model.objects.create(user=currentProfile.parent_user, item_id=attrs['item_id'], \
                recipe_item_id=attrs['recipe_item_id'])
            
            ready_data_true['items'] = obj
            ready_data_true['total'] = 1
            return ready_data_true
        except Exception, err:
            logger.error(err)
            ready_data_false['errors'] = err.message
            return ready_data_false
Пример #35
0
    def create(self, request):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:    
            currentProfile = Profile.getProfile(request.user)
            item_id = None
            vendor_id = None
            ext_posted_data = simplejson.loads(request.POST.get('items'))
            attrs = self.flatten_dict(ext_posted_data)

            if 'action' in request.POST:
                if request.POST.get('action') == 'defaultCreate': # front end wants us to create default credit
                    # all info is in history table for this item
                    try:
                        item_id = attrs['item_id']
                    except KeyError:
                        raise Exception (u"item_id is required")

                    invoiceDetails  = InvoiceDetail.objects.select_related('item','product', 'product__vendor'). \
                        filter(item__id=item_id, user=currentProfile.parent_user, order_qt__gt='0').\
                            order_by('-invoice__date')[0:1]
                    
                    if len(invoiceDetails) > 0:
                        # should be enough info to create a reason
                        detail = invoiceDetails[0].list()
                        data = {}
                        data['date_delivered']              = detail['date']
                        data['prod_name']                   = detail['name1']
                        data['prod_num']                    = detail['product_num']
                        data['prod_upc']                    = detail['upc']
                        data['invoice_num']                 = detail['#']
                        data['credit_qt']                   = replace(Decimal(attrs['credit_qt'])*-1)
                        data['cost_ea']                     = detail['price_per_unit']
                        data['cost_total']                  = replace(Decimal(data['credit_qt'])*Decimal(data['cost_ea']))
                        data['date_requested']              = datetime.now()
                        data['credit_reason']               = attrs['credit_reason']

                        table = self.model.objects.create(user=currentProfile.parent_user, item_id=item_id, vendor_id=detail['vendor_id'], **data)

                        ready_data_true['items'] = table
                        ready_data_true['total'] = 1
                        return ready_data_true

            else:
                try:
                    del attrs['id']
                except KeyError:
                    pass

                try:
                    item_id = attrs['item_id']
                    del attrs['item_id']
                except KeyError:
                    pass

                try:
                    vendor_id = attrs['vendor_id']
                    del attrs['vendor_id']
                except KeyError:
                    pass

                table = self.model.objects.create(user=currentProfile.parent_user, item_id=item_id, vendor_id=vendor_id, **attrs)

                ready_data_true['items'] = table
                ready_data_true['total'] = 1
                return ready_data_true

        except Exception, err:
            logger.error(err)
            ready_data_false['errors'] = err
            return ready_data_false
Пример #36
0
    def read(self, request, id=None):
        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}
        
        if not request.user.is_authenticated():
            ready_data_false["errors"] = "Authorization is failed"
            return ready_data_false

        if 'virtuemart_order_id' in request.GET:
            virtuemart_order_id = request.GET.get('virtuemart_order_id')
        else:
            ready_data_false["errors"] = "virtuemart_order_id is Required Argument"
            return ready_data_false
              
        hgm = settings.HGM
        if hgm != True:
            ready_data_false["error"] = "Not HGM"
            return ready_data_false

        try:
            currentProfile = Profile.getProfile(request.user)
            hgm_www_host = settings.HGM_WWW_HOST
            hgm_www_port = settings.HGM_WWW_PORT
            hgm_www_user = settings.HGM_WWW_USER
            hgm_www_password = settings.HGM_WWW_PASSWORD
            hgm_www_db = settings.HGM_WWW_DB

             # CONNECTION TO www.hudsongreenemarket.com 52.0.0.79
            myDB = MySQLdb.connect(host=hgm_www_host,port=hgm_www_port,user=hgm_www_user,passwd=hgm_www_password,db=hgm_www_db)
            cHandler = myDB.cursor()

            #filter_by_day

            sql = "SELECT products.virtuemart_order_item_id, products.virtuemart_product_id, " + \
                "products.order_item_sku, LEFT (products.order_item_name, 256), " + \
                "products.product_quantity, products.order_status, products.packed_qt, products.created_on, " + \
                "products.product_priceWithoutTax, products.product_tax, products.product_subtotal_with_tax, image.file_url_thumb, " + \
                "products.product_attribute " + \
                "FROM emk8r_virtuemart_order_items AS products " + \
                "LEFT JOIN emk8r_virtuemart_product_medias AS medias " + \
                "ON products.virtuemart_product_id=medias.virtuemart_product_id "+ \
                "LEFT JOIN emk8r_virtuemart_medias AS image " + \
                "ON medias.virtuemart_media_id=image.virtuemart_media_id "+ \
                "WHERE virtuemart_order_id='" + virtuemart_order_id + "' " + \
                "ORDER BY created_on ASC "

            #logger.info(sql)
            cHandler.execute(sql)

            results = cHandler.fetchall()
            products_len = len(results)
            ready_data_true['total'] = products_len

            all_data = []
            
            if products_len == 0:
                return ready_data_true

            status_options = {'P' : 'Pending', 'U' : 'Confirmed By Shopper',  'C' : 'Confirmed By HGM', \
                                'X' : 'Canceled', 'R' : 'Refunded', 'S' : 'Shipped', 'O' : 'Out Of Stock','A' : 'Packed'}
            for result in results:
                try:
                    data = {}
                    data['id']                          = result[0]
                    data['virtuemart_order_item_id']    = result[0]
                    data['virtuemart_product_id']       = result[1]
                    data['order_item_sku']              = result[2]
                    data['order_item_name']             = result[3]
                    data['product_quantity']            = result[4]
                    data['order_status']                = status_options[result[5]]
                    data['packed_qt']                   = result[6]
                    order_date_time = timestring.Date(result[7])
                    order_date_time = order_date_time - '5 hour'
                    data['created_on']                  = str(order_date_time)
                    data['product_priceWithoutTax']     = result[8]
                    data['product_tax']                 = result[9]
                    data['product_subtotal_with_tax']   = result[10]
                    data['image_url']                   = "http://www.hudsongreenemarket.com/" + str(result[11])

                    try:
                        item = Item.objects.get(upc_2=data['order_item_sku'], user=currentProfile.parent_user)
                        data['upc']             = item.upc
                        #data['image_url']       = item.image_url
                        data['bo_item_id']      = str(item.id)
                        data['qt_in_stock']     = item.qt_in_stock
                        data['loc_ret_dept']    = item.loc_ret_dept
                        if data['image_url'] == "http://www.hudsongreenemarket.com/" or data['image_url'] == "" or data['image_url'] == None:
                            data['image_url'] = item.image_url
                        
                    except ObjectDoesNotExist:
                        logger.error("UPC_2 DOESNT match for WWW : " + str(data['order_item_sku']))

                    # Tossing Salad logic
                    if result[1] == 6242:
                        #logger.info('This is Toss Salad')

                        sql = "SELECT virtuemart_customfield_id, customfield_value from emk8r_virtuemart_product_customfields " + \
                            "where virtuemart_product_id=6242 " + \
                            "ORDER BY virtuemart_customfield_id ASC; "

                        #logger.info(sql)
                        cHandler.execute(sql)
                        toss_salad_custom_fields_names = cHandler.fetchall()
                        #logger.info(toss_salad_custom_fields_names)
                        #return
                        #{
                        #    "56": "17988",
                        #    "57": "18007",
                        #    "61": "18078",
                        #    "62": "18131",
                        #    "63": "18185",
                        #    "64": "18239",
                        #    "60": "18292",
                        #    "70": {
                        #        "18312": "11:15 Am"
                        #    },
                        #    "71": "18313",
                        #    "65": "18608",
                        #    "66": "18662",
                        #    "67": "18833",
                        #    "42": {
                        #        "18903": {
                        #            "comment": ""
                        #        }
                        #    }
                        #}
                        
                        fields_dictionary = dict((x, y) for x, y in toss_salad_custom_fields_names)

                        custom_fields_data = simplejson.loads(result[12])
                        custom_fields_attrs = self.flatten_dict(custom_fields_data)
                        #logger.info("custom_fields_attrs: %s" % custom_fields_attrs)

                        a1=a2=a3=a4=a5=a6=a7=a8=a9=a10=a11=a12=a13=''
                        msg_cust_fields = ''
                        for attr in custom_fields_attrs:
                            if attr == '70':
                                field_name = 'Pick Up Time: '
                                field_value = custom_fields_attrs[attr]['18312']
                                a1 = field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '56':
                                field_name = 'Salad Leaves: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                a2 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '57':
                                field_name = 'Topping 1: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One':
                                    a3 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '61':
                                field_name = 'Topping 2: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One':
                                    a4 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '62':
                                field_name = 'Topping 3: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One':
                                    a5 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '63':
                                field_name = 'Topping 4: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One':
                                    a6 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '64':
                                field_name = 'Topping 5: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One':
                                    a7 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '65':
                                field_name = 'Topping 6: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One ($)':
                                    a8 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '66':
                                field_name = 'Topping 7: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One ($)':
                                    a9 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '67':
                                field_name = 'Topping 8: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One ($)':
                                    a10 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '60':
                                field_name = 'Dressing: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'Select One':
                                    a11 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            elif attr == '71':
                                field_name = 'Chopped: '
                                field_value = fields_dictionary[int(custom_fields_attrs[attr])]
                                if field_value != 'No':
                                    a12 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))
                            if attr == '42':
                                field_name = 'Notes: '
                                field_value = custom_fields_attrs[attr]['18903']['comment']
                                if field_value != '':
                                    a13 =  field_name + '<b>' + field_value + '</b>' + '<br>'
                                #logger.info("field_name: %s, field_value: %s" % (field_name, field_value))

                        msg_cust_fields = a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12+a13
                        data['custom_fields']      = msg_cust_fields
                        #logger.info("msg_cust_fields: %s" % msg_cust_fields)


                    all_data.append(data)
                except Exception, err:
                    logger.error(err)
                    ready_data_false["error"] = str(err)
                    return ready_data_false
                    
            ready_data_true['items'] = all_data
            ready_data_true['total'] = len(all_data)
            #logger.info(all_data)
            return ready_data_true
Пример #37
0
    def update(self, request, id=None):

        ready_data_true =  {'success': True }
        ready_data_false = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        if id:
            try:
                currentProfile = Profile.getProfile(request.user)
                hgm_www_host = settings.HGM_WWW_HOST
                hgm_www_port = settings.HGM_WWW_PORT
                hgm_www_user = settings.HGM_WWW_USER
                hgm_www_password = settings.HGM_WWW_PASSWORD
                hgm_www_db = settings.HGM_WWW_DB

                 # CONNECTION TO www.hudsongreenemarket.com 52.0.0.79
                myDB = MySQLdb.connect(host=hgm_www_host,port=hgm_www_port,user=hgm_www_user,passwd=hgm_www_password,db=hgm_www_db)
                cHandler = myDB.cursor()


                item_id = None
                ext_posted_data = simplejson.loads(request.POST.get('items'))
                attrs = self.flatten_dict(ext_posted_data)

                try:
                    del attrs['id']
                except KeyError:
                    pass

                packed_statement = ''
                if 'packed_qt' in attrs:
                    packed_statement = "SET packed_qt='" + str(attrs['packed_qt']) + "'"

                order_status_statement = ''
                if 'order_status' in attrs and attrs['order_status'] == 'Packed':
                    order_status_statement = ", order_status='A'"  # Packed



                sql = "UPDATE emk8r_virtuemart_order_items " + \
                    packed_statement + order_status_statement + \
                    " WHERE virtuemart_order_item_id='" + str(id) + "';"
                cHandler.execute(sql)
                myDB.commit()

                # EVERY TIME packed_qt has changed NEED TO DEPLETE INVENTORY IN BO
                try:
                    if 'bo_item_id' in attrs:
                        bo_item_id = str(attrs['bo_item_id'])
                        item = Item.objects.get(id=bo_item_id, user=currentProfile.parent_user)

                        if item.inventory_no_count == False: # if no_count True, do not change qt_in_stock
                            qt_in_stock = float(item.qt_in_stock) - float(1)
                            if qt_in_stock < 0:
                                qt_in_stock = 0
                            item.qt_in_stock = str("%.2f" % qt_in_stock)
                            item.save()

                            if settings.HGM == True: # UPDATE qt_in_stock in WWW
                                updateWwwQtInStock(item)
                                
                except ObjectDoesNotExist:
                    raise Exception (u"Item is not found")

                ready_data_true['total'] = 1
                return ready_data_true

            except Exception, err:
                ready_data_false['errors'] = str(err)
                return ready_data_false
Пример #38
0
    def create(self, request):
        ready_data_true     =  {'success': True }
        ready_data_false    = {'success': False}

        if not request.user.is_authenticated():
            ready_data_false["error"] = "Authorization is failed"
            return ready_data_false

        try:
            item_id         = request.POST.get('item_id')
            product_id      = request.POST.get('product_id')
            user            = request.user
            currentProfile  = Profile.getProfile(request.user)
            items           = request.POST.get('items')

            # 1. product and item are given in request, need to create Order from product
            if product_id:
                product = Product.objects.get(pk=product_id)
                item = Item.objects.get(pk=item_id)

                itemproduct = ItemProduct.objects.create(  \
                    product_num     = product.product_num,    \
                    vendor          = product.vendor,        \
                    upc             = product.upc,   \
                    category        = product.category,      \
                    name1           = product.name1,         \
                    name2           = product.name2,         \
                    package         = product.package,       \
                    date_modified   = product.date_modified, \
                    price           = product.price,         \
                    brand           = product.brand,          \
                    ispriceperunit  = product.ispriceperunit, \
                    notes           = product.notes, \
                    price_per_unit  = 0, \
                    user            = currentProfile.parent_user)

                try:
                    Order.objects.get(item=item, product=itemproduct, user=currentProfile.parent_user)
                except:
                    order = Order.objects.create(item=item, product=itemproduct, user=currentProfile.parent_user)
                    updateBestPriced(None, None, item_id)
                    ready_data_true['items'] = order.list()
                    ready_data_true['total'] = 1
                    return ready_data_true
                else:
                    # normally must be False, but this is not actual error, so it's OK
                    return ready_data_true


                ready_data_false['itemproduct'] = itemproduct
                return ready_data_false

            # 2. fields are given in request to create an Order
            elif items:

                # These fields could be used to create Order
                #
                # "item_id": "1713",                                                Order               Required
                # "product_num": "100065",                                          ItemProduct         Required
                # "name1": "Foie Gras, Duck Ref Millefeuille Appetizer",             ItemProduct.name1   Required
                # "vendor_id": "89",                                                ItemProduct         Required
                # "price": "",                                                      ItemProduct
                # "category": "",                                                   ItemProduct
                # "total_units_per_package": "",                                    ItemProduct
                # "ispriceperunit": false,                                          ItemProduct
                # "package_pack": "",                                               ItemProduct.package
                # "notes": "",                                                      ItemProduct
                # "brand": "Food Innovations Bb",                                   ItemProduct
                # "upc": "",                                                        ItemProduct
                # "preferred": false                                                Order

                ext_posted_data = simplejson.loads(request.POST.get('items'))
                attrs = self.flatten_dict(ext_posted_data)

                data = {}
                ready_data_false['data'] = data

                if 'ispriceperunit' not in attrs:
                    data['ispriceperunit']=False
                else:
                    data['ispriceperunit']=attrs['ispriceperunit']

                if 'preferred' not in attrs:
                    preferred=False
                else:
                    preferred=attrs['preferred']

                data['product_num']=attrs['product_num']
                data['upc']=replace(attrs['upc'])
                data['name1']=replace(attrs['name1'])
                data['name2']=replace(attrs['name2'])
                data['vendor_id']=attrs['vendor_id']
                data['date_modified']= datetime.now()

                data['price'] = Decimal(str(attrs['price']))
                if data['price'] == '': data['price'] = '0'
                data['total_units_per_package']=str(attrs['total_units_per_package'])
                if data['total_units_per_package'] == '': data['total_units_per_package'] = str(0)

                data['package']=replace(attrs['package'])
                data['brand']=replace(attrs['brand'])
                data['category']=replace(attrs['category'])
                data['notes']=replace(attrs['notes'])

                # RE: price_per_unit, update it when price or total_units_per_package or ispriceperunit are updated
                if not data['ispriceperunit']:
                    if data['price'] and data['total_units_per_package'] is not '0':
                        pricePerUnit = float(data['price'])/float(data['total_units_per_package'])
                        p_u      = str('%.3f' % (pricePerUnit,))
                    else:
                        p_u      = '0'
                else:
                    if data['price'] and data['total_units_per_package'] is not '0':
                        p_u      = data['price']
                    else:
                        p_u      = '0'

                data['price_per_unit'] = p_u

                if logger.isEnabledFor(logging.DEBUG):
                    logger.debug('data: %s' % (data))
                itemproduct = ItemProduct.objects.create(user=currentProfile.parent_user, **data)

                item = Item.objects.get(pk=item_id)

                # need to avoid to have duplicate itemproducts
                # let's get all orders for current item
                # then compare
                orders = Order.objects.filter(item=item, user=currentProfile.parent_user)
                ready_data_false['orders'] = orders
                for order in orders:
                    if order.product.product_num == attrs['product_num'] and order.product.vendor_id == attrs['vendor_id']:
                        ready_data_true['items'] = order.list()
                        return ready_data_true

                # there is no identical order, so let's create one
                order = Order.objects.create(item=item, product=itemproduct, preferred=preferred, user=currentProfile.parent_user)
                updateBestPriced(None, None, item_id)
                ready_data_true['items']=order.list()
                ready_data_true['total']=1
                return ready_data_true

            return ready_data_false

        except Exception, err:
            ready_data_false['errors'] = err.message
            if logger.isEnabledFor(logging.ERROR):
                logger.error('%s' % (err))
                logger.error('%s' % (traceback.format_exc()))
                logger.error('User: %s' % (request.user))
                logger.error('Items: %s' % (items))

            return ready_data_false