Exemple #1
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)
Exemple #2
0
def get_transaction(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    start_time = request.GET['start_time']
    end_time = request.GET['end_time']

    if str(start_time) == '*':
        transactions = list(
            Transaction.objects.filter(
                boss=current_boss).order_by('-date').values())
        start_time = '*'
        end_time = '*'
    else:
        transactions = list(
            Transaction.objects.filter(
                boss=current_boss,
                date__range=(start_time, end_time)).order_by('-date').values())
        start_time = time.strftime('%b %#d, %Y %#I:%M%p',
                                   time.localtime(int(start_time)))
        end_time = time.strftime('%b %#d, %Y %#I:%M%p',
                                 time.localtime(int(end_time)))

    # ADD DATE TO TRANSACTION ITEMS & CALCULATE TOTAL
    total_data = transaction_total(transactions)

    return JsonResponse(
        {
            'store': {
                'transactions': transactions
            },
            'total': total_data['total'],
            'start_time': start_time,
            'end_time': end_time
        },
        safe=False)
Exemple #3
0
def link_columns(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    column = request.POST['column']
    link_type = request.POST['link_type']
    store = Store.objects.get(id=request.POST['id'])
    store_inventory = store.inventory

    if link_type not in store.link_columns:
        return HttpResponseBadRequest('Link type does not exist.',
                                      'application/json')

    store.link_columns[link_type] = column.strip()

    if link_type == 'price' or link_type == 'cost':  # Turn all data to float values
        for item_id, item in store_inventory.iteritems():
            current_price = item[column]
            if current_price.replace('.', '', 1).isdigit():
                item[column] = decimal_format(float(current_price), 2, False)
            else:
                item[column] = '0.00'

    elif link_type == 'quantity':  # Turn all data to int values
        for key, item in store_inventory.iteritems():
            current_quantity = item[column]
            if str(current_quantity).isdigit():
                item[column] = int(current_quantity)
            else:
                item[column] = 0

    store.save()
    store.inventory = sort_inventory(store, store.inventory)

    return JsonResponse({'store': model_to_dict(store)}, safe=False)
Exemple #4
0
def overview_page(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_settings = model_to_dict(current_boss.settings)
    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

    data = {
        'base_url': get_base_url(),
        'business_id': user_business.id,
        'business_name': user_business.name,
        'stores': json.dumps(store_dict),
        'date_range': user_settings['date_range'],
        'start_point': user_settings['start_time']
    }

    return render(request, 'overview.html', data)
Exemple #5
0
def save_settings(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    user_settings = current_boss.settings

    settings = request.BODY["settings"]
    stores = request.BODY["stores"]

    for key, store in stores.iteritems():
        current_store = Store.objects.get(id=key)
        current_store.tax = store['tax']
        current_store.transaction_filter = store['filter']
        current_store.save()

    user_settings.date_range = settings['date_range']
    user_settings.start_time = settings['start_time']

    user_settings.save()

    return JsonResponse(
        {
            'stores': stores,
            'settings': model_to_dict(user_settings)
        },
        safe=False)
Exemple #6
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('Store name is an empty string.', 'application/json')

    user_stores = business.stores.all()

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

    store = Store.objects.create(name=request.POST['store_name'])
    # ADD TO BUSINESS STORE LIST
    business.stores.add(store)
    store.link_columns = {"quantity": False, "price": False, "cost": False, 'name': False}
    store.columns = []
    store.transaction_filter = ['ALL']
    store.save()

    return JsonResponse(model_to_dict(store), safe=False)
Exemple #7
0
def get_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)
Exemple #8
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)
    if current_user.boss:
        boss_username = current_user.username
    else:
        boss_username = User.objects.get(
            boss=current_user.employee.boss).username

    user_business = current_boss.business
    stores = user_business.stores.all().values()
    store_log = {}
    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[store_id] = list(
            ItemLog.objects.filter(store=store_id).order_by('-date').values(
                'user__first_name', 'user__last_name', 'action', 'operation',
                'item_name', 'change', 'previous_value', 'date', 'details',
                'id'))

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

    return render(request, 'inventory.html', data)
Exemple #9
0
def settings(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    establishment = current_boss.business

    return JsonResponse(
        {
            'link_columns': establishment.link_columns,
            'columns': establishment.columns['columns'],
            'name': establishment.name
        },
        safe=False)
Exemple #10
0
def edit_column(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    store = Store.objects.get(id=request.POST['id'])

    prev_column_name = request.POST['prev_column_name']
    new_column_name = request.POST['new_column_name']
    columns = store.columns
    items = store.inventory
    linked_columns = store.link_columns

    if prev_column_name not in columns:
        return HttpResponseBadRequest('Column name does not exist.', 'application/json')

    if new_column_name == '':
        return HttpResponseBadRequest('Column name is an empty string.', 'application/json')

    # Edit column list
    store.columns = [w.replace(prev_column_name, new_column_name) for w in columns]

    # Edit inventory
    for key, item in items.iteritems():
        item[new_column_name] = item.pop(prev_column_name)

    # Check link columns
    for key, item in linked_columns.iteritems():
        if linked_columns[key] == prev_column_name:
            linked_columns[key] = new_column_name

    # Check name link column
    name_regex = linked_columns['name']
    if name_regex:
        linked_columns['name'] = name_regex.replace('{{' + prev_column_name + '}}', '{{' + new_column_name + '}}')

    user_settings = current_boss.settings

    # Check transaction filters
    store.transaction_filter = [w.replace(prev_column_name, new_column_name) for w in columns]

    if prev_column_name == store.order_by:
        store.order_by = new_column_name

    store.save()
    user_settings.save()

    user_types = UserType.objects.filter(boss=current_boss)
    for user_type in user_types:
        permission = user_type.permission
        permission.save()

    store.inventory = sort_inventory(store, store.inventory)

    return JsonResponse({'columns': store.columns, 'store': model_to_dict(store)}, safe=False)
Exemple #11
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)
Exemple #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)

    return JsonResponse(
        {
            'transaction': model_to_dict(transaction),
            'success': True
        },
        safe=False)
Exemple #13
0
def store(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    user_business = current_boss.business

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

    data = {
        'business_id': user_business.id,
        'business_name': user_business.name,
        'stores': list(user_business.stores.all().values())
    }

    return render(request, 'store.html', data)
Exemple #14
0
def get_item_log(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    user_business = current_boss.business

    start_time = request.GET['start_time']
    end_time = request.GET['end_time']

    item_log = list(ItemLog.objects.filter(business=user_business, date__range=(start_time, end_time)).order_by('-date')
                    .values('user__first_name', 'user__last_name', 'action', 'operation', 'item_name', 'change',
                    'previous_value', 'date', 'details', 'id'))

    return JsonResponse({
        'item_log': item_log,
        'start_time': time.strftime('%b %#d, %Y %#I:%M%p', time.localtime(int(start_time))),
        'end_time': time.strftime('%b %#d, %Y %#I:%M%p', time.localtime(int(end_time))),
    }, safe=False)
Exemple #15
0
def delete_column(request):
    current_user = request.user
    current_boss = get_boss(current_user)
    store = Store.objects.get(id=request.POST['id'])

    column_name = request.POST['column_name']
    columns = store.columns
    items = store.inventory
    linked_columns = store.link_columns

    if column_name == '':
        return HttpResponseBadRequest('Column name is an empty string.', 'application/json')

    if column_name not in columns:
        return HttpResponseBadRequest('Column name does not exist.', 'application/json')
    
    # Remove column from list
    columns.remove(column_name)

    # Delete column from inventory
    for key, item in items.iteritems():
        item.pop(column_name, None)

    # Check link columns
    for key, item in linked_columns.iteritems():
        if linked_columns[key] == column_name:
            linked_columns[key] = False

    user_settings = current_boss.settings
    transaction_filter = store.transaction_filter

    if column_name == store.order_by:
        store.order_by = "none"

    # Check transaction filter
    if column_name in transaction_filter:
        transaction_filter.remove(column_name)

    store.save()
    user_settings.save()

    store.inventory = sort_inventory(store, store.inventory)

    return JsonResponse({'store': model_to_dict(store)}, safe=False)
Exemple #16
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_business = current_boss.business
    user_types = list(UserType.objects.filter(boss=current_boss).values())
    employees = Employee.objects.filter(
        boss=current_boss).order_by('-user_type')
    stores = user_business.stores.all().values()

    employees_list = []

    for current_employee in employees:
        employee_user = User.objects.get(employee=current_employee.id)
        name = employee_user.first_name + ' ' + employee_user.last_name
        employees_list.append({
            'name': name,
            'title': current_employee.user_type.name,
            'username': employee_user.username,
            'store': employee_user.employee.store
        })

    store_dict = {}

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

    data = {
        'base_url': get_base_url(),
        'name': current_user.first_name + " " + current_user.last_name,
        'user_type_list': user_types,
        'user_types': json.dumps(user_types),
        'employee_list': employees_list,
        'employees': json.dumps(employees_list),
        'stores': json.dumps(store_dict)
    }

    return render(request, 'employee.html', data)
Exemple #17
0
def create_user_type(request):
    current_user = request.user
    current_boss = get_boss(current_user)

    post_permissions = request.BODY['permissions']
    name = request.BODY['name'].strip()

    if name == "":
        return HttpResponseBadRequest('Column name does not exist.',
                                      'application/json')

    permissions = Permission.objects.create(
        add_column=post_permissions['add_column'],
        edit_column=post_permissions['edit_column'],
        delete_column=post_permissions['delete_column'],
        add_item=post_permissions['add_item'],
        edit_item=post_permissions['edit_item'],
        delete_item=post_permissions['delete_item'],
        import_file=post_permissions['import'],
        export_file=post_permissions['export'],
        drop_table=post_permissions['drop_table'],
        receive=post_permissions['receive'],
        damage=post_permissions['damage'],
        reset_cost=post_permissions['reset_cost'],
        reset_price=post_permissions['reset_price'],
        create_store=post_permissions['create_store'],
        edit_store=post_permissions['edit_store'],
        delete_store=post_permissions['delete_store'],
        create_transaction=post_permissions['create_transaction'],
        edit_transaction_settings=post_permissions[
            'edit_transaction_settings'],
        create_user=post_permissions['create_user'],
        create_user_type=post_permissions['create_user_type'],
        delete_user_type=post_permissions['delete_user_type'],
        edit_permissions=post_permissions['edit_permissions'])

    user_type = UserType.objects.create(name=name,
                                        permission=permissions,
                                        boss=current_boss)

    return JsonResponse(model_to_dict(user_type), safe=False)
Exemple #18
0
def transaction(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_settings = model_to_dict(current_boss.settings)
    user_business = current_boss.business
    # user_settings['business_tax'] = decimal_format(float(user_business.tax)*100, 3, False)
    user_settings['ip_address'] = user_settings['ip_address'].split('.')
    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'] = []

    data = {
        'base_url': get_base_url(),
        'name': current_user.first_name + " " + current_user.last_name,
        'business_id': user_business.id,
        'business_name': user_business.name,
        'stores': json.dumps(store_dict),
        'start_point': user_settings['start_time'],
        'date_range': user_settings['date_range'],
        'settings': json.dumps(user_settings),
        'all': 'ALL'
    }

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

    return render(request, 'transaction.html', data)
Exemple #19
0
def inventory_operation(request, action, operation, link_column,
                        callback_function):
    current_user = request.user
    current_boss = get_boss(current_user)
    store = Store.objects.get(id=request.POST['id'])
    linked_columns = store.link_columns

    changing_column = linked_columns[link_column]
    name_column = linked_columns['name']
    item = store.inventory[request.POST['item_id']]
    previous_value = item[changing_column]

    # Do operation
    item[changing_column] = callback_function(item[changing_column],
                                              request.POST['change_value'])

    store.save()

    created_item_log = ItemLog.objects.create(
        user=current_user,
        action=action,
        operation=operation,
        item_name=transaction_name_regex(name_column, item),
        change=request.POST['change_value'],
        previous_value=previous_value,
        details={"notes": request.POST['details']})

    created_item_log.store = store
    created_item_log.save()
    item_logs = list(
        ItemLog.objects.filter(store=store).order_by('-date').values(
            'user__first_name', 'user__last_name', 'action', 'operation',
            'item_name', 'change', 'previous_value', 'date', 'details', 'id'))

    store.inventory = sort_inventory(store, store.inventory)

    return {'store': model_to_dict(store), 'item_log': item_logs}
Exemple #20
0
def create_employee(request):
    current_user = request.user
    current_boss = get_boss(current_user)

    username = request.POST['username'].strip().lower()
    password = request.POST['password']
    first_name = request.POST['first_name']
    last_name = request.POST['last_name']
    user_type = request.POST['user_type']
    connection = request.POST['connection']
    store = request.POST['store']

    # Check first name
    if not len(first_name):
        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):
        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:
        data = {
            'success': False,
            'error_msg': 'Username must be between 3 to 15 characters.'
        }
        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')

    chosen_user_type = UserType.objects.get(id=user_type)

    created_employee = Employee.objects.create(
        boss=current_boss,
        connection=connection,
        permission=chosen_user_type.permission,
        user_type=chosen_user_type)

    if store != '':
        created_employee.store = Store.objects.get(id=store)
        created_employee.save()

    created_user = User.objects.create(
        username=username,
        password=helper.create_password(password),
        first_name=first_name,
        last_name=last_name,
        employee=created_employee)

    # Validate password
    authenticate(username=username, password=password)

    return JsonResponse(model_to_dict(created_user), safe=False)