{ "info": { "author": "Jason Carver", "author_email": "jason@membright.com", "bugtrack_url": null, "classifiers": [ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: Unix", "Programming Language :: Python" ], "description": "Accounts credit tracking for Django\n===========================\n\nAccounts can be used to implement a variety of interesting components, including:\n\n* Giftcards\n* Web accounts\n* Loyalty schemes\n\nBasically anything that involves tracking the movement of funds within a closed\nsystem.\n\nThis package uses [double-entry bookkeeping](http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system)\nwhere every transaction is recorded twice (once for the source and once for the\ndestination). This ensures the books always balance and there is full audit\ntrail of all transactional activity. \n\nIf your project manages money, you should be using a library like this. Your\nfinance people will thank you.\n\nFeatures\n--------\n\n* An account has a credit limit which defaults to zero. Accounts can be set up\n with no credit limit so that they are a 'source' of money within the system.\n At least one account must be set up without a credit limit in order for money\n to move around the system.\n\n* Accounts can have:\n - No users assigned\n - A single \"primary\" user - this is the most common case\n - A set of users assigned\n\n* A user can have multiple accounts\n\n* An account can have a start and end date to allow its usage in a limited time\n window\n\n* Accounts can be categorised\n\nInstallation\n------------\n\nTODO: make available on pypi for pip installation.\n\nYou should set-up a cronjob that calls:\n\n ./manage.py close_expired_accounts\n\nto close any expired accounts and transfer their funds to the 'expired'\naccount.\n\nAPI\n---\n\nCreate account instances using the manager:\n\n``` python\n\nfrom decimal import Decimal\nimport datetime\n\nfrom django.contrib.auth.models import User\n\nfrom accounts import models\n\nanonymous_account = models.Account.objects.create()\n\nbarry = User.objects.get(username=\"barry\")\nuser_account = models.Account.objects.create(primary_user=barry)\n\nno_credit_limit_account = models.Account.objects.create(credit_limit=None)\ncredit_limit_account = models.Account.objects.create(credit_limit=Decimal('1000.00'))\n\ntoday = datetime.date.today()\nnext_week = today + datetime.timedelta(days=7)\ndate_limited_account = models.Account.objects.create(\n\tstart_date=today, end_date=next_week)\n```\n\nTransfer funds using the facade:\n\n``` python\n\nfrom accounts import facade\n\nstaff_member = User.objects.get(username=\"staff\")\ntrans = facade.transfer(source=no_credit_limit_account,\n\t\t\t\t\t\tdestination=user_account,\n\t\t\t\t\t\tamount=Decimal('10.00'),\n\t\t\t\t\t\tuser=staff_member)\n```\n\nReverse transfers:\n\n``` python\nfacade.reverse(trans, user=staff_member, \n\t\t\t\tdescription=\"Just an example\")\n```\n\nIf the proposed transfer is invalid, an exception will be raised. All\nexceptions are subclasses of `accounts.exceptions.AccountException`. Your\nclient code should look for exceptions of this type and handle them\nappropriately.\n \nClient code should only use the `accounts.models.Budget` class and the\ntwo functions from `accounts.facade` - nothing else should be required.\n\nError handling\n--------------\n\nNote that the transfer operation is wrapped in its own database transaction to\nensure that only complete transfers are written out. When using Django's\ntransaction middleware, you need to be careful. If you have an unhandled\nexception, then account transfers will still be committed even though nothing\nelse will be. To handle this, you need to make sure that, if an exception\noccurs during your post-payment code, then you roll-back any transfers.\n\nHere's a toy example:\n\n``` python\nfrom accounts import facade\n\ndef submit(self, order_total):\n\t# Take payment first\n\ttransfer = facade.transfer(self.get_user_account(),\n\t\t\t\t\t\t\t self.get_merchant_account(),\n\t\t\t\t\t\t\t order_total)\n\t# Create order models\n\ttry:\n\t\tself.place_order()\n\texcept Exception, e:\n\t\t# Something went wrong placing the order. Roll-back the previous\n\t\t# transfer\n\t\tfacade.reverse(transfer)\n```\n\nIn this situation, you'll end up with two transfers being created but no order.\nWhile this isn't ideal, it's the best way of handling exceptions that occur\nduring order placement.\n\nMulti-transfer payments\n-----------------------\n\nProjects will often allow users to have multiple accounts and pay for an order\nusing more than one. This will involve several transfers and needs some careful handling\nin your application code.\n\nIt normally makes sense to write your own wrapper around the accounts API to encapsulate\nyour business logic and error handling. Here's an example:\n\n``` python\nfrom decimal import Decimal as D\nfrom accounts import models, exceptions, facade\n\n\ndef redeem(order_number, user, amount):\n # Get user's non-empty accounts ordered with the first to expire first\n accounts = models.Account.active.filter(\n user=user, balance__gt=0).order_by('end_date')\n\n # Build up a list of potential transfers that cover the requested amount\n transfers = []\n amount_to_allocate = amount\n for account in accounts:\n to_transfer = min(account.balance, amount_to_allocate)\n transfers.append((account, to_transfer))\n amount_to_allocate -= to_transfer\n if amount_to_allocate == D('0.00'):\n break\n if amount_to_allocate > D('0.00'):\n raise exceptions.InsufficientFunds()\n\n # Execute transfers to some 'Sales' account\n destination = models.Account.objects.get(name=\"Sales\")\n completed_transfers = []\n try:\n for account, amount in transfers:\n transfer = facade.transfer(\n account, destination, amount, user=user,\n description=\"Order %s\" % order_number)\n completed_transfers.append(transfer)\n except exceptions.AccountException, transfer_exc:\n # Something went wrong with one of the transfers (possibly a race condition).\n # We try and roll back all completed ones to get us back to a clean state.\n try:\n for transfer in completed_transfers:\n facade.reverse(transfer)\n except Exception, reverse_exc:\n # Uh oh: No man's land. We could be left with a partial redemption. This will\n # require an admin to intervene. Make sure your logger mails admins on error.\n logger.error(\"Order %s, transfers failed (%s) and reverse failed (%s)\",\n order_number, transfer_exc, reverse_exc)\n logger.exception(reverse_exc)\n\n # Raise an exception so that your client code can inform the user appropriately.\n raise RedemptionFailed()\n else:\n # All transfers completed ok\n return completed_transfers\n```\n\nAs you can see, there is some careful handling of the scenario where not all transfers can be \nexecuted.\n\n``` python\n\n try:\n transfers = api.redeem(order_number, user, total_incl_tax)\n except Exception:\n # Inform user of failed payment\n else:\n for transfer in transfers:\n source_type, __ = SourceType.objects.get_or_create(name=\"Accounts\")\n source = Source(\n source_type=source_type,\n amount_allocated=transfer.amount,\n amount_debited=transfer.amount,\n reference=transfer.reference)\n self.add_payment_source(source)\n```\n\nCore accounts and account types\n-------------------------------\n\nA post-syncdb signal will create the common structure for account types and\naccounts. Some names can be controlled with settings, as indicated in parentheses. \n\n- **Assets**\n\n - **Sales**\n - Redemptions (`ACCOUNTS_REDEMPTIONS_NAME`) - where money is\n transferred to when an account is used to pay for something. \n - Lapsed (`ACCOUNTS_LAPSED_NAME`) - where money is transferred to\n when an account expires. This is done by the\n 'close_expired_accounts' management command. The name of this\n account can be set using the `ACCOUNTS_LAPSED_NAME`.\n\n - **Cash**\n - \"Bank\" (`ACCOUNTS_BANK_NAME`) - the source account for creating new\n accounts that are paid for by the customer (eg a giftcard). This\n account will not have a credit limit and will normally have a\n negative balance as money is only transferred out.\n\n - **Unpaid** - This contains accounts that are used as sources for other\n accounts but aren't paid for by the customer. For instance, you might\n allow admins to create new accounts in the dashboard. An account of this\n type will be the source account for the initial transfer.\n\n- **Liabilities**\n\n - **Deferred income** - This contains customer accounts/giftcards. You may want to create\n additional account types within this type to categorise accounts.\n\nExample transactions\n--------------------\n\nConsider the following accounts and account types:\n\n- **Assets**\n - **Sales** \n - Redemptions \n - Lapsed\n - **Cash**\n - Bank \n - **Unpaid**\n - Merchant funded \n- **Liabilities**\n - **Deferred income**\n\nNote that all accounts start with a balance of 0 and the sum of all balances will always be zero.\n\n*A customer purchases a \u00a350 giftcard*\n\n- A new account is created of type 'Deferred income' with an end date\n- \u00a350 is transferred from the Bank to this new account\n\n*A customer pays for a \u00a330 order using their \u00a350 giftcard*\n\n- \u00a330 is transferred from the giftcard account to the redemptions account\n\n*The customer's giftcard expires with \u00a320 still on it*\n\n- \u00a320 is transferred from the giftcard account to the lapsed account\n\n*The customer phones up to complain and a staff member creates a new giftcard for \u00a320*\n\n- A new account is created of type 'Deferred income' \n- \u00a320 is transferred from the \"Merchant funded\" account to this new account\n\nSettings\n--------\n\nThere are settings to control the naming and initial unpaid and deferred income account\ntypes:\n\n* `ACCOUNTS_MIN_INITIAL_VALUE` The minimum value that can be used to create an\n account (or for a top-up)\n\n* `ACCOUNTS_MAX_INITIAL_VALUE` The maximum value that can be transferred to an\n account.\n\nContributing\n------------\n\nFork repo, set-up virtualenv and run:\n\n make install\n\nRun tests with:\n \n ./runtests.py\n\nHistory\n-------\n\nThis project used to depend on the e-commerce framework [Oscar](https://github.com/tangentlabs/django-oscar) in a number of places. You may be interested in the upstream repos if you want Oscar integration. This repo was forked off for people who want account balances without Oscar integration.", "description_content_type": null, "docs_url": null, "download_url": "UNKNOWN", "downloads": { "last_day": -1, "last_month": -1, "last_week": -1 }, "home_page": "UNKNOWN", "keywords": null, "license": "Copyright (c) 2011, Tangent Communications PLC and individual contributors.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n \n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n 3. Neither the name of Tangent Communications PLC nor the names of its contributors \n\t may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", "maintainer": null, "maintainer_email": null, "name": "django-account-balances", "package_url": "https://pypi.org/project/django-account-balances/", "platform": "UNKNOWN", "project_url": "https://pypi.org/project/django-account-balances/", "project_urls": { "Download": "UNKNOWN", "Homepage": "UNKNOWN" }, "release_url": "https://pypi.org/project/django-account-balances/0.4/", "requires_dist": null, "requires_python": null, "summary": "Track account credits in Django", "version": "0.4" }, "last_serial": 966303, "releases": { "0.3": [ { "comment_text": "", "digests": { "md5": "6bb8c230f44a2d64bd1cc012940730c8", "sha256": "a3279c15054df257996549041f507512f89ed92126fe15d5a3072f8a1011967a" }, "downloads": -1, "filename": "django-account-balances-0.3.tar.gz", "has_sig": false, "md5_digest": "6bb8c230f44a2d64bd1cc012940730c8", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 36946, "upload_time": "2014-01-11T05:59:35", "url": "https://files.pythonhosted.org/packages/1a/e4/71126431c2dc063f52e276e415ae276bbb1ff0c6cbd39f088e717124eb15/django-account-balances-0.3.tar.gz" } ], "0.4": [ { "comment_text": "", "digests": { "md5": "35f1fea4d54b08f181a151ef0929cf48", "sha256": "d28d3f0f18677a954244a386fa7aef0977a4870458452d08ef915e6915d613c7" }, "downloads": -1, "filename": "django-account-balances-0.4.tar.gz", "has_sig": false, "md5_digest": "35f1fea4d54b08f181a151ef0929cf48", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 36979, "upload_time": "2014-01-11T22:03:36", "url": "https://files.pythonhosted.org/packages/f4/73/2b2957518b891fd7e222111a426da0f83cc24e8bc057715e4927e297c639/django-account-balances-0.4.tar.gz" } ] }, "urls": [ { "comment_text": "", "digests": { "md5": "35f1fea4d54b08f181a151ef0929cf48", "sha256": "d28d3f0f18677a954244a386fa7aef0977a4870458452d08ef915e6915d613c7" }, "downloads": -1, "filename": "django-account-balances-0.4.tar.gz", "has_sig": false, "md5_digest": "35f1fea4d54b08f181a151ef0929cf48", "packagetype": "sdist", "python_version": "source", "requires_python": null, "size": 36979, "upload_time": "2014-01-11T22:03:36", "url": "https://files.pythonhosted.org/packages/f4/73/2b2957518b891fd7e222111a426da0f83cc24e8bc057715e4927e297c639/django-account-balances-0.4.tar.gz" } ] }