def manage_transaction(request, transaction_type = None):
	"""
	Manage the transactions depending on HTTP method
	GET:
	DELETE:
	PUT:
	POST:
	:param request: HTTP request
	:param transaction_type: transaction type income|expense|transfer
	:return: ServerResponse instance
	"""
	field_name = 'transaction'

	if request.is_GET:
		return ServerResponse.ok()

	if request.is_DELETE:
		pass

	if request.is_PUT:
		pass

	if request.is_POST:
		if not transaction_type:
			return ServerResponse.bad_request(message = Message.error('Transaction type is not defined'))

		transaction = Transaction.create(transaction_type)
		transaction.set_data(status_id = TransactionStatus.objects.get_success_status().guid, user_id = request.user.pk, **request.data)

		try:
			transaction.full_clean()
			transaction.save()

		except ValidationError as e:
			message = {}
			if 'expense_items' in e.message_dict.keys():
				message = Message.error(e.message_dict.get('expense_items')[0])

			return ServerResponse.bad_request(message = message, data = e.message_dict)

		except TransactionSaveError as e:
			return ServerResponse.internal_server_error(message = Message.error(e.message))

		transaction.model.create_register_record()

		return ServerResponse.created(
			data = {field_name: transaction.model.__class__.objects.get(guid = transaction.model.guid).serialize()}
		)
Esempio n. 2
0
def search(request):
	"""
	Search engine
	:param request:
	GET:
		required query params:
			:parameter type: type of object to search instance
			:parameter q: search query
	:return:
	"""
	obj_type = request.get_params.get('type', None)
	q = request.get_params.get('q', None)

	if not obj_type or not q:
		return ServerResponse.bad_request(message = Message.error('Required params are not defined'))

	search_engine = SearchEngine()
	search_engine.obj_type = obj_type

	instances = search_engine.search(q, user = request.user)

	return ServerResponse.ok(data = {
		'type': search_engine.model.__name__,
		'q': q,
		'instances': [i.serialize() for i in instances]
	})
def manage_po_register(request, guid):
	"""
	Manage the payment objects register on HTTP method
	GET:
	:param request: HTTP request
	:param guid: payment object guid
	:return: ServerResponse instance
	"""
	field_name = 'register'

	try:
		payment_object = request.user.paymentobject_set.get(guid=guid)
	except ObjectDoesNotExist as e:
		return ServerResponse.not_found(message=Message.error('The object {guid} is\'n found'.format(guid=guid)))

	last = request.get_params.get('last', False)

	if last:
		register_record = payment_object.get_last_register_record()
		return ServerResponse.ok({field_name: register_record.serialize() if register_record else {}})

	else:
		register_records = payment_object.get_aggregated_by_days_register_records()

		return ServerResponse.ok({field_name + 's': [record._asdict() for record in register_records]})
def manage_po_transaction(request, guid):
	"""
	Gets po associated transactions
	:param request:
	:param guid: po guid
	:return:
	"""
	try:
		payment_object = request.user.paymentobject_set.get(guid=guid)
	except ObjectDoesNotExist as e:
		return ServerResponse.not_found(message=Message.error('The object {guid} is\'n found'.format(guid=guid)))

	transaction_type = request.get_params.get('type', 'income,expense')
	count = request.get_params.get('count', None)
	aggregation = request.get_params.get('aggregation', None)

	if not aggregation:
		income_transactions = []
		expense_transactions = []

		if 'income' in transaction_type:
			income_transactions = IncomeTransaction.objects.get_po_associated(payment_object)

		if 'expense' in transaction_type:
			expense_transactions = ExpenseTransaction.objects.get_po_associated(payment_object)

		transactions = sorted(chain(income_transactions, expense_transactions), key = lambda x: x.date)[::-1]

		if count:
			transactions = transactions[:int(count):]

		return ServerResponse.ok(data={'transactions': [t.serialize() for t in transactions]})

	else:
		transaction_type = transaction_type.split(',')[0]

		transactions = []
		if 'income' in transaction_type:
			transactions = IncomeTransaction.objects.get_aggregated_by_days(payment_object)

		if 'expense' in transaction_type:
			transactions = ExpenseTransaction.objects.get_aggregated_by_days(payment_object)

		if count:
			transactions = transactions[:int(count):]

		return ServerResponse.ok(data={'transactions': [t._asdict() for t in transactions]})
def manage_expense_item_register(request, guid):
	"""
	Manage the expense items register on HTTP method
	GET:
	:param request: HTTP request
	:param guid: expense item guid
	:return: ServerResponse instance
	"""
	field_name = 'register'

	try:
		expense_item = request.user.expenseitem_set.get(guid=guid)
	except ObjectDoesNotExist as e:
		return ServerResponse.not_found(message=Message.error('The object {guid} is\'n found'.format(guid=guid)))

	last = request.get_params.get('last', False)

	if last:
		register_record = expense_item.get_last_register_record()
		return ServerResponse.ok({field_name: register_record.serialize() if register_record else {}})

	else:
		raise NotImplementedError('Not implemented yet')
Esempio n. 6
0
def manage_supplier(request, guid = None):
	"""
	Manage Supplier api method
	:param request: Http request
	GET:
	PUT:
	POST:
	:param guid:
	:return:
	"""
	field_name = 'supplier'

	if request.is_GET:

		if guid:
			try:
				supplier = request.user.supplier_set.get(guid = guid)
			except ObjectDoesNotExist as e:
				return ServerResponse.not_found(message = Message.error('The object {guid} is\'n found'.format(guid = guid)))

			return ServerResponse.ok(data = {field_name: supplier.serialize()})
		else:
			count = request.get_params.get('count', None)

			suppliers = Supplier.objects.filter(owner_id = request.user.pk).order_by('-creation_datetime')

			if count:
				suppliers = suppliers[:count:]

			return ServerResponse.ok(data = {field_name: [s.serialize() for s in suppliers]})

	if request.is_PUT:
		supplier_guid = request.data.get('guid', None)

		if not supplier_guid:
			return ServerResponse.bad_request(message = Message.error('Guid is not defined'))

		try:
			supplier = Supplier.objects.get(guid = supplier_guid, owner = request.user)
			supplier.update(request.data)
			supplier.save()
		except ObjectDoesNotExist as e:
			return ServerResponse.not_found(message = Message.error('The object {guid} is\'n found'.format(guid = supplier_guid)))

		except Exception as e:
			return ServerResponse.internal_server_error(message = Message.error('The error was occured during saving process'))

		return ServerResponse.ok(data = {field_name: supplier.serialize()})

	if request.is_POST:
		form = SupplierForm(request.data)

		if form.errors:
			return ServerResponse.bad_request(data = form.errors)

		supplier = Supplier(
			name = request.data.get('name'),
			description = request.data.get('description'),
			owner = request.user
		)

		try:
			supplier.save()
		except Exception as e:
			return ServerResponse.internal_server_error(message = Message.error('The error was occured during saving process'))

		return ServerResponse.created(data = {field_name: supplier.serialize()})
Esempio n. 7
0
def manage_category(request, guid=None):
    """
	Manage category
	:param request: HttpRequest
	GET:
		'/api/cmn/category/' - get all roots
		'/api/cmn/category/?subs=true' - get all roots
		'/api/cmn/category/{guid}/' - get category by guid
		'/api/cmn/category/{guid}/?subs=true' - get category with subs
	:return: ServerResponse
	"""
    field_name = "category"

    if request.is_GET:
        subs_field_name = "subs"
        parent_field_name = "parent"

        if guid:
            try:
                category = Category.objects.get(guid=guid, owner_id=request.user.pk)
            except ObjectDoesNotExist as e:
                return ServerResponse.not_found()

            result = {field_name: category.serialize()}

            if request.request.GET.get(subs_field_name, False):
                result[field_name][subs_field_name] = [s.serialize() for s in category.get_subs()]

            if request.request.GET.get(parent_field_name, False):
                parent_category = category.get_parent()

                result[field_name][parent_field_name] = parent_category.serialize() if parent_category else None

            return ServerResponse.ok(data=result)

        else:
            categories = Category.objects.get_roots(owner_id=request.user.pk)
            return ServerResponse.ok(data={field_name: {subs_field_name: [c.serialize() for c in categories]}})

    if request.is_PUT:
        form = CategoryForm(request.data)

        if form.errors:
            return ServerResponse.bad_request(data=form.errors)

        category_guid = request.data.get("guid", None)

        if not category_guid:
            return ServerResponse.bad_request(message=Message.error("Guid is not defined"))

        try:
            category = Category.objects.get(guid=category_guid, owner_id=request.user.pk)
            category.update(request.data)
            category.save()
        except ObjectDoesNotExist as e:
            return ServerResponse.not_found()
        except Exception as e:
            return ServerResponse.internal_server_error(
                message=Message.error("The error was occured during saving process")
            )

        return ServerResponse.ok(data={field_name: category.serialize()})

    if request.is_DELETE:
        if not guid:
            return ServerResponse.bad_request(message=Message.error("Guid must be set"))

        try:
            category = Category.objects.get(guid=guid, owner_id=request.user.pk)
        except ObjectDoesNotExist as e:
            return ServerResponse.not_found()

        if category.has_dependencies():
            return ServerResponse.internal_server_error(
                message=Message.warning("Category has dependencies. It cannot be deleted")
            )

        category.delete()
        return ServerResponse.ok(data={field_name: guid})

    if request.is_POST:
        form = CategoryForm(request.data)

        if form.errors:
            return ServerResponse.bad_request(data=form.errors)

        name = request.data.get("name")
        parent_guid = request.data.get("parent_guid", None)
        if parent_guid:
            # create subcategory
            try:
                parent_category = request.user.category_set.get(guid=parent_guid)
            except ObjectDoesNotExist as e:
                return ServerResponse.not_found(message=Message.error("Parent category does not exist"))

            try:
                category = Category.objects.create_sub(name, parent_category)
            except CreationError as e:
                return ServerResponse.internal_server_error(message=Message.error(e.message))

        else:
            # create root level category
            category = Category.objects.create_root(name)

        category.owner = request.user
        category.save()

        return ServerResponse.created(data={field_name: category.serialize()})
Esempio n. 8
0
def manage_po(request, guid=None):
	"""
	Manage the payment objects depending on HTTP method
	GET: return already created PO. if {guid} is defined returns 1 record
	DELETE:
	PUT:
	POST: create new PO
	:param request: HTTP request
	:param guid: payment object guid
	:return: ServerResponse instance
	"""
	field_name = 'po'

	if request.is_GET:
		if guid:
			# Get by guid
			try:
				payment_object = request.user.paymentobject_set.get(guid=guid)
			except ObjectDoesNotExist as e:
				return ServerResponse.not_found(message = Message.error('The object {guid} is\'n found'.format(guid=guid)))

			result = {field_name: payment_object.serialize()}

			return ServerResponse.ok(data=result)
		else:
			# Get all
			result = {field_name: []}
			payment_objects = request.user.paymentobject_set.all()

			for po in payment_objects:
				result[field_name].append(po.serialize())

			return ServerResponse.ok(data=result)

	if request.is_PUT:
		po_guid = request.data.get('guid', None)

		if not po_guid:
			return ServerResponse.bad_request(message = Message.error('Guid is not defined'))

		try:
			po = PaymentObject.objects.get(guid=po_guid)
			po.update(request.data)
			po.save()
		except ObjectDoesNotExist as e:
			return ServerResponse.not_found(message = Message.error('The object {guid} is\'n found'.format(guid=po_guid)))
		except Exception as e:
			return ServerResponse.internal_server_error(message = Message.error('The error was occured during saving process'))

		return ServerResponse.ok(data = {field_name: po.serialize()})

	if request.is_POST:
		form = ManagePOForm(request.data)

		if form.errors:
			return ServerResponse.bad_request(data = form.errors)

		po = PaymentObject(
			name = request.data.get('name'),
			allow_negative = request.data.get('allow_negative', False),
			currency_id = request.data.get('currency_id'),
			primary = request.data.get('primary', False),
			user = request.user,
			type_id = request.data.get('type_id')
		)
		try:
			po.save()
		except Exception as e:
			return ServerResponse.internal_server_error(message = Message.error('The error was occured during saving process'))

		return ServerResponse.created(data = {field_name: po.serialize()})
def manage_expense_item(request, guid = None):
	"""
	Manage Expense Items
	:param request: HttpRequest
	:return: ServerResponse instance
	"""
	field_name = 'expense_item'

	if request.is_GET:

		if guid:
			try:
				expense_item = request.user.expenseitem_set.get(guid = guid)
			except ObjectDoesNotExist as e:
				return ServerResponse.not_found(message = Message.error('The object {guid} is\'n found'.format(guid = guid)))

			return ServerResponse.ok(data = {field_name: expense_item.serialize()})

		else:
			count = request.get_params.get('count', None)

			expense_items = ExpenseItem.objects.filter(owner_id = request.user.pk).order_by('-creation_datetime')

			if count:
				expense_items = expense_items[:count:]

			return ServerResponse.ok(data = {field_name + 's': [item.serialize() for item in expense_items]})

	if request.is_PUT:
		expense_item_guid = request.data.get('guid', None)

		if not expense_item_guid:
			return ServerResponse.bad_request(message = Message.error('Guid is not defined'))

		try:
			expense_item = ExpenseItem.objects.get(guid = expense_item_guid, owner = request.user)
			expense_item.update(request.data)
			expense_item.save()
		except ObjectDoesNotExist as e:
			return ServerResponse.not_found(message = Message.error('The object {guid} is\'n found'.format(guid = expense_item_guid)))

		except Exception as e:
			return ServerResponse.internal_server_error(message = Message.error('The error was occured during saving process'))

		return ServerResponse.ok(data = {field_name: expense_item.serialize()})

	if request.is_POST:
		form = ExpenseItemForm(request.data)

		if form.errors:
			return ServerResponse.bad_request(data = form.errors)

		expense_item = ExpenseItem(
			name = request.data.get('name'),
			description = request.data.get('description'),
			category_id = request.data.get('category_id'),
			measure_id = request.data.get('measure_id'),
			currency_id = request.data.get('currency_id'),
			owner = request.user
		)

		try:
			expense_item.save()
		except Exception as e:
			return ServerResponse.internal_server_error(message = Message.error('The error was occured during saving process'))

		return ServerResponse.created(data = {field_name: expense_item.serialize()})