{"id":13411038,"url":"https://github.com/yii2tech/balance","last_synced_at":"2025-10-01T02:31:14.183Z","repository":{"id":57087040,"uuid":"55979106","full_name":"yii2tech/balance","owner":"yii2tech","description":"Balance accounting (bookkeeping) system based on debit and credit principle","archived":true,"fork":false,"pushed_at":"2019-07-02T11:15:31.000Z","size":62,"stargazers_count":181,"open_issues_count":0,"forks_count":44,"subscribers_count":18,"default_branch":"master","last_synced_at":"2025-08-24T19:30:08.598Z","etag":null,"topics":["accounting","balance","credit","debit","yii","yii2","yii2-extension"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yii2tech.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["klimov-paul"],"patreon":"klimov_paul"}},"created_at":"2016-04-11T14:25:41.000Z","updated_at":"2025-07-20T00:49:18.000Z","dependencies_parsed_at":"2022-08-24T22:50:51.763Z","dependency_job_id":null,"html_url":"https://github.com/yii2tech/balance","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/yii2tech/balance","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fbalance","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fbalance/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fbalance/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fbalance/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yii2tech","download_url":"https://codeload.github.com/yii2tech/balance/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yii2tech%2Fbalance/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":277378600,"owners_count":25808156,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-28T02:00:08.834Z","response_time":79,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["accounting","balance","credit","debit","yii","yii2","yii2-extension"],"created_at":"2024-07-30T20:01:10.985Z","updated_at":"2025-10-01T02:31:13.828Z","avatar_url":"https://github.com/yii2tech.png","language":"PHP","funding_links":["https://github.com/sponsors/klimov-paul","https://patreon.com/klimov_paul"],"categories":["Core components","Component 组件"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/yii2tech\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://avatars2.githubusercontent.com/u/12951949\" height=\"100px\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eBalance Accounting System extension for Yii2\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\nThis extension provides basic support for balance accounting (bookkeeping) system based on [debit and credit](https://en.wikipedia.org/wiki/Debits_and_credits) principle.\n\nFor license information check the [LICENSE](LICENSE.md)-file.\n\n[![Latest Stable Version](https://poser.pugx.org/yii2tech/balance/v/stable.png)](https://packagist.org/packages/yii2tech/balance)\n[![Total Downloads](https://poser.pugx.org/yii2tech/balance/downloads.png)](https://packagist.org/packages/yii2tech/balance)\n[![Build Status](https://travis-ci.org/yii2tech/balance.svg?branch=master)](https://travis-ci.org/yii2tech/balance)\n\n\nInstallation\n------------\n\nThe preferred way to install this extension is through [composer](http://getcomposer.org/download/).\n\nEither run\n\n```\nphp composer.phar require --prefer-dist yii2tech/balance\n```\n\nor add\n\n```json\n\"yii2tech/balance\": \"*\"\n```\n\nto the require section of your composer.json.\n\n\nUsage\n-----\n\nThis extension provides basic support for balance accounting (bookkeeping) system based on [debit and credit](https://en.wikipedia.org/wiki/Debits_and_credits) principle.\nBalance system is usually used for the accounting (bookkeeping) and money operations. However, it may also be used for any\nresource transferring from one location to another. For example: transferring goods from storehouse to the shop and so on.\n\nThere 2 main terms related to the balance system:\n\n - account - virtual storage of the resources, which have some logical meaning.\n - transaction - represents actual transfer of the resources to or from particular account.\n\nLets assume we have a system, which provides virtual money balance for the user. Money on the balance can be used for the\ngoods purchasing, user can top up his balance via some payment gateway. In such example, each user should have 3 virtual\nbalance accounts: 'virtual-money', 'payment-gateway' and 'purchases'. When user tops up his virtual balance, our system\nshould remove money from 'payment-gateway' and add them to 'virtual-money'. When user purchases an item, our system should\nremove money from 'virtual-money' and add them to 'purchases'.\nThe trick is: if you sum current amount over all user related accounts ('payment-gateway' + 'virtual-money' + 'purchases'),\nit will always be equal to zero. Such check allows you to verify if something went wrong any time.\n\nThis extension introduces term 'balance manager' as a Yii application component, which should handle all balance transactions.\nSeveral implementations of such component are provided:\n\n - [[yii2tech\\balance\\ManagerDb]] - uses a relational database as a data storage.\n - [[yii2tech\\balance\\ManagerMongoDb]] - uses MongoDB as a data storage.\n - [[yii2tech\\balance\\ManagerActiveRecord]] - uses ActiveRecord classes for the data storage.\n\nPlease refer to the particular manager class for more details.\n\nYou can use balance manager as standalone object or configure it as application component.\nApplication configuration example:\n\n```php\nreturn [\n    'components' =\u003e [\n        'balanceManager' =\u003e [\n            'class' =\u003e 'yii2tech\\balance\\ManagerDb',\n            'accountTable' =\u003e '{{%BalanceAccount}}',\n            'transactionTable' =\u003e '{{%BalanceTransaction}}',\n            'accountLinkAttribute' =\u003e 'accountId',\n            'amountAttribute' =\u003e 'amount',\n            'dataAttribute' =\u003e 'data',\n        ],\n    ],\n    ...\n];\n```\n\nIn order to increase (debit) balance at particular account, [[\\yii2tech\\balance\\ManagerInterface::increase()]] method is used:\n\n```php\nYii::$app-\u003ebalanceManager-\u003eincrease($accountId, 500); // add 500 credits to account\n```\n\nIn order to decrease (credit) balance at particular account, [[\\yii2tech\\balance\\ManagerInterface::decrease()]] method is used:\n\n```php\nYii::$app-\u003ebalanceManager-\u003edecrease($accountId, 100); // remove 100 credits from account\n```\n\n\u003e Tip: actually, method `decrease()` is redundant, you can call `increase()` with negative amount in order to achieve same result.\n\nIt is unlikely you will use plain `increase()` and `decrease()` methods in your application. In most cases there is a need\nto **transfer** money from one account to another at once. Method [[\\yii2tech\\balance\\ManagerInterface::transfer()]] can be\nused for this:\n\n```php\n$fromId = 1;\n$toId = 2;\nYii::$app-\u003ebalanceManager-\u003etransfer($fromId, $to, 100); // remove 100 credits from account 1 and add 100 credits to account 2\n```\n\nNote that method `transfer()` creates 2 separated transactions: one per each affected account. Thus you can easily fetch\nall money transfer history for particular account, simply selecting all transactions linked to it. 'Debit' transactions\nwill have positive amount, while 'credit' ones - negative.\n\n\u003e Note: If you wish each transaction created by `transfer()` remember another account involved in the process, you'll need\n  to setup [[\\yii2tech\\balance\\Manager::$extraAccountLinkAttribute]].\n\nYou may revert particular transaction using [[\\yii2tech\\balance\\ManagerInterface::revert()]] method:\n\n```php\nYii::$app-\u003ebalanceManager-\u003erevert($transactionId);\n```\n\nThis method will not remove original transaction, but create new one, which compensates it.\n\n\n## Querying accounts \u003cspan id=\"querying-accounts\"\u003e\u003c/span\u003e\n\nUsing account IDs for the balance manager is not very practical. In our above example, each system user have 3 virtual\naccounts, each of which has its own unique ID. However, while performing purchase we operating user ID and account type,\nso we need to query actual account ID before using balance manager.\nThus there is an ability to specify account for the balance manager methods using their attributes set. For example:\n\n```php\nYii::$app-\u003ebalanceManager-\u003etransfer(\n    [\n        'userId' =\u003e Yii::$app-\u003euser-\u003eid,\n        'type' =\u003e 'virtual-money',\n    ],\n    [\n        'userId' =\u003e Yii::$app-\u003euser-\u003eid,\n        'type' =\u003e 'purchases',\n    ],\n    500\n);\n```\n\nIn this example balance manager will find ID of the affected accounts automatically, using provided attributes as a filter.\n\nYou may enable [[yii2tech\\balance\\Manager::$autoCreateAccount]], allowing automatic creation of the missing accounts, if they\nare specified as attributes set. This allows accounts creation on the fly, by demand only, eliminating necessity of their\npre-creation.\n\n**Heads up!** Actually 'account' entity is redundant at balance system, and its usage can be avoided. However, its presence\nprovides more flexibility and saves performance. Storing of account data is not mandatory for this extension, you can\nconfigure your balance manager in the way it is not used.\n\n\n## Finding account current balance \u003cspan id=\"finding-account-current-balance\"\u003e\u003c/span\u003e\n\nCurrent money amount at particular account can always be calculated as a sum of amounts over related transactions.\nYou can use [[\\yii2tech\\balance\\ManagerInterface::calculateBalance()]] method for that:\n\n```php\nYii::$app-\u003ebalanceManager-\u003etransfer($fromAccount, $toAccount, 100); // assume this is first time accounts are affected\n\necho Yii::$app-\u003ebalanceManager-\u003ecalculateBalance($fromAccount); // outputs: -100\necho Yii::$app-\u003ebalanceManager-\u003ecalculateBalance($toAccount); // outputs: 100\n```\n\nHowever, calculating current balance each time you need it, is not efficient. Thus you can specify an attribute of account\nentity, which will be used to store current account balance. This can be done via [[\\yii2tech\\balance\\Manager::$accountBalanceAttribute]].\nEach time balance manager performs a transaction it will update this attribute accordingly:\n\n```php\nuse yii\\db\\Query;\n\nYii::$app-\u003ebalanceManager-\u003etransfer($fromAccountId, $toAccountId, 100); // assume this is first time accounts are affected\n\n$currentBalance = (new Query())\n    -\u003eselect(['balance'])\n    -\u003efrom('BalanceAccount')\n    -\u003eandWhere(['id' =\u003e $fromAccountId])\n    -\u003escalar();\n\necho $currentBalance; // outputs: -100\n```\n\n\n## Saving extra transaction data \u003cspan id=\"saving-extra-transaction-data\"\u003e\u003c/span\u003e\n\nUsually there is a necessity to save extra information along with the transaction. For example: we may need to save\npayment ID received from payment gateway. This can be achieved in following way:\n\n```php\n// simple increase :\nYii::$app-\u003ebalanceManager-\u003eincrease(\n    [\n        'userId' =\u003e Yii::$app-\u003euser-\u003eid,\n        'type' =\u003e 'virtual-money',\n    ],\n    100,\n    // extra data associated with transaction :\n    [\n        'paymentGateway' =\u003e 'PayPal',\n        'paymentId' =\u003e 'abcxyzerft',\n    ]\n);\n\n// transfer :\nYii::$app-\u003ebalanceManager-\u003etransfer(\n    [\n        'userId' =\u003e Yii::$app-\u003euser-\u003eid,\n        'type' =\u003e 'payment-gateway',\n    ],\n    [\n        'userId' =\u003e Yii::$app-\u003euser-\u003eid,\n        'type' =\u003e 'virtual-money',\n    ],\n    100,\n    // extra data associated with transaction :\n    [\n        'paymentGateway' =\u003e 'PayPal',\n        'paymentId' =\u003e 'abcxyzerft',\n    ]\n);\n```\n\nThe way extra attributes are stored in the data storage depends on particular balance manager implementation.\nFor example: [[\\yii2tech\\balance\\ManagerDb]] will try to store extra data inside transaction table columns, if their name\nequals the parameter name. You may as well setup special data field via [[\\yii2tech\\balance\\ManagerDb::$dataAttribute]],\nwhich will store all extra parameters, which have no matching column, in serialized state.\n\n\u003e Note: watch for the keys you use in transaction data: make sure they do not conflict with columns, which are\n  reserved for other purposes, like primary keys.\n\n\n## Events \u003cspan id=\"events\"\u003e\u003c/span\u003e\n\n[[\\yii2tech\\balance\\Manager]] provide several events, which can be handled via event handler or behavior:\n\n - [[yii2tech\\balance\\Manager::EVENT_BEFORE_CREATE_TRANSACTION]] - raised before creating new transaction.\n - [[yii2tech\\balance\\Manager::EVENT_AFTER_CREATE_TRANSACTION]] - raised after creating new transaction.\n\nFor example:\n\n```php\nuse yii2tech\\balance\\Manager;\nuse yii2tech\\balance\\ManagerDb;\n\n$manager = new ManagerDb();\n\n$manager-\u003eon(Manager::EVENT_BEFORE_CREATE_TRANSACTION, function ($event) {\n    $event-\u003etransactionData['amount'] += 10; // you may adjust transaction data to be saved, including transaction amount\n    $event-\u003etransactionData['comment'] = 'adjusted by event handler';\n});\n\n$manager-\u003eon(Manager::EVENT_AFTER_CREATE_TRANSACTION, function ($event) {\n    echo 'new transaction: ' $event-\u003etransactionId; // you may get newly created transaction ID\n});\n\n$manager-\u003eincrease(1, 100); // outputs: 'new transaction: 1'\necho Yii::$app-\u003ebalanceManager-\u003ecalculateBalance(1); // outputs: 110\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Fbalance","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyii2tech%2Fbalance","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyii2tech%2Fbalance/lists"}