Exemplo n.º 1
0
def delete_employee(request):
    employee = Employee.objects.get(id=request.POST['employee'])
    user = User.objects.get(employee=employee)
    store = Store.objects.get(id=request.POST['store'])
    boss = get_boss(request.user)

    employee.delete()
    user.delete()

    employees = Employee.objects.filter(boss=boss,
                                        store=store).order_by('-type')
    employees_dict = {}
    store = model_to_dict(store)

    for current_employee in employees:
        employee_user = User.objects.get(employee_id=current_employee.id)
        employee_id = current_employee.id
        employees_dict[employee_id] = {
            'first_name': employee_user.first_name,
            'last_name': employee_user.last_name,
            'type': current_employee.type,
            'username': employee_user.username,
            'email': employee_user.email,
            'id': employee_id
        }

    store['employees'] = employees_dict

    return render_json({'store': store, 'success': True})
Exemplo n.º 2
0
def print_receipt(request):
    current_user = request.user
    current_boss = get_boss(current_user)

    # Print receipt
    receipt_printer(current_boss.settings, request.BODY['transaction'])

    return JsonResponse({'success': True}, safe=False)
Exemplo n.º 3
0
def save_receipt_settings(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    user_settings = current_boss.settings

    user_settings.ip_address = request.BODY['ip_address']
    user_settings.header = request.BODY['header']
    user_settings.footer = request.BODY['footer']

    user_settings.save()

    return JsonResponse({'transaction_settings': model_to_dict(user_settings)}, safe=False)
Exemplo n.º 4
0
def delete_store(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    business = current_boss.business
    user_stores = business.stores.all()
    store_id = request.POST['id']

    store = Store.objects.get(id=store_id)

    # Check if boss owns the store
    if store not in user_stores:
        return HttpResponseBadRequest('Store does not exist.',
                                      'application/json')

    store.delete()

    return JsonResponse({'id': store_id}, safe=False)
Exemplo n.º 5
0
def employee(request):
    current_user = request.user

    # If user is login redirect to overview
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/')

    current_boss = get_boss(current_user)
    user_type = 'boss'
    if not current_user.boss:
        user_type = current_user.employee.type

    user_business = current_boss.business
    stores = user_business.stores.all().values()
    store_dict = {}

    for current_store in stores:
        store_id = str(current_store['id'])
        store_dict[store_id] = current_store
        employees = Employee.objects.filter(boss=current_boss, store=store_id).order_by('-type')
        employees_dict = {}

        for current_employee in employees:
            employee_user = User.objects.get(employee_id=current_employee.id)
            employee_id = current_employee.id
            employees_dict[employee_id] = {'first_name': employee_user.first_name, 'last_name': employee_user.last_name,
            'type': current_employee.type, 'username': employee_user.username, 'email': employee_user.email,
            'id': employee_id}

        store_dict[store_id]['employees'] = employees_dict

    data = {
        'base_url': get_base_url(),
        'name': current_user.first_name + " " + current_user.last_name,
        'stores': json.dumps(store_dict),
        'user_type': user_type,
        'username': current_user.username
    }

    return render(request, 'employee.html', data)
Exemplo n.º 6
0
def edit_store(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    business = current_boss.business

    store_name = request.POST['store_name']

    if store_name == '':
        return HttpResponseBadRequest('This field is required.',
                                      'application/json')

    user_stores = business.stores.all()

    for user_store in user_stores:
        if user_store.name == store_name:
            return HttpResponseBadRequest('Name already exist.',
                                          'application/json')

    store = Store.objects.get(id=request.POST['id'])
    store.name = store_name
    store.save()

    return JsonResponse(model_to_dict(store), safe=False)
Exemplo n.º 7
0
def create_store(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    business = current_boss.business

    store_name = request.POST['store_name']

    if store_name == '':
        return HttpResponseBadRequest('This field is required.',
                                      'application/json')

    user_stores = business.stores.all()

    for user_store in user_stores:
        if user_store.name == store_name:
            return HttpResponseBadRequest('Name already exist.',
                                          'application/json')

    store = Store.objects.create(name=request.POST['store_name'])
    # ADD TO BUSINESS STORE LIST
    business.stores.add(store)

    return JsonResponse(model_to_dict(store), safe=False)
Exemplo n.º 8
0
def drop_table(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    if current_user.boss:
        boss_username = current_user.username
    else:
        boss_username = User.objects.get(
            boss=current_user.employee.boss).username

    store = Store.objects.get(id=request.POST['id'])

    if request.POST['drop_table']:
        # Remove directory
        asset_directory = os.path.abspath(
            os.path.join(os.path.dirname(__file__), '..', '..', 'templates',
                         'bundle', 'assets', 'files'))
        boss_directory = os.path.join(asset_directory, boss_username)
        store_directory = os.path.join(boss_directory, store.name)

        if os.path.exists(store_directory):
            shutil.rmtree(store_directory)

        store.inventory = {}
        store.columns = []
        store.link_columns = {
            "quantity": False,
            "price": False,
            "cost": False,
            "name": False
        }
        store.picture_column = ''
        store.save()

        user_settings = current_boss.settings
        user_settings.save()

        return JsonResponse({'store': model_to_dict(store)}, safe=False)
Exemplo n.º 9
0
def edit_employee(request):
    helper.check_req_data([
        'username', 'email', 'password', 'first_name', 'last_name', 'type',
        'store', 'employee'
    ], request.POST)

    username = request.POST['username'].strip().lower()
    email = request.POST['email'].strip().lower()
    password = request.POST['password']
    first_name = request.POST['first_name']
    last_name = request.POST['last_name']
    user_type = request.POST['type']
    store = Store.objects.get(id=request.POST['store'])
    employee = Employee.objects.get(id=request.POST['employee'])
    boss = get_boss(request.user)

    # Check first name
    if not len(first_name):
        print username
        data = {'success': False, 'error_msg': 'Must have a first name.'}
        return HttpResponseBadRequest(json.dumps(data), 'application/json')

    # Check last name
    if not len(last_name):
        print username
        data = {'success': False, 'error_msg': 'Must have a last name.'}
        return HttpResponseBadRequest(json.dumps(data), 'application/json')

    # Check username
    if len(username) <= 2 or len(username) >= 16:
        print username
        data = {
            'success': False,
            'error_msg': 'Username must be between 3 to 15 characters.'
        }
        return HttpResponseBadRequest(json.dumps(data), 'application/json')

    # Check Email
    if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
        data = {'success': False, 'error_msg': 'Invalid email.'}
        return HttpResponseBadRequest(json.dumps(data), 'application/json')

    # Check if valid password: Must be 8 or more characters and contain a combo of letters and numbers
    if not len(password) >= 8:
        data = {
            'success': False,
            'error_msg': 'Password must be 8 characters or more.'
        }
        return HttpResponseBadRequest(json.dumps(data), 'application/json')

    if not bool(re.search(r'\d', password)) or not bool(
            re.search(r'[a-zA-Z]', password)):
        data = {'success': False, 'error_msg': 'Invalid password.'}
        return HttpResponseBadRequest(json.dumps(data), 'application/json')

    # Check if email exist in the database
    if User.objects.filter(username=username).exists():
        data = {'success': False, 'error_msg': 'Username exists.'}
        return HttpResponseBadRequest(json.dumps(data), 'application/json')

    # Check if email exist in the database
    if User.objects.filter(email=email).exists():
        data = {'success': False, 'error_msg': 'Email exists.'}
        return HttpResponseBadRequest(json.dumps(data), 'application/json')

    employee.type = user_type
    employee.save()

    user = User.objects.get(employee=employee)
    user.username = username
    user.email = email
    user.password = helper.create_password(password)
    user.first_name = first_name
    user.last_name = last_name
    user.save()

    employees = Employee.objects.filter(boss=boss,
                                        store=store).order_by('-type')
    employees_dict = {}
    store = model_to_dict(store)

    for current_employee in employees:
        employee_user = User.objects.get(employee_id=current_employee.id)
        employee_id = current_employee.id
        employees_dict[employee_id] = {
            'first_name': employee_user.first_name,
            'last_name': employee_user.last_name,
            'type': current_employee.type,
            'username': employee_user.username,
            'email': employee_user.email,
            'id': employee_id
        }

    store['employees'] = employees_dict

    return render_json({'store': store, 'success': True})
Exemplo n.º 10
0
def overview(request):
    current_user = request.user

    # If not login go to login page
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login/')

    current_boss = get_boss(current_user)

    user_business = current_boss.business
    # user_settings['business_tax'] = decimal_format(float(user_business.tax)*100, 3, False)
    stores = user_business.stores.all().values()
    store_dict = {}

    for current_store in stores:
        store_id = str(current_store['id'])
        store_dict[store_id] = current_store
        store_dict[store_id]['transactions'] = []
        transactions = models_to_dict(Transaction.objects.filter(store_id=store_id).order_by('-date'))

        ordered_transactions = []
        datetime_holder = ''
        t_dict = None

        for t in transactions:
            item_discount = 0
            current_datetime = epoch_strftime(t['date'], "%A %B %d, %Y")
            epoch_date = time.mktime(time.strptime(current_datetime, "%A %B %d, %Y"))

            # Calculations
            t_tax = round(float(t['tax'])*float(t['subtotal'])*100)/100
            t_total = float(t['subtotal']) + t_tax - float(item_discount)
            # Data: Tax, Discount, Total
            t['timestamp'] = epoch_strftime(t['date'], '%b %#d, %Y %I:%M%p')
            t['tax'] = '{0:.2f}'.format(t_tax)
            t['discount'] = '{0:.2f}'.format(item_discount)
            t['total'] = '{0:.2f}'.format(t_total)

            # Split different dates
            if datetime_holder == current_datetime:
                t_dict['transactions'].append(t)
            else:
                if t_dict is not None:
                    ordered_transactions.append(t_dict)
                t_dict = {'datetime': current_datetime, 'epoch': epoch_date, 'transactions': []}
                datetime_holder = current_datetime
                t_dict['transactions'].append(t)
        # Append the last date
        if t_dict is not None:
            ordered_transactions.append(t_dict)

        store_dict[store_id]['transactions'] = ordered_transactions

    data = {
        'base_url': get_base_url(),
        'name': current_user.first_name + " " + current_user.last_name,
        'username': current_user.username,
        'business_id': user_business.id,
        'business_name': user_business.name,
        'stores': json.dumps(store_dict)
    }

    # if len(user_business.inventory):
    #     user_settings['example_item'] = next(iter(user_business.inventory.items()))[1]

    return render(request, 'overview.html', data)
Exemplo n.º 11
0
def inventory(request):
    current_user = request.user

    # Only go to overview if user is logged in
    if not current_user.is_authenticated():
        return HttpResponseRedirect('/login/')

    current_boss = get_boss(current_user)
    user_type = 'boss'
    if not current_user.boss:
        user_type = current_user.employee.type

    user_business = current_boss.business
    stores = user_business.stores.all().values()
    store_dict = {}

    if len(stores):
        active_store = str(stores.first()['id'])
    else:
        active_store = ''

    for current_store in stores:
        store_id = str(current_store['id'])
        store_dict[store_id] = current_store
        store_inventory = current_store['inventory']

        if current_store['order_by'] != 'none':
            current_store['inventory'] = sorted(store_inventory.items(), key=lambda (k, v): v[current_store['order_by']], reverse=current_store['reverse'])
        else:
            current_store['inventory'] = sorted(store_inventory.items(), key=lambda (k, v): int(k), reverse=False)

        store_log = list(ItemLog.objects.filter(store_id=store_id).order_by('-date').values(
            'user__first_name', 'user__last_name', 'action', 'operation', 'item_name', 'change', 'previous_value',
            'date', 'details', 'id'))

        ordered_logs = []
        datetime_holder = ''
        l_dict = None

        for l in store_log:
            current_datetime = epoch_strftime(l['date'], "%A %B %d, %Y")
            # Data: Tax, Discount, Total
            l['timestamp'] = epoch_strftime(l['date'], '%b %#d, %I:%M%p')

            # Split different dates
            if datetime_holder == current_datetime:
                l_dict['logs'].append(l)
            else:
                if l_dict is not None:
                    ordered_logs.append(l_dict)

                l_dict = {'datetime': current_datetime, 'logs': []}
                datetime_holder = current_datetime
                l_dict['logs'].append(l)

        # Append the last date
        if l_dict is not None:
            ordered_logs.append(l_dict)

        current_store['item_log'] = ordered_logs

    data = {
        'base_url': get_base_url(),
        'business_id': user_business.id,
        'business_name': user_business.name,
        'active_store': active_store,
        'name': current_user.first_name + " " + current_user.last_name,
        'username': current_user.username,
        'stores': json.dumps(store_dict),
        'user_type': user_type
    }

    return render(request, 'inventory.html', data)
Exemplo n.º 12
0
def create_transaction(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    store_id = request.BODY['store_id']
    store = Store.objects.get(id=store_id)
    user_inventory = store.inventory
    quantity_column = store.link_columns['quantity']
    cost_column = store.link_columns['cost']
    transaction_items = request.BODY['items']

    if not len(transaction_items):
        return HttpResponseBadRequest('Must have at least one item per transaction.', 'application/json')

    for key, item in transaction_items.iteritems():
        item['id'] = key
        item['cost'] = user_inventory[key][cost_column]

    item_list = []

    # Subtract from inventory
    for key, item in transaction_items.iteritems():
        inventory_item = user_inventory[key]
        inventory_qty = int(inventory_item[quantity_column])
        transaction_qty = int(item['quantity'])
        inventory_qty -= transaction_qty

        if inventory_qty < 0:
                inventory_qty = 0

        user_inventory[key][quantity_column] = inventory_qty
        item_list.append(item)
        store.save()

    transaction = Transaction.objects.create(
        boss=current_boss,
        seller=current_user,
        store=store,
        payment_type=request.BODY['payment_type'],
        subtotal=request.BODY['subtotal'],
        tax=request.BODY['tax'],
        memo=request.BODY['memo'],
        items=item_list
    )

    transactions = models_to_dict(store.transaction_set.all().order_by('-date'))
    ordered_transactions = []
    datetime_holder = ''
    t_dict = None

    for t in transactions:
        item_discount = 0
        current_datetime = epoch_strftime(t['date'], "%A %B %d, %Y")

        # Calculations
        t_tax = round(float(t['tax'])*float(t['subtotal'])*100)/100
        t_total = float(t['subtotal']) + t_tax - float(item_discount)
        # Data: Tax, Discount, Total
        t['timestamp'] = epoch_strftime(t['date'], '%b %#d, %Y %I:%M%p')
        t['tax'] = '{0:.2f}'.format(t_tax)
        t['discount'] = '{0:.2f}'.format(item_discount)
        t['total'] = '{0:.2f}'.format(t_total)

        # Split different dates
        if datetime_holder == current_datetime:
            t_dict['transactions'].append(t)
        else:
            if t_dict is not None:
                ordered_transactions.append(t_dict)
            t_dict = {'datetime': current_datetime, 'transactions': []}
            datetime_holder = current_datetime
            t_dict['transactions'].append(t)
    # Append the last date
    if t_dict is not None:
        ordered_transactions.append(t_dict)

    return JsonResponse({'transaction': model_to_dict(transaction), 'store_transactions': ordered_transactions, 'success': True}, safe=False)