Repository: jeka-kiselyov/dimeshift Branch: master Commit: 440898e8e48b Files: 202 Total size: 489.5 KB Directory structure: gitextract__uiwwo29/ ├── .bowerrc ├── .gitignore ├── .rebooted ├── Gruntfile.js ├── LICENSE ├── Procfile ├── README.md ├── app.json ├── bower.json ├── config/ │ ├── config.json │ ├── currencies.json │ ├── pages.json │ └── resources.json ├── data/ │ ├── cache/ │ │ └── .gitignore │ ├── i18n/ │ │ ├── en.json │ │ ├── ptbr.json │ │ ├── ru.json │ │ └── ua.json │ ├── mailtemplates/ │ │ ├── registration.template │ │ ├── remove_account.template │ │ └── restore_password.template │ └── min/ │ └── .gitignore ├── docs/ │ └── api.md ├── includes/ │ ├── api.js │ ├── config.js │ ├── demo.js │ ├── errors.js │ ├── exchange.js │ ├── mailer.js │ ├── models/ │ │ ├── authentication.js │ │ ├── index.js │ │ ├── plan.js │ │ ├── transaction.js │ │ ├── user.js │ │ ├── wallet.js │ │ └── wallet_access.js │ ├── routes/ │ │ ├── exchange/ │ │ │ ├── exchange.apib │ │ │ └── rates.js │ │ ├── i18n/ │ │ │ ├── get.js │ │ │ └── i18n.apib │ │ ├── index.js │ │ ├── plans/ │ │ │ ├── del.js │ │ │ ├── get.js │ │ │ ├── list.js │ │ │ ├── plans.apib │ │ │ ├── post.js │ │ │ └── put.js │ │ ├── stats/ │ │ │ ├── month.js │ │ │ ├── stats.apib │ │ │ ├── week.js │ │ │ └── year.js │ │ ├── users/ │ │ │ ├── get.js │ │ │ ├── newpassword.js │ │ │ ├── post.js │ │ │ ├── put.js │ │ │ ├── removeaccount.js │ │ │ ├── restore.js │ │ │ ├── signin.js │ │ │ ├── signout.js │ │ │ ├── users.apib │ │ │ └── wallets/ │ │ │ └── list.js │ │ └── wallets/ │ │ ├── accesses/ │ │ │ ├── accesses.apib │ │ │ ├── del.js │ │ │ ├── list.js │ │ │ └── post.js │ │ ├── delete.js │ │ ├── get.js │ │ ├── list.js │ │ ├── plans/ │ │ │ └── list.js │ │ ├── post.js │ │ ├── put.js │ │ ├── stats/ │ │ │ ├── month.js │ │ │ ├── wallet_stats.apib │ │ │ ├── week.js │ │ │ └── year.js │ │ ├── transactions/ │ │ │ ├── del.js │ │ │ ├── list.js │ │ │ ├── post.js │ │ │ └── transactions.apib │ │ └── wallets.apib │ ├── servers/ │ │ ├── images_server.js │ │ ├── index.js │ │ ├── index_server.js │ │ ├── minify_server.js │ │ ├── public_server.js │ │ └── static_file_server.js │ ├── test/ │ │ ├── planning.test.js │ │ ├── stats.test.js │ │ └── wallet.test.js │ └── test.js ├── index.js ├── package.json ├── public/ │ ├── css/ │ │ ├── .gitignore │ │ ├── main.css │ │ └── parts/ │ │ ├── dialogs/ │ │ │ ├── base.css │ │ │ ├── registration.css │ │ │ └── signin.css │ │ ├── head.css │ │ ├── home.css │ │ ├── icons.css │ │ ├── import.css │ │ ├── overload.css │ │ ├── page_transitions.css │ │ ├── sticked_footer.css │ │ ├── text_format.css │ │ ├── wallets.css │ │ └── widgets.css │ ├── index.html │ ├── jstemplates/ │ │ ├── 404.tpl │ │ ├── dialogs/ │ │ │ ├── add_profit.tpl │ │ │ ├── add_wallet.tpl │ │ │ ├── change_language.tpl │ │ │ ├── edit_wallet.tpl │ │ │ ├── fill_profile.tpl │ │ │ ├── hide_wallet.tpl │ │ │ ├── registration.tpl │ │ │ ├── remove_access.tpl │ │ │ ├── remove_plan.tpl │ │ │ ├── remove_transaction.tpl │ │ │ ├── restore.tpl │ │ │ ├── set_total_to.tpl │ │ │ ├── signin.tpl │ │ │ ├── transaction_details.tpl │ │ │ └── wallet_accesses.tpl │ │ ├── months.tpl │ │ ├── pages/ │ │ │ ├── import/ │ │ │ │ └── xls.tpl │ │ │ ├── index/ │ │ │ │ └── index.tpl │ │ │ ├── plans/ │ │ │ │ ├── index.tpl │ │ │ │ └── view.tpl │ │ │ ├── profile/ │ │ │ │ └── index.tpl │ │ │ ├── user/ │ │ │ │ ├── confirm.tpl │ │ │ │ ├── index.tpl │ │ │ │ ├── registration.tpl │ │ │ │ ├── restore.tpl │ │ │ │ ├── signin.tpl │ │ │ │ └── update_password.tpl │ │ │ └── wallets/ │ │ │ ├── index.tpl │ │ │ └── view.tpl │ │ └── parts/ │ │ ├── transactions.tpl │ │ └── wallet_plans.tpl │ └── scripts/ │ ├── .gitignore │ ├── app/ │ │ ├── abstract/ │ │ │ ├── dialog.js │ │ │ └── page.js │ │ ├── collections/ │ │ │ ├── plans.js │ │ │ ├── transactions.js │ │ │ ├── users.js │ │ │ ├── wallets.js │ │ │ └── wallets_accesses.js │ │ ├── exchange.js │ │ ├── helper.js │ │ ├── i18n.js │ │ ├── local_storage.js │ │ ├── log.js │ │ ├── models/ │ │ │ ├── plan.js │ │ │ ├── transaction.js │ │ │ ├── user.js │ │ │ ├── wallet.js │ │ │ └── wallets_access.js │ │ ├── router.js │ │ ├── settings.js │ │ ├── template_manager.js │ │ ├── view_stack.js │ │ └── views/ │ │ ├── charts/ │ │ │ └── balance.js │ │ ├── dialogs/ │ │ │ ├── add_profit.js │ │ │ ├── add_wallet.js │ │ │ ├── change_language.js │ │ │ ├── edit_wallet.js │ │ │ ├── fill_profile.js │ │ │ ├── hide_wallet.js │ │ │ ├── logout.js │ │ │ ├── registration.js │ │ │ ├── remove_access.js │ │ │ ├── remove_plan.js │ │ │ ├── remove_transaction.js │ │ │ ├── restore.js │ │ │ ├── set_total_to.js │ │ │ ├── signin.js │ │ │ ├── transaction_details.js │ │ │ └── wallet_accesses.js │ │ ├── header.js │ │ ├── pages/ │ │ │ ├── 404.js │ │ │ ├── import_xls.js │ │ │ ├── index.js │ │ │ ├── plan.js │ │ │ ├── plans.js │ │ │ ├── profile.js │ │ │ ├── update_password.js │ │ │ ├── wallet.js │ │ │ └── wallets.js │ │ ├── parts/ │ │ │ ├── profile_change_password.js │ │ │ ├── profile_remove_account.js │ │ │ ├── transactions.js │ │ │ └── wallet_plans.js │ │ ├── tours/ │ │ │ ├── wallet.js │ │ │ └── wallets.js │ │ └── widgets/ │ │ └── index.js │ ├── app.js │ ├── functions.js │ ├── setup.js │ └── table_helper.js └── tools/ ├── check_i18n_files.js └── harvest_i18n_strings.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .bowerrc ================================================ { "directory": "public/vendors/" } ================================================ FILE: .gitignore ================================================ node_modules public/vendors npm-debug.log data/database.sqlite ================================================ FILE: .rebooted ================================================ rebooted ================================================ FILE: Gruntfile.js ================================================ module.exports = function(grunt) { grunt.initConfig({ concurrent: { dev: { tasks: ['nodemon', 'watch'], options: { logConcurrentOutput: true } } }, nodemon: { dev: { script: 'index.js', options: { ext: 'js,css,html,tpl', watch: ['**/*.js', '**/*.tpl', '**/*.css', 'public/index.html', '**/*.json'], nodeArgs: ['--debug'], env: { PORT: '8080' }, // omit this property if you aren't serving HTML files and // don't want to open a browser tab on start callback: function(nodemon) { nodemon.on('log', function(event) { console.log(event.colour); }); // opens browser on initial server start nodemon.on('config:update', function() { // Delay before server listens on port setTimeout(function() { require('open')('http://localhost:8080'); }, 1000); }); // refreshes browser when server reboots nodemon.on('restart', function() { // Delay before server listens on port setTimeout(function() { require('fs').writeFileSync('.rebooted', 'rebooted'); }, 3000); }); } } } }, watch: { server: { files: ['.rebooted'], options: { livereload: true, debounceDelay: 500 } }, javascript: { files: ['includes/**/*.js'], tasks: "test" } }, env: { options: {}, test: { NODE_ENV: 'test' }, apiary: { APIARY_API_KEY: process.env.DIMESHIFT_APIARY_API_KEY // https://login.apiary.io/tokens } }, concat: { options: { separator: '\n \n', }, dist: { src: ["docs/api.md", "includes/routes/**/*.apib"], dest: 'data/cache/api.apib' } }, exec: { publish: ['apiary', 'publish', ['--api-name', 'dimeshift'].join('='), ['--path', 'data/cache/api.apib'].join('=')].join(' ') }, run: { test_server: { options: { wait: false }, args: [ 'index.js' ] } }, mochacli: { options: { require: [], reporter: 'spec', bail: true, sort: true, env: { NODE_ENV: 'test' } }, all: ['includes/test/*.js'] } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-nodemon'); grunt.loadNpmTasks('grunt-concurrent'); grunt.loadNpmTasks('grunt-mocha-cli'); grunt.loadNpmTasks('grunt-env'); grunt.loadNpmTasks('grunt-run'); grunt.loadNpmTasks('grunt-exec'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('default', ['concurrent']); grunt.registerTask('dev', ['concurrent']); grunt.registerTask('test', ['env:test', 'run:test_server', 'mochacli', 'stop:test_server']); grunt.registerTask('apiary', ['env:apiary', 'concat', 'exec:publish']); }; ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: Procfile ================================================ web: node index.js ================================================ FILE: README.md ================================================ # DimeShift - easiest way to track your expenses. Online. Open-source. Free * node.js * npm * Front-end: jQuery, Bootstrap, Backbone.js with JSmart template engine. * Back-end: Sequelize, SQLite database by default, easy to switch to MySQL or Postgree for production. Demo: ---- [DimeShift](https://dimeshift.com/) Desktop Application: ---- [DimeShift Desktop](https://github.com/jeka-kiselyov/dimeshift-desktop). Cross platform desktop app built on [Electron](http://electron.atom.io/) Installation: ---- [![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/jeka-kiselyov/dimeshift) or install from CLI: ```bash mkdir dimeshift cd dimeshift git clone https://github.com/jeka-kiselyov/dimeshift.git . npm install ``` * [Install npm](https://docs.npmjs.com/getting-started/installing-node) if you don't have it. * [Install bower](http://bower.io/#install-bower) if you don't have it. Run: ---- ```bash npm start ``` Open [localhost:8080](http://localhost:8080) in your browser. Documentation: ---- [API](http://docs.dimeshift.apiary.io/) Screenshots: ---- ![Dimeshift transactions](https://raw.githubusercontent.com/jeka-kiselyov/dimeshift/master/public/images/homepage/screenshots/transactions.jpg?1mar16) ![Dimeshift wallets](https://raw.githubusercontent.com/jeka-kiselyov/dimeshift/master/public/images/homepage/screenshots/wallets.jpg?1mar16) ![Dimeshift goals](https://raw.githubusercontent.com/jeka-kiselyov/dimeshift/master/public/images/homepage/screenshots/goal.jpg?1mar16) ![Dimeshift i18n](https://raw.githubusercontent.com/jeka-kiselyov/dimeshift/master/public/images/homepage/screenshots/i18n.jpg?1mar16) License ---- GNU Affero GPL **Free Software, Hell Yeah!** From Slavyansk, Ukraine. With Love ================================================ FILE: app.json ================================================ { "name": "dimeshift", "description": "Webapp to track and manage personal finances", "repository": "https://github.com/jeka-kiselyov/dimeshift", "logo": "https://raw.githubusercontent.com/jeka-kiselyov/dimeshift/master/public/images/homepage/screenshots/transactions.jpg", "keywords": ["node", "finances", "money", "HTML5", "Sequelize", "Backbone.js", "Restify"], "addons": ["heroku-postgresql:hobby-dev", "sparkpost:free"], "env": { "NODE_ENV": "heroku" } } ================================================ FILE: bower.json ================================================ { "name": "DimeShift", "version": "0.1.34", "authors": [ "jeka911 " ], "description": "", "main": "app/public/scripts/app.js", "moduleType": [ "globals" ], "dependencies": { "jquery": "1.10.2", "jasmine": "https://github.com/pivotal/jasmine/releases/download/v2.0.2/jasmine-standalone-2.0.2.zip", "jasmine-ajax": "https://raw.githubusercontent.com/pivotal/jasmine-ajax/master/lib/mock-ajax.js", "jsmart": "2.13.1", "backbone": "1.0.0", "backbone.paginator": "https://github.com/backbone-paginator/backbone.paginator/archive/2.0.2.zip", "underscore": "1.7.0", "bootstrap": "3.3.4", "magnific-popup": "*", "bootstrap-clickonmouseover": "https://github.com/jeka-kiselyov/bootstrap-clickonmouseover/archive/master.zip", "mprogress": "https://github.com/lightningtgc/MProgress.js/archive/master.zip", "bootstrap-tour": "~0.10.2", "js-xlsx": "~0.8.0", "moment": "~2.10.6", "eonasdan-bootstrap-datetimepicker": "^4.17.37", "font-awesome": "fontawesome#^4.6.1" } } ================================================ FILE: config/config.json ================================================ { "development": { "port": 8080, "database": { "dialect": "sqlite", "username": "root", "password": "root", "database": "walletjs", "host": "127.0.0.1", "storage": "data/database.sqlite" }, "smtp": { "host": "mailtrap.io", "username": "38298e68fa9771771", "password": "ab75f0affdd61a", "port": "465" }, "openexchangerates": { "use_env_variable": false, "app_id": "OPENEXCHANGERATES_APP_ID", "update_interval": 86400 }, "default_from_email": "noreply@dimeshift.com", "site_path": "http://localhost:8080/", "minify": { "javascript": true, "css": true } }, "electron": { "port": 0, "database": { "dialectModulePath": "../../includes/sqlite3.js", "dialect": "sqlite", "storage": "data/database.sqlite" }, "smtp": null, "openexchangerates": null, "default_from_email": null, "site_path": null, "minify": { "javascript": true, "css": true } }, "test": { "port": 8081, "database": { "dialect": "sqlite", "storage": "data/database.sqlite" }, "smtp": null, "openexchangerates": { "app_id": "234234234234234234234", "update_interval": 86400 }, "default_from_email": "noreply@dimeshift.com", "site_path": "http://localhost:8080/", "minify": { "javascript": false, "css": false } }, "heroku": { "database": { "use_env_variable": "DATABASE_URL" }, "smtp": { "use_env_variables": true, "host": "SPARKPOST_SMTP_HOST", "username": "SPARKPOST_SMTP_USERNAME", "password": "SPARKPOST_SMTP_PASSWORD", "port": "SPARKPOST_SMTP_PORT" }, "openexchangerates": { "use_env_variable": true, "app_id": "OPENEXCHANGERATES_APP_ID", "update_interval": 86400 }, "default_from_email": "noreply@dimeshift.com", "site_path": "http://dimeshift.com/", "minify": { "javascript": true, "css": true } } } ================================================ FILE: config/currencies.json ================================================ { "AED": "United Arab Emirates Dirham", "AFN": "Afghan Afghani", "ALL": "Albanian Lek", "AMD": "Armenian Dram", "ANG": "Netherlands Antillean Guilder", "AOA": "Angolan Kwanza", "ARS": "Argentine Peso", "AUD": "Australian Dollar", "AWG": "Aruban Florin", "AZN": "Azerbaijani Manat", "BAM": "Bosnia-Herzegovina Convertible Mark", "BBD": "Barbadian Dollar", "BDT": "Bangladeshi Taka", "BGN": "Bulgarian Lev", "BHD": "Bahraini Dinar", "BIF": "Burundian Franc", "BMD": "Bermudan Dollar", "BND": "Brunei Dollar", "BOB": "Bolivian Boliviano", "BRL": "Brazilian Real", "BSD": "Bahamian Dollar", "BTC": "Bitcoin", "BTN": "Bhutanese Ngultrum", "BWP": "Botswanan Pula", "BYR": "Belarusian Ruble", "BZD": "Belize Dollar", "CAD": "Canadian Dollar", "CDF": "Congolese Franc", "CHF": "Swiss Franc", "CLF": "Chilean Unit of Account (UF)", "CLP": "Chilean Peso", "CNY": "Chinese Yuan", "COP": "Colombian Peso", "CRC": "Costa Rican Colón", "CUP": "Cuban Peso", "CVE": "Cape Verdean Escudo", "CZK": "Czech Republic Koruna", "DJF": "Djiboutian Franc", "DKK": "Danish Krone", "DOP": "Dominican Peso", "DZD": "Algerian Dinar", "EEK": "Estonian Kroon", "EGP": "Egyptian Pound", "ERN": "Eritrean Nakfa", "ETB": "Ethiopian Birr", "EUR": "Euro", "FJD": "Fijian Dollar", "FKP": "Falkland Islands Pound", "GBP": "British Pound Sterling", "GEL": "Georgian Lari", "GGP": "Guernsey Pound", "GHS": "Ghanaian Cedi", "GIP": "Gibraltar Pound", "GMD": "Gambian Dalasi", "GNF": "Guinean Franc", "GTQ": "Guatemalan Quetzal", "GYD": "Guyanaese Dollar", "HKD": "Hong Kong Dollar", "HNL": "Honduran Lempira", "HRK": "Croatian Kuna", "HTG": "Haitian Gourde", "HUF": "Hungarian Forint", "IDR": "Indonesian Rupiah", "ILS": "Israeli New Sheqel", "IMP": "Manx pound", "INR": "Indian Rupee", "IQD": "Iraqi Dinar", "IRR": "Iranian Rial", "ISK": "Icelandic Króna", "JEP": "Jersey Pound", "JMD": "Jamaican Dollar", "JOD": "Jordanian Dinar", "JPY": "Japanese Yen", "KES": "Kenyan Shilling", "KGS": "Kyrgystani Som", "KHR": "Cambodian Riel", "KMF": "Comorian Franc", "KPW": "North Korean Won", "KRW": "South Korean Won", "KWD": "Kuwaiti Dinar", "KYD": "Cayman Islands Dollar", "KZT": "Kazakhstani Tenge", "LAK": "Laotian Kip", "LBP": "Lebanese Pound", "LKR": "Sri Lankan Rupee", "LRD": "Liberian Dollar", "LSL": "Lesotho Loti", "LTL": "Lithuanian Litas", "LVL": "Latvian Lats", "LYD": "Libyan Dinar", "MAD": "Moroccan Dirham", "MDL": "Moldovan Leu", "MGA": "Malagasy Ariary", "MKD": "Macedonian Denar", "MMK": "Myanma Kyat", "MNT": "Mongolian Tugrik", "MOP": "Macanese Pataca", "MRO": "Mauritanian Ouguiya", "MTL": "Maltese Lira", "MUR": "Mauritian Rupee", "MVR": "Maldivian Rufiyaa", "MWK": "Malawian Kwacha", "MXN": "Mexican Peso", "MYR": "Malaysian Ringgit", "MZN": "Mozambican Metical", "NAD": "Namibian Dollar", "NGN": "Nigerian Naira", "NIO": "Nicaraguan Córdoba", "NOK": "Norwegian Krone", "NPR": "Nepalese Rupee", "NZD": "New Zealand Dollar", "OMR": "Omani Rial", "PAB": "Panamanian Balboa", "PEN": "Peruvian Nuevo Sol", "PGK": "Papua New Guinean Kina", "PHP": "Philippine Peso", "PKR": "Pakistani Rupee", "PLN": "Polish Zloty", "PYG": "Paraguayan Guarani", "QAR": "Qatari Rial", "RON": "Romanian Leu", "RSD": "Serbian Dinar", "RUB": "Russian Ruble", "RWF": "Rwandan Franc", "SAR": "Saudi Riyal", "SBD": "Solomon Islands Dollar", "SCR": "Seychellois Rupee", "SDG": "Sudanese Pound", "SEK": "Swedish Krona", "SGD": "Singapore Dollar", "SHP": "Saint Helena Pound", "SLL": "Sierra Leonean Leone", "SOS": "Somali Shilling", "SRD": "Surinamese Dollar", "STD": "São Tomé and Príncipe Dobra", "SVC": "Salvadoran Colón", "SYP": "Syrian Pound", "SZL": "Swazi Lilangeni", "THB": "Thai Baht", "TJS": "Tajikistani Somoni", "TMT": "Turkmenistani Manat", "TND": "Tunisian Dinar", "TOP": "Tongan Paʻanga", "TRY": "Turkish Lira", "TTD": "Trinidad and Tobago Dollar", "TWD": "New Taiwan Dollar", "TZS": "Tanzanian Shilling", "UAH": "Ukrainian Hryvnia", "UGX": "Ugandan Shilling", "USD": "United States Dollar", "UYU": "Uruguayan Peso", "UZS": "Uzbekistan Som", "VEF": "Venezuelan Bolívar Fuerte", "VND": "Vietnamese Dong", "VUV": "Vanuatu Vatu", "WST": "Samoan Tala", "XAF": "CFA Franc BEAC", "XAG": "Silver (troy ounce)", "XAU": "Gold (troy ounce)", "XCD": "East Caribbean Dollar", "XDR": "Special Drawing Rights", "XOF": "CFA Franc BCEAO", "XPF": "CFP Franc", "YER": "Yemeni Rial", "ZAR": "South African Rand", "ZMK": "Zambian Kwacha (pre-2013)", "ZMW": "Zambian Kwacha", "ZWL": "Zimbabwean Dollar" } ================================================ FILE: config/pages.json ================================================ { "/*": "Index", "/wallets": "Wallets", "/profile": "Profile", "/plans": "Plans", "/plans/:id": "Plan", "/wallets/:id": "Wallet", "/wallets/:id/import": "ImportXLS", "/user/updatepassword/:code/:hash": "UpdatePassword", "/user/newpassword": "Index" } ================================================ FILE: config/resources.json ================================================ { "javascript": [ "./public/vendors/jquery/jquery.min.js", "./public/vendors/bootstrap/js/modal.js", "./public/vendors/bootstrap/js/button.js", "./public/vendors/bootstrap/js/dropdown.js", "./public/vendors/bootstrap/js/collapse.js", "./public/vendors/bootstrap/js/tooltip.js", "./public/vendors/bootstrap/js/popover.js", "./public/vendors/bootstrap-tour/build/js/bootstrap-tour.js", "./public/vendors/underscore/underscore-min.js", "./public/vendors/backbone/backbone.js", "./public/vendors/backbone.paginator/lib/backbone.paginator.min.js", "./public/vendors/bootstrap-clickonmouseover/bootstrap.clickonmouseover.js", "./public/vendors/magnific-popup/dist/jquery.magnific-popup.min.js", "./public/vendors/mprogress/build/js/mprogress.min.js", "./public/vendors/jsmart/jsmart.js", "./public/scripts/functions.js", "./public/scripts/app.js", "./public/scripts/app/helper.js", "./public/scripts/app/view_stack.js", "./public/scripts/app/settings.js", "./public/scripts/app/local_storage.js", "./public/scripts/app/template_manager.js", "./public/scripts/app/i18n.js", "./public/scripts/app/exchange.js", "./public/scripts/app/abstract/", "./public/scripts/app/models/", "./public/scripts/app/collections/", "./public/scripts/app/views/dialogs/", "./public/scripts/app/views/widgets/", "./public/scripts/app/views/parts/", "./public/scripts/app/views/pages/", "./public/scripts/app/views/tours/", "./public/scripts/app/views/charts/", "./public/scripts/app/views/header.js", "./public/scripts/app/log.js", "./public/scripts/app/router.js", "./public/scripts/setup.js" ], "css": [ "./public/vendors/mprogress/build/css/mprogress.css", "./public/vendors/magnific-popup/dist/magnific-popup.css", "./public/vendors/bootstrap/dist/css/bootstrap.min.css", "./public/vendors/font-awesome/css/font-awesome.css", "./public/vendors/bootstrap-tour/build/css/bootstrap-tour.min.css", "./public/vendors/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css", "./public/css/main.css", "./public/css/parts/", "./public/css/parts/dialogs/" ] } ================================================ FILE: data/cache/.gitignore ================================================ exchangerates.json api.apib ================================================ FILE: data/i18n/en.json ================================================ { "Nothing is found": "", "Add Income": "", "Amount": "", "Description": "", "Desciption": "", "Add": "", "Saving...": "", "Add Wallet": "", "Name": "", "Currency": "", "Select Currency": "", "Edit Wallet": "", "Save": "", "Fill Profile": "", "Username": "", "Email": "", "Password": "", "Invalid username or password": "", "Thank you! From now, you can sign in to your account any time from any device.": "", "Are you sure that you want to hide": "", "this wallet": "", "wallet": "", "Are you sure that you want to remove": "", "You will be able to restore it from Trash folder": "", "All wallet data(transactions etc.) will be lost": "", "Yes, Hide It": "", "Yes, Remove": "", "Removing...": "", "Cancel": "", "Canceling...": "", "Registration": "", "Sign Up": "", "Registration...": "", "Thank you! Please check your email inbox for confirmation link": "", "Already a member?": "", "Sign In": "", "Are you sure that you want to remove access for email": "", "from this wallet": "", "from wallet": "", "Are you sure that you want to remove this transaction?": "", "Restore Password": "", "Restore": "", "Processing...": "", "Instructions have been sent to your email address": "", "Don't have an account?": "", "Register": "", "Set Total To": "", "Total": "", "Set": "", "Username or Email": "", "Signing in...": "", "Restore your password": "", "Transaction Details": "", "Date": "", "Time": "", "Remove": "", "Users with access": "", "to this wallet": "", "to wallet": "", "Only you have access to this wallet": "", "Not registered yet": "", "Remove Access": "", "Add access": "", "Give Access": "", "January": "", "February": "", "March": "", "April": "", "May": "", "June": "", "July": "", "August": "", "September": "", "October": "", "November": "", "December": "", "january": "", "february": "", "march": "", "april": "", "may": "", "june": "", "july": "", "august": "", "september": "", "october": "", "november": "", "december": "", "Home": "", "Settings": "", "Your password has been successfully changed": "", "Invalid current password": "", "Passwords missmatch": "", "New password is too short": "", "Current Password": "", "New Password": "", "Repeat Password": "", "Change Password": "", "Update Password": "", "Invalid Restore Password Code": "", "Restore Password Code": "", "Restore Password Hash": "", "Your Wallets": "", "You have no wallets": "", "You have no hidden wallets": "", "Hide": "", "Edit": "", "Manage Accesses": "", "This wallet is shared with you by another user": "", "Filter": "", "Active": "", "Trash": "", "Access": "", "Both": "", "Yours": "", "Shared with you": "", "Wallets": "", "or": "", "set total to": "", "Transactions": "", "Describe expense and press Enter to add": "", "Transaction amount": "", "Expenses per day trends": "", "No transactions for": "", "Contact": "", "Log Out": "", "View Source on GitHub": "", "Copyright": "", "GNU Affero GPL License": "", "Change DimeShift language": "", "the easiest way to track your expenses": "", "To demonstrate how simple it is": "", "we don't even ask you to register": "", "Just move your mouse pointer over": "", "here": "", "and start using wallet right now!": "", "Just click": "", "Screenshots": "", "Easiest way to manage your personal finances online": "", "Simple as it is": "", "Any currency": "", "Create as many wallets as you need": "", "Internalization": "", "Just click on the globe icon in top right corner": "", "Open Source!": "", "GNU Affero GPL Licensed. Please feel free to check out the code and fork it!": "", "Please don't forget to let us know your email address, so you can sign in to DimeShift on your next visit": "", "Do it": "", "Here is quick introdution to DimeShift.

Our demo robot has created few sample wallets for you to check out.": "", "But you can add as many as you want.

Different name, different currencies": "", "There're few options availiable when you move your mouse over your wallet.

\n\tBut lets jump directly to wallet page.

Click any row to jump to it.\n\t": "", "Let's start by adding some money to your wallet.

Click \"Add Profit\" button and fill the form in modal window. It's simple.": "", "You can also set current total with \"Set Total To\" dialog.

\n\t\t\t\t\tWe don't ask you to track every transaction you've done(though you can). \n\t\t\t\t\tFeel free to update your DimeShift wallet every evening, or even once in few days.

\n\t\t\t\t\tClick \"set total to\" action link and fill the form to check how it works.": "", "It's time to add some expense.

\n\tYou can add transaction with one string, e.g. \"99.93, best expense ever\".

\n\tPress Enter when tranasction description is ready.\n\t": "", "Check out updated transactions list": "", "Check out expenses per day trends. Simple chart that gets updated every time you add another tranasction.": "", "Don't forget to fill your profile, so you can sign in to DimeShift next time.": "", "Select file": "", "Uploading...": "", "Do not import": "", "Expense amount": "", "Preview": "", "Import": "", "Back": "", "Import .xls file": "", "Step 1. Select .xls file to import": "", "Invalid xls file. Please select another one and try again": "", "Please select your local .xls file": "", "Step 2. Select columns to import": "", "more rows": "", "Amount and Date fields are required": "", "Few more rows": "", "Do not import transaction, if it's already in database": "", "Step 4. Import": "", "Finished": "", "Import operation is finished": "", "Check out you updated wallet": "", "Step 3. Preview and settings": "", "You don't have access to other users' wallets": "", "Goals": "", "Are you sure that you want to remove this plan?": "", "Plan name": "", "Plan your expenses": "", "Your plans": "", "View Report": "", "Create new": "", "Basic settings": "", "Wallets to use for planning": "", "Next": "", "Plan settings": "", "Current balance is": "", "Calculate in different currency": "", "And on": "", "Plan is to keep": "", "Set to": "", "So you": "", "can spend up to": "", "have to get": "", "on the next day": "", "in next": "", "days": "", "per day": "", "Confirm and save": "", "Goal Details": "", "From:": "", "To:": "", "From": "", "to": "", "Day by day report": "", "Total On Start": "", "Spent": "", "Profit": "", "Plan": "", "Remove account": "", "Security code": "", "Demo account will be removed as soon as you do log out from it.": "", "Please think twice. All account data will be lost.": "", "has been mailed to your email. Please fill this form to finish account removal.": "", "Your account has been removed. We will miss you :(": "", "Invalid": "", "There're no goals defined for this wallet": "", "Set Goal": "", "You": "", "today": "" } ================================================ FILE: data/i18n/ptbr.json ================================================ { "Nothing is found": "Sem resultado", "Add Income": "Adicionar Receita", "Amount": "Valor", "Description": "Descrição", "Desciption": "", "Add": "Adicionar", "Saving...": "Salvando...", "Add Wallet": "Adicionar Carteira", "Name": "Nome", "Currency": "Moeda", "Select Currency": "Selecionar Moeda", "Edit Wallet": "Editar Carteira", "Save": "Salvar", "Fill Profile": "Preencher Perfil", "Username": "Usuário", "Email": "Email", "Password": "Senha", "Invalid username or password": "Usuário ou senha inválidos", "Thank you! From now, you can sign in to your account any time from any device.": "Obrigado! A partir de agora, você pode fazer login na sua conta a qualquer momento a partir de qualquer dispositivo.", "Are you sure that you want to hide": "Tem certeza que você deseja ocultar", "this wallet": "esta carteira", "wallet": "carteira", "Are you sure that you want to remove": "Tem certeza que você deseja ocultar", "You will be able to restore it from Trash folder": "Você será capaz de restaurá-lo a partir da Lixeira", "All wallet data(transactions etc.) will be lost": "Todos os dados da carteira (transações etc.) serão perdidos", "Yes, Hide It": "Sim, oculte-o", "Yes, Remove": "Sim, Remover", "Removing...": "Removendo...", "Cancel": "Cancelar", "Canceling...": "Cancelando...", "Registration": "Registro", "Sign Up": "Inscrição", "Registration...": "Registro...", "Thank you! Please check your email inbox for confirmation link": "Obrigado! Por favor verifique sua caixa de entrada pelo link de confirmação", "Already a member?": "Já é membro", "Sign In": "Entrar", "Are you sure that you want to remove access for email": "Tem certeza de que deseja remover o acesso de e-mail?", "from this wallet": "desta carteira", "from wallet": "da carteira", "Are you sure that you want to remove this transaction?": "Tem certeza de que deseja remover esta transação?", "Restore Password": "Restaurar Senha", "Restore": "Restaurar", "Processing...": "Processando", "Instructions have been sent to your email address": "Instruções enviadas para seu email", "Don't have an account?": "Sem uma conta?", "Register": "Registrar", "Set Total To": "Definir Total Para", "Total": "Total", "Set": "Definir", "Username or Email": "Usuário ou Email", "Signing in...": "Entrando", "Restore your password": "Restaurar sua senha", "Transaction Details": "Detalhes da Transação", "Date": "Data", "Time": "Hora", "Remove": "Remover", "Users with access": "Usuários com acesso", "to this wallet": "para esta carteira", "to wallet": "para carteira", "Only you have access to this wallet": "Somente você tem acesso a esta carteira", "Not registered yet": "Não registrado ainda", "Remove Access": "Remover Acesso", "Add access": "Adicionar acesso", "Give Access": "Obter Acesso", "January": "Janeiro", "February": "Fevereiro", "March": "Março", "April": "Abril", "May": "Maio", "June": "Junho", "July": "Julho", "August": "Agosto", "September": "Setembro", "October": "Outubro", "November": "Novembro", "December": "Dezembro", "january": "janeiro", "february": "fevereiro", "march": "março", "april": "abril", "may": "maio", "june": "junho", "july": "julho", "august": "agosto", "september": "setembro", "october": "outubro", "november": "novembro", "december": "dezembro", "Home": "Home", "Settings": "Configurações", "Your password has been successfully changed": "Sua senha foi atualizada com sucesso", "Invalid current password": "Senha atual inválida", "Passwords missmatch": "Senhas incompatíveis", "New password is too short": "Nova senha é muito curta", "Current Password": "Senha Atual", "New Password": "NOva Senha", "Repeat Password": "Repetir Senha", "Change Password": "Alterar Senha", "Update Password": "Atualizar Senha", "Invalid Restore Password Code": "Código para restaurar senha inválido", "Restore Password Code": "Código para restaurar senha", "Restore Password Hash": "Hash para restaurar senha", "Your Wallets": "Suas Carteiras", "You have no wallets": "Você não possui carteiras", "You have no hidden wallets": "Você não possui carteiras ocultas", "Hide": "Ocultar", "Edit": "Editar", "Manage Accesses": "Gerenciar Acessos", "This wallet is shared with you by another user": "Esta carteira é compartilhada com você por outro usuário", "Filter": "Filtro", "Active": "Ativo", "Trash": "Lixo", "Access": "Acesso", "Both": "Ambos", "Yours": "Seus", "Shared with you": "Compartilhado com você", "Wallets": "Carteiras", "or": "ou", "set total to": "definir total para", "Transactions": "Transações", "Describe expense and press Enter to add": "Descreva a despesa e pressione Enter para adicionar", "Transaction amount": "Valor da transação", "Expenses per day trends": "Tendencia de despesas por dia", "No transactions for": "Sem transações para", "Contact": "Contato", "Log Out": "Encerrar", "View Source on GitHub": "Ver origem no GitHub", "Copyright": "Copyright", "GNU Affero GPL License": "GNU Affero GPL License", "Change DimeShift language": "Mudar linguagem DimeShift", "the easiest way to track your expenses": "A maneira mais simples de gerenciar suas finanças", "To demonstrate how simple it is": "Para demonstrar como é simples", "we don't even ask you to register": "Não pediremos para registrar", "Just move your mouse pointer over": "Basta mover o ponteiro do mouse sobre", "here": "aqui", "and start using wallet right now!": "e inicie usando a carteira agora mesmo!", "Just click": "Basta clicar", "Screenshots": "Screenshots", "Easiest way to manage your personal finances online": "Maneira mais fácil de gerenciar suas finanças pessoais on-line", "Simple as it is": "Simples como é", "Any currency": "Qualquer moeda", "Create as many wallets as you need": "Crie quantas carteiras precisar", "Internalization": "Internacioanlização", "Just click on the globe icon in top right corner": "", "Please don't forget to let us know your email address, so you can sign in to DimeShift on your next visit": "Por favor, não se esqueça de nos informar seu endereço de e-mail, para entrar em sua próxima visita a DimeShift", "Do it": "Faça", "Here is quick introdution to DimeShift.

Our demo robot has created few sample wallets for you to check out.": "Rápida introdução a DimeShift.
Different name, different currencies": "Mas você pode adicionar quantos você quiser.

Diferentes nomes e moedas", "There're few options availiable when you move your mouse over your wallet.

\n\tBut lets jump directly to wallet page.

Click any row to jump to it.\n\t": "Poucas opções são disponibilizadas quando você move o mouse sobre a sua carteira.

\n\tMas vamos pular diretamente para a página de carteira.

Clique em qualquer linha para saltar para ela.\n\t", "Let's start by adding some money to your wallet.

Click \"Add Profit\" button and fill the form in modal window. It's simple.": "Vamos começar adicionando um pouco de dinheiro para a sua carteira.

Clique o botão \"Adicionar Beneficio\" e preencha o formulário na janela. É simples.", "You can also set current total with \"Set Total To\" dialog.

\n\t\t\t\t\tWe don't ask you to track every transaction you've done(though you can). \n\t\t\t\t\tFeel free to update your DimeShift wallet every evening, or even once in few days.

\n\t\t\t\t\tClick \"set total to\" action link and fill the form to check how it works.": "Você pode definir o Total Atual com o diálogo \"Definir Total Para\".

\n\t\t\t\t\tNós não pedimos que você acompanhe todas as transações que você fez (embora você possa). \n\t\t\t\tSinta-se livre para atualizar sua carteira DimeShift todas as noites, ou mesmo uma vez em poucos dias.

\n\t\t\t\t\tClique no link \"Definir Total Para\" e preencha o formulário para ver como funciona.", "It's time to add some expense.

\n\tYou can add transaction with one string, e.g. \"99.93, best expense ever\".

\n\tPress Enter when tranasction description is ready.\n\t": "É hora de adicionar alguma despesa.

\n\tVocê pode adicionar transação com um simples texto,ex:\"99.93, melhor gasto\".

\n\tPressione Enter quando a descrição da transação estiver pronta.\n\t", "Check out updated transactions list": "Confira lista de transações atualizadas", "Check out expenses per day trends. Simple chart that gets updated every time you add another tranasction.": "Confira as tendências de despesas por dia. Gráfico simples que é atualizado cada vez que você adicionar uma outra transação.", "Don't forget to fill your profile, so you can sign in to DimeShift next time.": "Não se esqueça de preencher o seu perfil, de modo que você possa entrar na DimeShift da próxima vez.", "Select file": "Selecionar arquivo", "Uploading...": "Carregando...", "Do not import": "Não importar", "Expense amount": "Valor da despesa", "Preview": "Visualizar", "Import": "Importar", "Back": "Voltar", "Import .xls file": "Importar arquivo .xls", "Step 1. Select .xls file to import": "Passo 1. Selecionar arquivo .xls para importar", "Invalid xls file. Please select another one and try again": "Arquivo xls inválido. Por favor selecionar outro e tentar novamente", "Please select your local .xls file": "Selecionar o local do seu arquivo .xls", "Step 2. Select columns to import": "Passo 2. Selecionar colunas para importar", "more rows": "mais linhas", "Amount and Date fields are required": "Os campos valor e data são obrigatórios", "Few more rows": "Poucas linhas a mais", "Do not import transaction, if it's already in database": "Não importar transação, se ela já está no banco de dados", "Step 4. Import": "Passo 4. Importar", "Finished": "Terminado", "Import operation is finished": "Operação de importação concluída", "Check out you updated wallet": "Confira atualização de sua carteira", "Step 3. Preview and settings": "Passo 3. Configuração e Visualização", "Goals": "", "Are you sure that you want to remove this plan?": "", "Plan name": "", "Plan your expenses": "", "Your plans": "", "View Report": "", "Create new": "", "Basic settings": "", "Wallets to use for planning": "", "Next": "", "Plan settings": "", "Current balance is": "", "Calculate in different currency": "", "And on": "", "Plan is to keep": "", "Set to": "", "So you": "", "can spend up to": "", "have to get": "", "on the next day": "", "in next": "", "days": "", "per day": "", "Confirm and save": "", "Goal Details": "", "From:": "", "To:": "", "From": "", "to": "", "Day by day report": "", "Total On Start": "", "Spent": "", "Profit": "", "Plan": "", "Remove account": "", "Security code": "", "Demo account will be removed as soon as you do log out from it.": "", "Please think twice. All account data will be lost.": "", "has been mailed to your email. Please fill this form to finish account removal.": "", "Your account has been removed. We will miss you :(": "", "Invalid": "", "You don't have access to other users' wallets": "", "There're no goals defined for this wallet": "", "Set Goal": "", "You": "", "today": "" } ================================================ FILE: data/i18n/ru.json ================================================ { "Nothing is found": "Ничего не найдено", "Add Income": "Добавить доход", "Amount": "Сумма", "Description": "Описание", "Add": "Добавить", "Saving...": "Сохранение", "Add Wallet": "Добавить кошелек", "Name": "Название", "Currency": "Валюта", "Select Currency": "Выбрать валюту", "Edit Wallet": "Редактировать кошелек", "Save": "Сохранить", "Fill Profile": "Заполнить профиль", "Username": "Имя пользователя", "Email": "", "Password": "Пароль", "Invalid username or password": "Неправильное имя пользователя или пароль", "Thank you! From now, you can sign in to your account any time from any device.": "Спасибо! Теперь вы можете войти в ваш аккаунт с любого устройства.", "Are you sure that you want to hide": "Вы уверены что хотите скрыть", "this wallet": "этот кошелек", "wallet": "кошелек", "Are you sure that you want to remove": "Вы уверены что хотите удалить", "You will be able to restore it from Trash folder": "Вы сможете восстановить его из Корзины", "All wallet data(transactions etc.) will be lost": "Все данные, включая транзакции, будут утеряны", "Yes, Hide It": "Да, спрятать", "Yes, Remove": "Да, удалить", "Removing...": "Удаление...", "Cancel": "Отмена", "Canceling...": "Отмена...", "Registration": "Регистрация", "Sign Up": "Зарегистрироваться", "Registration...": "Регистрация...", "Thank you! Please check your email inbox for confirmation link": "Спасибо. Мы отправили вам письмо с ссылкой для подтверждения вашей учетной записи", "Already a member?": "Уже зарегистрированы?", "Sign In": "Войти", "Are you sure that you want to remove access for email": "Вы уверены что хотите удалить доступ для email", "from this wallet": "для этого кошелька", "from wallet": "для кошелька", "Are you sure that you want to remove this transaction?": "Вы уверены что хотите удалить эту транзакцию?", "Restore Password": "Восстановить пароль", "Restore": "Восттановить", "Processing...": "Обработка...", "Instructions have been sent to your email address": "Инструкции отправлены на вашу электронную почту", "Don't have an account?": "Еще нет учетной записи?", "Register": "Зарегистрироваться", "Set Total To": "Установить текущую сумму", "Total": "Итого", "Set": "Установить", "Username or Email": "Имя пользователя или пароль", "Signing in...": "Проверка...", "Restore your password": "Восттановить ваш пароль", "Transaction Details": "Детали транзакции", "Date": "Дата", "Time": "Время", "Remove": "Удалить", "Users with access": "Пользователи с доступом", "to this wallet": "к этому кошельку", "to wallet": "к кошельку", "Only you have access to this wallet": "Только у вас есть доступ", "Not registered yet": "Еще не зарегистрирован", "Remove Access": "Лишить доступа", "Add access": "Предоставить доступ", "Give Access": "Предоставить доступ", "January": "Январь", "February": "Февраль", "March": "Март", "April": "Апрель", "May": "Май", "June": "Июнь", "July": "Июль", "August": "Август", "September": "Сентябрь", "October": "Октябрь", "November": "Ноябрь", "December": "Декабрь", "january": "января", "february": "февраля", "march": "марта", "april": "апреля", "may": "мая", "june": "июня", "july": "июля", "august": "августа", "september": "сентября", "october": "октября", "november": "ноября", "december": "декабря", "Home": "Главная", "Settings": "Настройки", "Your password has been successfully changed": "Пароль успешно изменен", "Invalid current password": "Неверный текущий пароль", "Passwords missmatch": "Пароли не совпадают", "New password is too short": "Новый пароль слишком короткий", "Current Password": "Текущий пароль", "New Password": "Новый пароль", "Repeat Password": "Повторить новый пароль", "Change Password": "Изменить пароль", "Update Password": "Изменить пароль", "Invalid Restore Password Code": "Неверный код восстановления пароля", "Restore Password Code": "Код восстановления пароля", "Restore Password Hash": "Хэш восстановления пароля", "Your Wallets": "Ваши кошельки", "You have no wallets": "У вас нет кошельков", "You have no hidden wallets": "У вас нет скрытых кошельков", "Hide": "Спрятать", "Edit": "Редактировать", "Manage Accesses": "Управление доступом", "This wallet is shared with you by another user": "Доступ к этому кошельку предоставлен другим пользователем", "Filter": "Фильтр", "Active": "Активные", "Trash": "Корзина", "Access": "Доступ", "Both": "Все", "Yours": "Ваши", "Shared with you": "Доступные вам", "Wallets": "Кошельки", "or": "или", "set total to": "установить текущую сумму", "Transactions": "Транзакции", "Describe expense and press Enter to add": "Опишите транзакцию и нажмите Enter", "Transaction amount": "Сумма операции", "Expenses per day trends": "Тенденции дневных расходов", "No transactions for": "Нет транзакций за", "Contact": "Написать нам", "Log Out": "Выйти", "View Source on GitHub": "Исходный код на GitHub", "Copyright": "Разработано в", "GNU Affero GPL License": "под лицензией GNU Affero GPL", "Change DimeShift language": "Выбрать язык интерфейса", "the easiest way to track your expenses": "самый простой способ вести учет финансов", "To demonstrate how simple it is": "Чтобы показать насколько", "we don't even ask you to register": "мы даже не просим вас вводить данные в форму регистрации", "Just move your mouse pointer over": "Просто наведите указатель мыши", "here": "сюда", "and start using wallet right now!": "и начните использовать DimeShift уже сейчас!", "Just click": "Просто нажмите", "Screenshots": "Скриншоты", "Easiest way to manage your personal finances online": "Самый простой способ упорядочить ваши финансы", "Simple as it is": "Проще не придумаешь", "Any currency": "Любая валюта", "Create as many wallets as you need": "Создавайте сколь угодно много кошельков", "Internalization": "Локализации", "Just click on the globe icon in top right corner": "Доступны несколько языков интерфейса", "Please don't forget to let us know your email address, so you can sign in to DimeShift on your next visit": "Пожалуйста, заполните ваш профиль, чтобы вы смогли войти в вашу учетную запись в следующий раз", "Do it": "Заполнить", "Here is quick introdution to DimeShift.

Our demo robot has created few sample wallets for you to check out.": "Позвольте нам провести небольшой тур по основным функциям DimeShift

Наш робот создал пару тестовых кошельков для тестирования.", "But you can add as many as you want.

Different name, different currencies": "Но вы можете создать их столько, сколько захотите.

В любой валюте, с любым названием.", "There're few options availiable when you move your mouse over your wallet.

\n\tBut lets jump directly to wallet page.

Click any row to jump to it.\n\t": "Наведите указатель на строку с названием кошелька и появятся кнопки с дополнительными функциями.

Но давайте сразу перейдем на страницу кошелька. Нажмите на любой кошелек, чтобы продолжить.", "Let's start by adding some money to your wallet.

Click \"Add Profit\" button and fill the form in modal window. It's simple.": "Давайте для начала добавим в кошелек немного денег :)

Нажмите на эту кнопку и заполните небольшую форму во всплывающем окне. Это просто.", "You can also set current total with \"Set Total To\" dialog.

\n\t\t\t\t\tWe don't ask you to track every transaction you've done(though you can). \n\t\t\t\t\tFeel free to update your DimeShift wallet every evening, or even once in few days.

\n\t\t\t\t\tClick \"set total to\" action link and fill the form to check how it works.": "В отличии от других подобных систем, Dimeshift разрабатывали реалисты. Мы не просим вас вводить данные о каждой транзакции, иногда бывает проще в какой-то момент установить текущую сумму.

Это можно делать каждый вечер или даже раз в несколько дней.

Если вдруг вы забыли о своем решении вести учет, а через время вернулись к этой идее - не страшно, возвращайтесь к своим кошелькам в любое время.", "It's time to add some expense.

\n\tYou can add transaction with one string, e.g. \"99.93, best expense ever\".

\n\tPress Enter when tranasction description is ready.\n\t": "Настало время указать расходы.

Можно описать транзакцию в одну строку, например '99.99, лучшая трата в моей жизни'

Нажмите Enter, когда будет готово", "Check out updated transactions list": "Список транзакций обновился", "Check out expenses per day trends. Simple chart that gets updated every time you add another tranasction.": "Каждая транзакция отображается на графике, наглядно показывая ваши траты", "Don't forget to fill your profile, so you can sign in to DimeShift next time.": "Заполните ваш профиль, чтобы иметь возможность войти в него снова", "Select file": "Выбрать файл", "Uploading...": "Загрузка...", "Do not import": "Не имортировать", "Expense amount": "Сумма траты", "Preview": "Предпросмотр", "Import": "Импорт", "Back": "Назад", "Import .xls file": "Импорт файла Excel", "Step 1. Select .xls file to import": "Шаг 1. Выберите файл для импорта", "Invalid xls file. Please select another one and try again": "Неверный формат файла. Попробуйте загрузить другой файл", "Please select your local .xls file": "Выберите .xls файл на вашем компьютере", "Step 2. Select columns to import": "Шаг 2. Веберите столбцы для импорта", "more rows": "дополнительных строк", "Amount and Date fields are required": "Обязательные столбцы: сумма и дата", "Few more rows": "Еще несколько строк", "Do not import transaction, if it's already in database": "Не импортировать транзакцию, если она уже есть в базе данных", "Step 4. Import": "Шаг 4. Импорт", "Finished": "Завершено", "Import operation is finished": "Импорт завершен", "Check out you updated wallet": "Просмотрите ваш обновленный кошелек", "Step 3. Preview and settings": "Шаг 3. Предпросмотр", "You don't have access to other users' wallets": "У вас нет доступа к кошелькам других пользователей", "Goals": "Цели", "Are you sure that you want to remove this plan?": "Вы уверены, что хотите удалить эту цель?", "Plan name": "Название цели", "Plan your expenses": "Планирование расходов", "Your plans": "Ваши цели", "View Report": "Просмотреть отчет", "Create new": "Создать новую", "Basic settings": "Основные настройки", "Wallets to use for planning": "Кошельки для планирования", "Next": "Далее", "Plan settings": "Настройки цели", "Current balance is": "Текущий баланс", "Calculate in different currency": "Пересчитать в другой валюте", "And on": "И на дату", "Plan is to keep": "Баланс должен быть", "Set to": "Установить в", "So you": "Итак, вы", "can spend up to": "можете потратить до", "have to get": "должны добавить", "on the next day": "завтра", "in next": "в следующие", "days": "дней", "per day": "в день", "Confirm and save": "Подтвердить и сохранить", "Goal Details": "Детали Цели", "From:": "От:", "To:": "До:", "From": "От", "to": "до", "Day by day report": "Отчёт по дням", "Total On Start": "Баланс в начале дня", "Spent": "Траты", "Profit": "Доход", "Plan": "Цель", "Remove account": "Удалить учетную запись", "Security code": "Код безопасности", "Demo account will be removed as soon as you do log out from it.": "Демострационный аккаунт будет удален после завершения текущей сессии", "Please think twice. All account data will be lost.": "Уверены? Все данные будут удалены безвозвратно.", "has been mailed to your email. Please fill this form to finish account removal.": "был отправлен на ваш email. Заполните эту форму и завершите процедуру удаления", "Your account has been removed. We will miss you :(": "Аккаунт удалён. Печалька :( Мы будем скучать.", "Invalid": "Неверный", "There're no goals defined for this wallet": "Для этого кошелька не определены цели", "Set Goal": "Установить цель", "You": "Вы", "today": "сегодня" } ================================================ FILE: data/i18n/ua.json ================================================ { "Nothing is found": "Нічого не знайдено", "Add Income": "Додати прибуток", "Amount": "Сума", "Description": "Опис", "Add": "Додати", "Saving...": "Збереження...", "Add Wallet": "Додати гаманець", "Name": "Ім’я", "Currency": "Валюта", "Select Currency": "Вибрати валюту", "Edit Wallet": "Редагувати гаманець", "Save": "Зберегти", "Fill Profile": "Заповнити профіль", "Username": "Ім’я користувача", "Email": "", "Password": "Пароль", "Invalid username or password": "Невірне ім’я користувача або пароль", "Thank you! From now, you can sign in to your account any time from any device.": "Дякуємо! Відтепер, ви можете увійти в свій обліковий запис в будь-який час з будь-якого пристрою.", "Are you sure that you want to hide": "Ви впевнені, що ви хочете приховати", "this wallet": "цей гаманець", "wallet": "гаманець", "Are you sure that you want to remove": "Ви впевнені, що ви хочете видалити", "You will be able to restore it from Trash folder": "Ви зможете відновити його з папки Приховані", "All wallet data(transactions etc.) will be lost": "Всі дані гаманця будуть втрачені", "Yes, Hide It": "Так, приховати", "Yes, Remove": "Так, видалити", "Removing...": "Обробка...", "Cancel": "Скасувати", "Canceling...": "Скасування...", "Registration": "Реєстрація", "Sign Up": "Зареєструватися", "Registration...": "Реєстрація...", "Thank you! Please check your email inbox for confirmation link": "Дякуємо! Будь ласка, перевірте свою поштову скриньку. Ми відправили вам повідомлення з посиланням підтвердження вашого облікового запису", "Already a member?": "Вже зареєстровані?", "Sign In": "Увійти", "Are you sure that you want to remove access for email": "Ви впевнені, що хочете видалити доступ для цієї електронної пошти", "from this wallet": "для цього гаманця", "from wallet": "для гаманця", "Are you sure that you want to remove this transaction?": "Ви впевнені, що хочете видалити цю транзакцію?", "Restore Password": "Відновити пароль", "Restore": "Відновити", "Processing...": "Обробка...", "Instructions have been sent to your email address": "Інструкції були відправлені на вашу електронну пошту", "Don't have an account?": "Не маєте облікового запису?", "Register": "Зареєструватися", "Set Total To": "Встановити загальну суму у", "Total": "Загальна сума", "Set": "Встановити", "Username or Email": "Ім’я користувача або електронна пошта", "Signing in...": "Обробка...", "Restore your password": "Відновити пароль", "Transaction Details": "Деталі транзакції", "Date": "Дата", "Time": "Час", "Remove": "Видалити", "Users with access": "Користувачі з доступом", "to this wallet": "до цього гаманця", "to wallet": "до гаманця", "Only you have access to this wallet": "Тільки ви маєте доступ до цього гаманця", "Not registered yet": "Поки що не зареєстрований", "Remove Access": "Видалити доступ", "Add access": "Дозволити доступ", "Give Access": "Дозволити доступ", "January": "Січень", "February": "Лютий", "March": "Березень", "April": "Квітень", "May": "Травень", "June": "Червень", "July": "Липень", "August": "Серпень", "September": "Вересень", "October": "Жовтень", "November": "Листопад", "December": "Грудень", "january": "січня", "february": "лютого", "march": "березня", "april": "квітня", "may": "травня", "june": "червня", "july": "липня", "august": "серпня", "september": "вересня", "october": "жовтня", "november": "листопада", "december": "грудня", "Home": "Головна", "Settings": "Налаштування", "Your password has been successfully changed": "Ваш пароль змінено", "Invalid current password": "Невірний поточний пароль", "Passwords missmatch": "Паролі не збігаються", "New password is too short": "Новий пароль занадто короткий", "Current Password": "Поточний пароль", "New Password": "Новий пароль", "Repeat Password": "Повторити новий пароль", "Change Password": "Змінитити пароль", "Update Password": "Змінитити пароль", "Invalid Restore Password Code": "Невірний код відновлення", "Restore Password Code": "Код відновлення", "Restore Password Hash": "Хеш відновлення", "Your Wallets": "Ваші гаманці", "You have no wallets": "У вас немає гаманців", "You have no hidden wallets": "У вас немає прихованих гаманців", "Hide": "Приховати", "Edit": "Редагувати", "Manage Accesses": "Доступ", "This wallet is shared with you by another user": "Доступ до цього гаманця надано іншим користувачем", "Filter": "Фільтр", "Active": "Активні", "Trash": "Приховані", "Access": "Доступ", "Both": "Будь-які", "Yours": "Ваші", "Shared with you": "Інших користувачів", "Wallets": "Гаманці", "or": "чи", "set total to": "встановити загальну суму у", "Transactions": "Транзакції", "Describe expense and press Enter to add": "Опишіть витрату і натисніть Enter", "Transaction amount": "Сума транзакції", "Expenses per day trends": "Тенденції витрат за день", "No transactions for": "Немає транзакцій за", "Contact": "Зв’язатися з нами", "Log Out": "Вийти", "View Source on GitHub": "Код на GitHub", "Copyright": "Розроблено у", "GNU Affero GPL License": "ліцензія GNU Affero GPL", "Change DimeShift language": "Змінитити мову", "the easiest way to track your expenses": "найпростіший спосіб ведення обліку фінансів", "To demonstrate how simple it is": "Щоб продемонструвати як це просто", "we don't even ask you to register": "ми навіть не просимо вас зареєструватися", "Just move your mouse pointer over": "Просто наведіть курсор миші", "here": "сюди", "and start using wallet right now!": "і почніть використовувати DimeShift прямо зараз!", "Just click": "Просто натисніть", "Screenshots": "Скріншоти", "Easiest way to manage your personal finances online": "", "Simple as it is": "", "Any currency": "", "Create as many wallets as you need": "", "Internalization": "", "Just click on the globe icon in top right corner": "", "Please don't forget to let us know your email address, so you can sign in to DimeShift on your next visit": "Будь ласка, заповніть ваш профіль, щоб ви змогли увійти в ваш обліковий запис наступного разу", "Do it": "Заповнити", "Here is quick introdution to DimeShift.

Our demo robot has created few sample wallets for you to check out.": "Дозвольте нам провести невеликий тур по основним функціям DimeShift.

Наш робот створив пару тестових гаманців для тестування.", "But you can add as many as you want.

Different name, different currencies": "Але ви можете створити їх стільки, скільки забажаєте.

У будь-якій валюті, з будь-якою назвою.", "There're few options availiable when you move your mouse over your wallet.

\n\tBut lets jump directly to wallet page.

Click any row to jump to it.\n\t": "Наведіть курсор на рядок з назвою гаманця і з'являться кнопки з додатковими функціями.

Але спочатку перейдімо на сторінку гаманця. Натисніть на будь-який гаманець, щоб продовжити.", "Let's start by adding some money to your wallet.

Click \"Add Profit\" button and fill the form in modal window. It's simple.": "Для початку додамо в гаманець трохи грошей :)

Натисніть на цю кнопку і заповніть невелику форму у спливаючому віконці. Це просто.", "You can also set current total with \"Set Total To\" dialog.

\n\t\t\t\t\tWe don't ask you to track every transaction you've done(though you can). \n\t\t\t\t\tFeel free to update your DimeShift wallet every evening, or even once in few days.

\n\t\t\t\t\tClick \"set total to\" action link and fill the form to check how it works.": "На відміну від інших подібних систем, DimeShift розробляли реалісти. Ми не просимо вас вводити дані про кожну транзакцію, іноді буває простіше в якийсь момент встановити поточну суму.

Це можна робити щовечора або навіть раз на кілька днів.

Якщо раптом ви забули про своє рішення вести облік, а через час повернулися до цієї ідеї - все окей, повертайтеся до своїх гаманців в будь-який час.", "It's time to add some expense.

\n\tYou can add transaction with one string, e.g. \"99.93, best expense ever\".

\n\tPress Enter when tranasction description is ready.\n\t": "Настав час вказати витрати.

Можна описати транзакцію в один рядок, наприклад '99.99, краща трата в моєму житті'

Натисніть Enter, коли опис буде готовим", "Check out updated transactions list": "Список транзакцій оновився", "Check out expenses per day trends. Simple chart that gets updated every time you add another tranasction.": "Кожна транзакція відображається на графіку, наочно демонструючі ваші витрати", "Don't forget to fill your profile, so you can sign in to DimeShift next time.": "Заповніть ваш профіль, щоб мати можливість увійти до нього наступного разу", "Select file": "Вибрати файл", "Uploading...": "Завантаження...", "Do not import": "Не імпортувати", "Expense amount": "Сума витрати", "Preview": "Переглянути", "Import": "Імпорт", "Back": "Назад", "Import .xls file": "Імпорт файла Excel", "Step 1. Select .xls file to import": "Крок 1. Вибрати файл", "Invalid xls file. Please select another one and try again": "Невірний формат файлу. Спробуйте інший файл", "Please select your local .xls file": "Завантажте файл .xls з вашого комп’ютеру", "Step 2. Select columns to import": "Крок 2. Вибрати сповпці для імпорту", "more rows": "додаткових строк", "Amount and Date fields are required": "Обов'язкові стовпці: сума і дата", "Few more rows": "Ще кілька рядків", "Do not import transaction, if it's already in database": "Не імпортувати транзакцію, якщо вона вже є в базі даних", "Step 4. Import": "Крок 4. Імпорт", "Finished": "Завершено", "Import operation is finished": "Імпорт завершений", "Check out you updated wallet": "Перегляньте ваш оновлений гаманець", "Step 3. Preview and settings": "Крок 3. Перегляд", "You don't have access to other users' wallets": "Інші користувачі не надавали вам доступ до своїх гаманців", "Goals": "Цілі", "Are you sure that you want to remove this plan?": "Ви впевнені, що хочете видалити цю ціль?", "Plan name": "Назва цілі", "Plan your expenses": "Планування витрат", "Your plans": "Ваші цілі", "View Report": "Звіт", "Create new": "Додати нову", "Basic settings": "Основні налаштування", "Wallets to use for planning": "Гаманці для планування", "Next": "Далі", "Plan settings": "Налаштування цілі", "Current balance is": "Поточний баланс", "Calculate in different currency": "Перерахувати в іншій валюті", "And on": "І на дату", "Plan is to keep": "Баланс повинен становити", "Set to": "Встановити у", "So you": "Отже, ви", "can spend up to": "можете витратити", "have to get": "повинні додати", "on the next day": "завтра", "in next": "у наступні", "days": "днів", "per day": "у день", "Confirm and save": "Підтвердити і зберегти", "Goal Details": "Деталі цілі", "From:": "Від:", "To:": "До:", "From": "Від", "to": "до", "Day by day report": "Звіт по днях", "Total On Start": "Баланс на початку дня", "Spent": "Витрати", "Profit": "Дохід", "Plan": "Ціль", "Remove account": "Видалити аккаунт", "Security code": "Код безпеки", "Demo account will be removed as soon as you do log out from it.": "Демостраціонний аккаунт буде видалений після завершення поточної сесії", "Please think twice. All account data will be lost.": "Впевнені? Усі дані будуть видалені безповоротно.", "has been mailed to your email. Please fill this form to finish account removal.": "був відправлений на ваш email. Заповніть цю форму і завершіть процедуру видалення", "Your account has been removed. We will miss you :(": "Аккаунт видалений :( Шкода, повертайтеся при першій нагоді, будемо чекати.", "Invalid": "Невірній", "There're no goals defined for this wallet": "Для цього гаманця не визначені цілі", "Set Goal": "Встановити ціль", "You": "Ви", "today": "сьогодні" } ================================================ FILE: data/mailtemplates/registration.template ================================================ Thank you for joining DimeShift
$ dimeshift

We appreciate your interest.

- The DimeShift Team

================================================ FILE: data/mailtemplates/remove_account.template ================================================ Remove your DimeShift account
$ dimeshift

Hi %login%,

Here's your code to remove DimeShift account: %remove_account_code%

 

- The DimeShift Team

================================================ FILE: data/mailtemplates/restore_password.template ================================================ Restore your DimeShift password
$ dimeshift

Hi %login%,

Use this link to restore your password: %site_path%user/updatepassword/%password_restore_code%/%password_restore_hash%

 

- The DimeShift Team

================================================ FILE: data/min/.gitignore ================================================ * !.gitignore ================================================ FILE: docs/api.md ================================================ FORMAT: 1A HOST: http://dimeshift.com/ # DimeShift [DimeShift](http://dimeshift.com) ([github.com/jeka-kiselyov/dimeshift](https://github.com/jeka-kiselyov/dimeshift)) DimeShift API is simple. You'll love it. # Authentication Set authCode HTTP header for authentication. Obtain authCode with Create a New User or Authenticate User methods. ``` request.setRequestHeader('authCode', '421a5bbd0624efebf12b2cbe5454b753'); ``` ================================================ FILE: includes/api.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var fs = require('fs'); var path = require('path'); var getVisitorIp = function(req) { var ipAddr = req.headers["x-forwarded-for"]; if (ipAddr) { var list = ipAddr.split(","); ipAddr = list[list.length - 1]; } else { ipAddr = req.connection.remoteAddress; } return ipAddr; }; exports.requireSignedIn = function(req, callback) { var cookies = req.cookies; var auth_code = cookies.logged_in_user || ''; var ip = getVisitorIp(req); if (auth_code === '') throw new errors.HaveNoRightsError(); db.User.getByAuthCode({ auth_code: auth_code, ip: ip }).then(function(user) { if (typeof(callback) == 'function') callback(user); }, function(err) { throw new errors.HaveNoRightsError(); }); }; exports.getVisitorIp = getVisitorIp; var i18n_path = path.join(__dirname, '../data/i18n'); var i18n_cache = {}; exports.geti18njson = function(code) { if (typeof(i18n_cache[code]) !== 'undefined') return i18n_cache[code]; i18n_cache[code] = fs.readFileSync(path.join(i18n_path, code + '.json'), 'utf8'); return i18n_cache[code]; }; var getParam = function(req, name, def) { if (typeof(req.body) !== 'undefined' && typeof(req.body[name]) !== 'undefined') return req.body[name]; else if (typeof(req.params) !== 'undefined' && typeof(req.params[name]) !== 'undefined') return req.params[name]; else return def; }; exports.getParam = getParam; ================================================ FILE: includes/config.js ================================================ var rfr = require('rfr'); var env = process.env.NODE_ENV || 'development'; var config = rfr('config/config.json'); var net = require('net'); if (typeof(config[env]) == 'undefined') config = config['development']; else config = config[env]; config['env'] = env; config['resources'] = rfr('config/resources.json'); if (config['port'] === 0) { var portrange = 45032 function getPort(cb) { var port = portrange portrange += 1 var server = net.createServer() server.listen(port, function(err) { server.once('close', function() { cb(port) }) server.close() }) server.on('error', function(err) { getPort(cb) }) } config['port'] = getPort; } module.exports = config; ================================================ FILE: includes/demo.js ================================================ var sequelize = require('sequelize'); exports.fillDemoAccount = function(user, callback) { return new sequelize.Promise(function(resolve, reject) { var rand = function(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } var currency = 'USD'; var wallet_1_name = 'Sample Cash Wallet'; var wallet_2_name = 'Sample Bank Account Wallet'; var initial_1_description = 'Profit'; var initial_2_description = 'My freelance work'; var initial_1_amount = 4000 + rand(0, 50) * 100; var initial_2_amount = 3000 + rand(0, 50) * 100; var now = Date.now() / 1000 | 0; var descriptions_1 = [ 'Vodka', 'Beer', 'Candies', 'Date with Sammy', 'Sausages', 'Food', 'Foods', 'Eat out', 'Mall', 'Cinema', 'Gas', 'Wi-Fi access', 'Wi-Fi', 'Wine' ]; var descriptions_2 = [ 'Hosting', 'Custom Software', 'Amazon S3', 'Amazon AWS', 'Wordpress template', 'Translations', 'Data Gathering', 'CSS work', 'Adwords', 'PPC Campaign', 'PPM Campaign', 'Content writing', 'iStock', 'Shutterstock', 'Gettyimages', 'Photobank' ]; var t_to_add_1 = []; var total_1 = initial_1_amount; t_to_add_1.push({ amount: initial_1_amount, description: initial_1_description, datetime: now - 70 * 24 * 60 * 60 }); for (var i = 29; i > 0; i--) { var amount = rand(0, (initial_1_amount / 30)) + (rand(0, 100) * 0.01); var description = descriptions_1[Math.floor(Math.random() * descriptions_1.length)]; var datetime = now - ((i - rand(0, 80) * 0.01) * 24 * 60 * 60); total_1 = total_1 - amount; t_to_add_1.push({ amount: -amount, description: description, datetime: datetime }); if (total_1 < 300) { var amount = rand(100, 1000); t_to_add_1.push({ amount: amount, description: initial_1_description, datetime: datetime + rand(10, 1000) }); total_1 = total_1 + amount; } } var t_to_add_2 = []; var total_2 = initial_2_amount; t_to_add_2.push({ amount: initial_2_amount, description: initial_2_description, datetime: now - 50 * 24 * 60 * 60 }); for (var i = 19; i > 0; i--) { var amount = rand(10, 11 + (initial_2_amount / 20)); var description = descriptions_2[Math.floor(Math.random() * descriptions_2.length)]; var datetime = now - ((i - rand(0, 80) * 0.01) * 24 * 60 * 60); if (rand(0, 5) === 1) amount = amount - 0.01; total_2 = total_2 - amount; t_to_add_2.push({ amount: -amount, description: description, datetime: datetime }); if (total_2 < 1000) { var amount = rand(1, 10) * 100; t_to_add_2.push({ amount: amount, description: initial_2_description, datetime: datetime + rand(10, 1000) }); total_2 = total_2 + amount; } } sequelize.Promise.map([wallet_1_name, wallet_2_name], function(name) { return user.createWallet({ name: name, currency: currency }); }).spread(function(wallet_1, wallet_2) { /// @todo: do with raw query. Too slow now. sequelize.Promise.map(t_to_add_1, function(data) { return wallet_1.insertTransaction({ description: data.description, amount: data.amount, datetime: data.datetime }); }).then(function() { sequelize.Promise.map(t_to_add_2, function(data) { return wallet_2.insertTransaction({ description: data.description, amount: data.amount, datetime: data.datetime }); }).then(function() { resolve(); }); }); }); }); } ================================================ FILE: includes/errors.js ================================================ var restify = require('restify'); var util = require('util'); var restifyErrors = require('restify-errors'); function ValidationError(err) { restifyErrors.RestError.call(this, { restCode: 'ValidationError', statusCode: 666, message: [], constructorOpt: ValidationError }); this.name = 'ValidationError'; if (typeof(err.errors) !== 'undefined') { for (var k in err.errors) this.message.push(err.errors[k].message); } else { console.log(err); this.message.push("" + err); } }; util.inherits(ValidationError, restifyErrors.RestError); function HaveNoRightsError() { restifyErrors.RestError.call(this, { restCode: 'HaveNoRightsError', statusCode: 6969, message: 'You have no rights to call this API method with this parameters. Try to check auth hash', constructorOpt: HaveNoRightsError }); this.name = 'HaveNoRightsError'; }; util.inherits(HaveNoRightsError, restifyErrors.RestError); function NotFoundError() { restifyErrors.RestError.call(this, { restCode: 'NotFoundError', statusCode: 404, message: 'Nothing is found. Please check item id', constructorOpt: NotFoundError }); this.name = 'NotFoundError'; }; util.inherits(NotFoundError, restifyErrors.RestError); exports.ValidationError = ValidationError; exports.HaveNoRightsError = HaveNoRightsError; exports.NotFoundError = NotFoundError; ================================================ FILE: includes/exchange.js ================================================ var path = require('path'); var oxr = require('open-exchange-rates'); var fx = require('money'); var fs = require('fs'); var rfr = require('rfr'); var config = rfr('includes/config.js'); var openExchangeRatesAppId = null; var openExchangeRatesUpdateInterval = null; if (config.openexchangerates) { openExchangeRatesAppId = config.openexchangerates.app_id || ''; openExchangeRatesUpdateInterval = config.openexchangerates.update_interval || 86400; if (config.openexchangerates.use_env_variable) openExchangeRatesAppId = process.env[openExchangeRatesAppId]; } var cache_filename = path.join(__dirname, '..', 'data/cache/exchangerates.json'); var cached = null; var reloadRates = function(callback) { if (!openExchangeRatesAppId) { console.error("Please specify openexchangerates -> app_id in config.json to enable currency conversion"); if (typeof(callback) === 'function') callback(cached); } oxr.latest(function() { cached = {}; cached.rates = oxr.rates; cached.base = oxr.base; fs.writeFile(cache_filename, JSON.stringify(cached, null, 2), function(){ if (typeof(callback) === 'function') callback(cached); }); }); }; var reloadIfNeeded = function(callback) { fs.stat(cache_filename, function(err, stats) { if (!stats || (stats.mtime.getTime() / 1000) < (Date.now() / 1000 | 0) - openExchangeRatesUpdateInterval) { reloadRates(callback); } }); }; var cached = { rates: {}, base: 'USD' }; oxr.set({ app_id: openExchangeRatesAppId }); try { cached = JSON.parse("" + fs.readFileSync(cache_filename, 'utf8')); } catch (e) { console.log("No cached exchange rates\n"); } if (cached && typeof(cached.rates) !== 'undefined' && typeof(cached.base) !== 'undefined') { fx.rates = cached.rates; fx.base = cached.base; reloadIfNeeded(); } else { reloadRates(function() { fx.rates = cached.rates; fx.base = cached.base; }); } var getRates = function() { reloadIfNeeded(); return cached; }; var convert = function(value, from, to) { var ret = value; try { ret = fx(value).from(from).to(to); } catch (e) { ret = value; } return ret; }; exports.fx = fx; exports.convert = convert; exports.getRates = getRates; // fx(100).from('HKD').to('GBP'); // ~8.0424 ================================================ FILE: includes/mailer.js ================================================ var nodemailer = require('nodemailer'); var rfr = require('rfr'); var fs = require('fs'); var config = rfr('includes/config.js'); var transporter = null; if (config && config.smtp) { if (config.smtp.use_env_variables) { transporter = nodemailer.createTransport({ host: process.env[config.smtp.host], port: process.env[config.smtp.port], auth: { user: process.env[config.smtp.username], pass: process.env[config.smtp.password] } }); } else { transporter = nodemailer.createTransport({ host: config.smtp.host, port: config.smtp.port, auth: { user: config.smtp.username, pass: config.smtp.password } }); } if (config.default_from_email) transporter.default_from_email = config.default_from_email; } var default_replaces = {}; if (config.site_path) default_replaces.site_path = config.site_path; var __mailtemplates_cache = {}; var sendMail = function(to, subject, html) { if (transporter !== null) transporter.sendMail({ from: transporter.default_from_email, to: to, subject: subject, html: html }); } var sendTemplate = function(templateName, to, replaces) { var doSend = function() { var subject = __mailtemplates_cache[templateName].subject; var body = __mailtemplates_cache[templateName].body; for (var k in replaces) { subject = subject.split('%' + k + '%').join(replaces[k]); body = body.split('%' + k + '%').join(replaces[k]); } for (var k in default_replaces) { subject = subject.split('%' + k + '%').join(default_replaces[k]); body = body.split('%' + k + '%').join(default_replaces[k]); } sendMail(to, subject, body); }; if (typeof(__mailtemplates_cache[templateName]) === 'undefined') { fs.readFile('./data/mailtemplates/' + templateName + '.template', function(err, data) { var lines = ("" + data).split("\n"); var subject = lines.shift(); var body = lines.join("\n"); __mailtemplates_cache[templateName] = { subject: subject, body: body }; doSend(); }); } else { doSend(); } } exports.transporter = transporter; exports.send = sendMail; exports.sendTemplate = sendTemplate; ================================================ FILE: includes/models/authentication.js ================================================ var crypto = require('crypto'); module.exports = function(sequelize, DataTypes) { var Authentication = sequelize.define('Authentication', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, auth_code: DataTypes.STRING(100) }, { timestamps: false, indexes: [{ unique: true, fields: ['auth_code'] }], freezeTableName: true, tableName: 'authentications', classMethods: {}, instanceMethods: {} }); return Authentication; }; ================================================ FILE: includes/models/index.js ================================================ var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var rfr = require('rfr'); var basename = path.basename(module.filename); var config = rfr('includes/config.js'); var db = {}; var options = { logging: false }; if (config.database.use_env_variable) { var sequelize = new Sequelize(process.env[config.database.use_env_variable], options); } else { options.host = config.database.host || null; options.dialect = config.database.dialect || null; options.storage = config.database.storage || null; if (options.storage) options.storage = path.join(rfr.root, options.storage); if (config.database.dialectModulePath) options.dialectModulePath = path.join(rfr.root, config.database.dialectModulePath); var sequelize = new Sequelize(config.database.database, config.database.username, config.database.password, options); } fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf('.') !== 0) && (file !== basename); }) .forEach(function(file) { if (file.slice(-3) !== '.js') return; var model = sequelize['import'](path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if (db[modelName].associate) { db[modelName].associate(db); } }); sequelize.db = db; db.sequelize = sequelize; db.Sequelize = Sequelize; //// Foreign keys db['Authentication'].belongsTo(db['User'], { foreignKey: 'user_id', constraints: false }); db['User'].hasMany(db['Authentication'], { foreignKey: 'user_id', constraints: false, onDelete: 'CASCADE' }); db['Wallet'].belongsTo(db['User'], { foreignKey: 'user_id', constraints: false }); db['User'].hasMany(db['Wallet'], { foreignKey: 'user_id', constraints: false, onDelete: 'CASCADE' }); db['Transaction'].belongsTo(db['User'], { foreignKey: 'user_id', constraints: false }); db['Transaction'].belongsTo(db['Wallet'], { foreignKey: 'wallet_id', constraints: false }); db['User'].hasMany(db['Transaction'], { foreignKey: 'user_id', constraints: false }); db['Wallet'].hasMany(db['Transaction'], { foreignKey: 'wallet_id', constraints: false, onDelete: 'CASCADE' }); db['WalletAccess'].belongsTo(db['Wallet'], { foreignKey: 'wallet_id', constraints: false }); db['WalletAccess'].belongsTo(db['User'], { as: 'OriginalUser', foreignKey: 'original_user_id' }); db['WalletAccess'].belongsTo(db['User'], { as: 'ToUser', foreignKey: 'to_user_id' }); db['Wallet'].hasMany(db['WalletAccess'], { foreignKey: 'wallet_id', constraints: false, onDelete: 'CASCADE' }); db['User'].hasMany(db['WalletAccess'], { foreignKey: 'to_user_id', constraints: false, onDelete: 'SET NULL' }); db['Plan'].belongsTo(db['User'], { foreignKey: 'user_id', constraints: false }); db['User'].hasMany(db['Plan'], { foreignKey: 'user_id', constraints: false, onDelete: 'CASCADE' }); db['Plan'].belongsToMany(db['Wallet'], { as: 'wallets', through: 'plan_wallets', foreignKey: 'plan_id', otherKey: 'wallet_id' }); db['Wallet'].belongsToMany(db['Plan'], { as: 'Plans', through: 'plan_wallets', foreignKey: 'wallet_id', otherKey: 'plan_id' }); module.exports = db; ================================================ FILE: includes/models/plan.js ================================================ var rfr = require('rfr'); var exchange = rfr('includes/exchange.js'); module.exports = function(sequelize, DataTypes) { var Plan = sequelize.define('Plan', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: DataTypes.STRING(255), goal_balance: { type: DataTypes.FLOAT(), defaultValue: 0 }, goal_currency: { type: DataTypes.STRING(10), defaultValue: 'USD' }, goal_datetime: { type: DataTypes.INTEGER }, start_balance: { type: DataTypes.FLOAT(), defaultValue: 0 }, start_currency: { type: DataTypes.STRING(10), defaultValue: 'USD' }, start_datetime: { type: DataTypes.INTEGER }, end_balance: { type: DataTypes.FLOAT(), defaultValue: 0 }, status: { type: DataTypes.ENUM('active', 'finished'), defaultValue: 'active', field: "status", validate: { isIn: { args: [ ['active', 'finished'] ], msg: "Invalid plan status" } } } }, { timestamps: false, indexes: [], freezeTableName: true, tableName: 'plans', classMethods: {}, instanceMethods: { checkIfFinished: function() { var plan = this; return new sequelize.Promise(function(resolve, reject) { if (plan.status == 'finished') { resolve(plan); return; } var currentDateTime = (Date.now() / 1000 | 0); if (plan.goal_datetime <= currentDateTime) { plan.status = 'finished'; plan.getCurrentTotal().then(function(total) { plan.end_balance = total; return plan.save(); }).then(function(plan) { resolve(plan); }); } else { resolve(plan); } }); }, updateWalletsIds: function(wallets_ids) { var plan = this; /// remove duplicate elements wallets_ids = wallets_ids.reduce(function(p, c) { if (p.indexOf(c) < 0) p.push(c); return p; }, []); return new sequelize.Promise(function(resolve, reject) { /// need to check if all wallets are user's wallets sequelize.db.Wallet.findAll({ where: { id: { $in: wallets_ids } } }).then(function(wallets) { var goodWalletsCount = 0; for (var k in wallets_ids) { for (var j in wallets) if (wallets[j].id == wallets_ids[k] && wallets[j].user_id == plan.user_id) goodWalletsCount++; } if (goodWalletsCount != wallets_ids.length) throw "Invalid wallets ids"; plan.setWallets(wallets_ids).then(function() { plan.save().then(function(plan) { resolve(plan); }); }); }); }); }, getCurrentTotal: function() { var plan = this; return new sequelize.Promise(function(resolve, reject) { plan.getWallets().then(function(wallets) { var balance = 0; var walletTotal = 0; for (var k in wallets) { walletTotal = exchange.convert(wallets[k].total, wallets[k].currency, plan.goal_currency); balance += walletTotal; } resolve(balance); }); }); }, setDefaultValues: function() { var plan = this; return new sequelize.Promise(function(resolve, reject) { if (!plan.start_datetime) plan.start_datetime = Date.now() / 1000 | 0; if (!plan.status) plan.status = 'active'; if (!plan.name) plan.name = 'Undefined'; if (!plan.start_currency && plan.goal_currency) plan.start_currency = plan.goal_currency; if (!plan.goal_currency && plan.start_currency) plan.goal_currency = plan.start_currency; if (!plan.start_balance && !plan.isNewRecord) { /// get start_balance from wallets plan.getWallets().then(function(wallets) { var start_balance = 0; // @todo: use exchange rates to recalculate for (var k in wallets) start_balance += wallets[k].total; plan.start_balance = start_balance; resolve(plan); }); } else { resolve(plan); } }); } } }); return Plan; }; ================================================ FILE: includes/models/transaction.js ================================================ var crypto = require('crypto'); module.exports = function(sequelize, DataTypes) { var Transaction = sequelize.define('Transaction', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, description: DataTypes.STRING(255), type: { type: DataTypes.ENUM('profit', 'expense'), defaultValue: 'expense', validate: { isIn: { args: [ ['profit', 'expense'] ], msg: "Invalid transaction type" } } }, subtype: { type: DataTypes.ENUM('setup', 'confirmed', 'planned'), defaultValue: 'confirmed', validate: { isIn: { args: [ ['setup', 'confirmed', 'planned'] ], msg: "Invalid transaction subtype" } } }, amount: { type: DataTypes.FLOAT(), defaultValue: 0 }, abs_amount: { type: DataTypes.FLOAT(), defaultValue: 0 }, datetime: { type: DataTypes.INTEGER, field: "datetime" } }, { timestamps: false, indexes: [ ], freezeTableName: true, tableName: 'transactions', classMethods: {}, instanceMethods: { deleteAndCheckWallet: function() { var setUpDiff = -this.amount; var wallet_id = this.wallet_id; var this_datetime = this.datetime; var this_id = this.id; var that = this; return new sequelize.Promise(function(resolve, reject) { var setUpTransaction = null; sequelize.db.Transaction.findOne({ where: { wallet_id: wallet_id, subtype: 'setup', datetime: { $gte: this_datetime }, id: { $ne: this_id } }, order: 'datetime ASC' }).then(function(setupTransaction) { if (setupTransaction) { setupTransaction.amount -= setUpDiff; setupTransaction.save().then(function(setupTransaction) { that.destroy(); resolve(); }); } else { sequelize.query("UPDATE wallets SET total = total + :diff WHERE id = :id", { replacements: { diff: setUpDiff, id: wallet_id } }).then(function() { that.destroy(); resolve(); }); } }, function(err) { console.log(err); }); }); } } }); return Transaction; }; ================================================ FILE: includes/models/user.js ================================================ var crypto = require('crypto'); var rfr = require('rfr'); var demo = rfr('includes/demo.js'); var mailer = rfr('includes/mailer.js'); var moment = require('moment'); module.exports = function(sequelize, DataTypes) { var User = sequelize.define('User', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, email: { type: DataTypes.STRING(255), validate: { isEmail: { msg: "Invalid email" }, isUnique: function(value, next) { var that = this; sequelize.db.User.findOne({ where: { email: value, id: { $ne: this.id } }, attributes: ['id'] }) .then(function(foundUser) { if (foundUser) throw new Error('Email is already in use'); next(); }).catch(function(err) { throw new Error('Email is already in use'); }); } } }, type: { type: DataTypes.STRING(20), defaultValue: 'default', validate: { isIn: { args: [ ['default', 'facebook'] ], msg: "Invalid user type" } } }, password: DataTypes.STRING(50), login: { type: DataTypes.STRING(255), validate: { isUnique: function(value, next) { var that = this; sequelize.db.User.findOne({ where: { login: value, id: { $ne: this.id } }, attributes: ['id'] }) .then(function(foundUser) { if (foundUser) throw new Error('This username is already in use'); next(); }).catch(function(err) { throw new Error('This username is already in use'); }); } } }, is_demo: { type: DataTypes.INTEGER, defaultValue: 0, allowNull: false }, is_admin: { type: DataTypes.INTEGER, defaultValue: 0, allowNull: false }, registration_date: DataTypes.INTEGER, activity_date: DataTypes.INTEGER, registration_ip: DataTypes.STRING(20), activity_ip: DataTypes.STRING(20), confirmation_code: DataTypes.STRING(255), remove_account_code: DataTypes.STRING(255), password_restore_code: DataTypes.STRING(255), is_banned: { type: DataTypes.INTEGER, defaultValue: 0, allowNull: false } }, { timestamps: false, freezeTableName: true, tableName: 'users', classMethods: { hashPassword: function(password) { return crypto.createHash('md5').update(password + 'password_salt').digest("hex"); }, register: function(params) { var params = params || {}; var type = params.type || 'default'; var login = params.login || ''; var password = params.password || ''; var email = params.email || ''; var ip = params.ip || null; var is_demo = 0; if (email == 'demo@demo.com') { email = 'email' + Math.random() + '@example.com'; login = 'login' + Math.random(); password = 'password' + Math.random(); type = 'default'; is_demo = 1; } password = this.hashPassword(password); return new sequelize.Promise(function(resolve, reject) { var user = sequelize.db.User.build({ type: type, email: email, login: login, password: password }); user.registration_date = Date.now() / 1000 | 0; user.registration_ip = ip; user.is_demo = is_demo; user.save().then(function(user) { if (is_demo) { demo.fillDemoAccount(user).then(function() { resolve(user); }); } else { sequelize.db.WalletAccess.checkAccessForNewUser(user); resolve(user); } }, function(err) { reject(err); }); }); }, registerDemo: function(params, callback) { }, removeOldDemoAccounts: function() { var maxTimestamp = (Date.now() / 1000 | 0) - 2 * 24 * 60 * 60; return sequelize.query("DELETE FROM users WHERE is_demo = 1 AND registration_date < :max_timestamp", { replacements: { max_timestamp: maxTimestamp } }); }, updatePassword: function(code, hash, password) { return new sequelize.Promise(function(resolve, reject) { if (password.length < 6) return reject('Password is too short'); sequelize.db.User.findOne({ where: { password_restore_code: code } }).then(function(user) { if (!user) return reject('Invalid reset password code'); var restore_password_hash = sequelize.db.User.hashPassword(user.id + user.password_restore_code); if (hash != restore_password_hash) return reject('Invalid reset password code'); password = sequelize.db.User.hashPassword(password); user.password = password; return user.save(); }).then(function(user) { resolve(user); }, function(err) { reject(err); }); }); }, resetPassword: function(email) { var restore_password_hash = ''; return new sequelize.Promise(function(resolve, reject) { sequelize.db.User.findOne({ where: { email: email } }).then(function(user) { if (!user) return reject('Can not find this email in our database'); user.password_restore_code = sequelize.db.User.hashPassword("" + user.id + Math.random()); restore_password_hash = sequelize.db.User.hashPassword(user.id + user.password_restore_code); return user.save(); }).then(function(user) { mailer.sendTemplate('restore_password', user.email, { login: user.login, password_restore_code: user.password_restore_code, password_restore_hash: restore_password_hash }); return resolve(user); }).catch(function(e) { return reject('Can not find this email in our database'); }); }); }, getByAuthCode: function(params, callback) { var params = params || {}; var ip = params.ip || null; var auth_code = params.auth_code || null; return new sequelize.Promise(function(resolve, reject) { sequelize.db.Authentication.findOne({ where: { auth_code: auth_code } }).then(function(authentication) { if (!authentication) return reject('Invalid auth code'); return authentication.getUser(); }).then(function(user) { user.activity_ip = ip; user.activity_date = Date.now() / 1000 | 0; user.save(); return resolve(user); }).catch(function(e) { return reject('Invalid auth code'); }); }); }, signIn: function(params) { var params = params || {}; var username = params.username || ''; var password = params.password || ''; password = this.hashPassword(password); return sequelize.db.User.findOne({ where: { $or: [{ login: username }, { email: username }], password: password } }); } }, instanceMethods: { auth: function(params) { var md5sum = crypto.createHash('md5'); var hash = '' + md5sum.update('' + Math.random() + this.id).digest('hex'); return this.createAuthentication({ auth_code: hash }); }, signOut: function() { return sequelize.query("SELECT * FROM `authentications` WHERE user_id = :user_id", { replacements: { user_id: this.id } }); }, removeAccount: function() { var user = this; return new sequelize.Promise(function(resolve, reject) { user.remove_account_code = sequelize.db.User.hashPassword("del" + user.id + Math.random()); user.save().then(function(user) { mailer.sendTemplate('remove_account', user.email, { login: user.login, remove_account_code: user.remove_account_code }); return resolve(user); }); }); }, removeAccountConfirm: function(code) { var user = this; return new sequelize.Promise(function(resolve, reject) { if (user.remove_account_code && user.remove_account_code == code) return user.destroy().then(function() { return resolve(true); }); else return resolve(false); }); }, fillProfile: function(params) { var params = params || {}; var login = params.login || ''; var email = params.email || ''; var password = params.password || ''; var ip = params.ip || null; password = sequelize.db.User.hashPassword(password); if (this.is_demo) { this.login = login; this.email = email; this.password = password; this.is_demo = 0; this.registration_ip = ip; sequelize.db.WalletAccess.checkAccessForNewUser(this); } else return false; return this.save(); }, update: function(params) { var params = params || {}; var password = params.password || ''; var current_password = params.current_password || ''; current_password = sequelize.db.User.hashPassword(current_password); if (current_password == this.password) { password = sequelize.db.User.hashPassword(password); this.password = password; } else { return false; } return this.save(); }, insertWallet: function(params) { var params = params || {}; var name = params.name || ''; var currency = params.currency || 'USD'; return this.createWallet({ name: name, currency: currency }); }, getSharedWallets: function() { return sequelize.query("SELECT wallets.* FROM wallets JOIN wallet_accesses ON wallet_accesses.wallet_id = wallets.id WHERE wallet_accesses.to_user_id = :user_id", { replacements: { user_id: this.id }, model: sequelize.db.Wallet }); }, getUserPlans: function(id) { var where = { 'user_id': this.id }; if (typeof(id) !== 'undefined') where['id'] = id; return sequelize.db.Plan.findAll({ attributes: ['id', 'user_id', 'name', 'goal_balance', 'goal_currency', 'goal_datetime', 'start_balance', 'start_currency', 'start_datetime', 'end_balance', 'status'], where: where, include: [{ model: sequelize.db.Wallet, as: 'wallets', attributes: ['id', 'name', 'total'], through: { attributes: [] } }] }); }, getUserPlan: function(id) { var user = this; return new sequelize.Promise(function(resolve, reject) { user.getUserPlans(id).then(function(plans) { if (plans.length > 0) resolve(plans[0]); else resolve(null); }); }); }, addUserPlan: function(data) { var wallets_ids = data.wallets || []; var user = this; /// remove duplicate elements wallets_ids = wallets_ids.reduce(function(p, c) { if (p.indexOf(c) < 0) p.push(c); return p; }, []); return new sequelize.Promise(function(resolve, reject) { /// need to check if all wallets are user's wallets sequelize.db.Wallet.findAll({ where: { id: { $in: wallets_ids } } }).then(function(wallets) { var goodWalletsCount = 0; for (var k in wallets_ids) { for (var j in wallets) if (wallets[j].id == wallets_ids[k] && wallets[j].user_id == user.id) goodWalletsCount++; } if (goodWalletsCount != wallets_ids.length) throw "Invalid wallets ids"; user.createPlan(data).then(function(plan) { plan.setWallets(wallets_ids).then(function() { return plan.setDefaultValues(); }).then(function() { return plan.save(); }).then(function(plan) { resolve(plan); }); }); }); }); }, getWalletIfHasAccess: function(wallet_id) { return sequelize.db.WalletAccess.getWalletIfHasAccess(this, wallet_id); }, getStats: function(params) { var user = this; var period = params.period || 'week'; if (period != 'week' && period != 'month' && period != 'year') period = 'week'; var utcOffset = params.utcOffset || 0; var wallet_id = params.wallet_id || null; return new sequelize.Promise(function(resolve, reject) { var now = moment(); now.utcOffset(utcOffset); var retPeriods = []; var walletsCurrencies = {}; var lowestTimestamp = now.unix(); var highestTimestamp = now.unix(); var count = 7; if (period == 'month') count = 31; else if (period == 'year') count = 12; for (var i = 0; i < count; i++) { var newPeriod = { month: now.month() + 1, year: now.year(), utcOffset: now.format('Z') }; if (period == 'year') now.startOf('month'); else { newPeriod.day = now.date(); now.startOf('day'); } newPeriod.fromTimestamp = now.unix(); // >= if (newPeriod.fromTimestamp < lowestTimestamp) lowestTimestamp = newPeriod.fromTimestamp; if (period == 'year') now.endOf('month'); else now.endOf('day'); newPeriod.toTimestamp = now.unix(); // <= if (newPeriod.toTimestamp > highestTimestamp) highestTimestamp = newPeriod.toTimestamp; if (period == 'year') now.subtract(1, 'months'); else now.subtract(1, 'days'); retPeriods.push(newPeriod); } user.getWallets().then(function(wallets){ var foundWallet = false; if (wallets) { for (var k in wallets) { if ((wallet_id && wallets[k].id == wallet_id) || !wallet_id) { walletsCurrencies[wallets[k].id] = wallets[k].currency; foundWallet = true; } } } if (!foundWallet) return resolve(null); var allCurrencies = []; for (k in walletsCurrencies) if (allCurrencies.indexOf(walletsCurrencies[k]) == -1) allCurrencies.push(walletsCurrencies[k]); for (k in retPeriods) { retPeriods[k].stats = {}; for (var ak in allCurrencies) retPeriods[k].stats[allCurrencies[ak]] = { expense: 0, profit: 0 } }; var where = { user_id: user.id, datetime: { $lte: highestTimestamp, $gte: lowestTimestamp } }; if (wallet_id > 0) where.wallet_id = wallet_id; sequelize.db.Transaction.findAll({ where: where }).then(function(transactions){ if (transactions) for (var kt in transactions) for (var kp in retPeriods) { if (transactions[kt].datetime >= retPeriods[kp].fromTimestamp && transactions[kt].datetime <= retPeriods[kp].toTimestamp) { var currency = walletsCurrencies[transactions[kt].wallet_id]; if (transactions[kt].amount < 0) retPeriods[kp].stats[currency].expense += Math.abs(transactions[kt].amount); else retPeriods[kp].stats[currency].profit += Math.abs(transactions[kt].amount); } } for (var k in retPeriods) { delete retPeriods[k].fromTimestamp; delete retPeriods[k].toTimestamp; } resolve(retPeriods); }); }); }); } } }); return User; }; ================================================ FILE: includes/models/wallet.js ================================================ var crypto = require('crypto'); module.exports = function(sequelize, DataTypes) { var Wallet = sequelize.define('Wallet', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: DataTypes.STRING(255), type: { type: DataTypes.ENUM('default', 'user'), defaultValue: 'default', validate: { isIn: { args: [ ['default', 'user'] ], msg: "Invalid wallet type" } } }, status: { type: DataTypes.ENUM('active', 'hidden'), defaultValue: 'active', validate: { isIn: { args: [ ['active', 'hidden'] ], msg: "Invalid wallet status" } } }, currency: { type: DataTypes.STRING(10), defaultValue: 'USD' }, total: { type: DataTypes.FLOAT(), defaultValue: 0 } }, { timestamps: false, indexes: [ ], freezeTableName: true, tableName: 'wallets', classMethods: {}, instanceMethods: { giveAccess: function(params) { var params = params || {}; var email = params.email || ''; var original_user_id = this.user_id; var that = this; return new sequelize.Promise(function(resolve, reject) { sequelize.db.User.findOne({ where: { email: email } }). then(function(user) { if (user) return that.createWalletAccess({ to_email: email, to_user_id: user.id, original_user_id: original_user_id }); else return that.createWalletAccess({ to_email: email, original_user_id: original_user_id }); }) .then(function(wallet_access) { resolve(wallet_access); }, function(err) { reject(err); }); }); }, setTotalTo: function(params) { var params = params || {}; var amount = parseFloat(params.amount, 10) || 0; var diff = amount - this.total; params.subtype = 'setup'; params.amount = diff; return this.insertTransaction(params); }, insertTransaction: function(params) { var params = params || {}; var description = params.description || ''; var amount = parseFloat(params.amount, 10) || 0; var abs_amount = Math.abs(amount); var subtype = params.subtype || 'confirmed'; var currentDateTime = (Date.now() / 1000 | 0); var datetime = currentDateTime; var inThePast = false; if (parseInt(params.datetime)) { datetime = parseInt(params.datetime); if (datetime < currentDateTime) inThePast = true; } var type = 'expense'; if (amount >= 0) type = 'profit'; var user_id = this.user_id; var that = this; return new sequelize.Promise(function(resolve, reject) { that.createTransaction({ description: description, amount: amount, abs_amount: abs_amount, subtype: subtype, datetime: datetime, type: type, user_id: user_id }).then(function(transaction) { /// proccess successful calculation if (!inThePast) { that.total = that.total + transaction.amount; that.save().done(function(res) { resolve(transaction); }); } else { /// need to recalculate /// find setup transaction after this current one we've added sequelize.db.Transaction.findOne({ where: { wallet_id: that.id, subtype: 'setup', datetime: { $gt: datetime } }, order: 'datetime ASC' }).then(function(setup_transaction) { if (setup_transaction) { /// there's setup transaction setup_transaction.amount = setup_transaction.amount + transaction.amount; setup_transaction.save().done(function(res) { resolve(transaction); }); } else { /// no setup transaction, update wallet that.total = that.total + transaction.amount; that.save().done(function(res) { resolve(transaction); }); } }); } }, function(err) { reject(err); }); }); }, getWalletPlans: function() { var wallet = this; return new sequelize.Promise(function(resolve, reject) { sequelize.db.Plan.findAll({ attributes: ['id'], where: { 'user_id': wallet.user_id }, include: [{ model: sequelize.db.Wallet, as: 'wallets', attributes: ['id', 'name', 'total'], where: { id: wallet.id }, through: { attributes: [] } }] }).then(function(plans) { var ids = []; for (var k in plans) ids.push(plans[k].id); sequelize.db.Plan.findAll({ attributes: ['id', 'user_id', 'name', 'goal_balance', 'goal_currency', 'goal_datetime', 'start_balance', 'start_currency', 'start_datetime', 'end_balance', 'status'], where: { id: { $in: ids } }, include: [{ model: sequelize.db.Wallet, as: 'wallets', attributes: ['id', 'name', 'total'], through: { attributes: [] } }] }).then(function(plans) { resolve(plans); }); }); }); } } }); return Wallet; }; ================================================ FILE: includes/models/wallet_access.js ================================================ module.exports = function(sequelize, DataTypes) { var Authentication = sequelize.define('WalletAccess', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, to_email: { type: DataTypes.STRING(255), validate: { isEmail: { msg: "Invalid email" } } }, }, { timestamps: false, indexes: [{ unique: true, fields: ['to_email'] }], freezeTableName: true, tableName: 'wallet_accesses', classMethods: { checkAccessForNewUser: function(user) { var email = user.email; var new_user_id = user.id; sequelize.db.WalletAccess.findAll({ where: { to_email: email, to_user_id: null } }) .then(function(wallet_accesses) { wallet_accesses.forEach(function(wallet_access) { wallet_access.to_user_id = new_user_id; wallet_access.save(); }); }); }, getWalletIfHasAccess: function(user, wallet_id) { return new sequelize.Promise(function(resolve, reject) { sequelize.db.Wallet.findOne({ where: { id: wallet_id } }) .then(function(wallet) { if (!wallet) resolve(null); if (wallet.user_id == user.id) resolve(wallet); else { sequelize.query("SELECT wallets.* FROM wallets JOIN wallet_accesses ON wallet_accesses.wallet_id = wallets.id WHERE wallets.id = :wallet_id AND wallet_accesses.to_user_id = :user_id", { replacements: { user_id: user.id, wallet_id: wallet_id }, model: sequelize.db.Wallet }) .then(function(wallets) { if (!wallets.length) resolve(null); else resolve(wallets[0]); }, function(err) { reject(err); }); } }); }); } }, instanceMethods: {} }); return Authentication; }; ================================================ FILE: includes/routes/exchange/exchange.apib ================================================ # Group Exchange Rates ### Get Exchange Rates [GET /api/exchange/rates] Get cached exchange rates from OpenExchangeRates (if API key is defined in config files) or from Yahoo FX. + Response 200 (application/json) + Body { "base":"USD", "rates": { "AED":3.673, "AFN":68.37, "ZAR":14.5653, "ZMK":5189.5, "ZMW":9.2, "ZWL":322.355 } } ================================================ FILE: includes/routes/exchange/rates.js ================================================ var rfr = require('rfr'); var api = rfr('includes/api.js'); var exchange = rfr('includes/exchange.js'); exports.route = '/api/exchange/rates'; exports.method = 'get'; exports.handler = function(req, res, next) { res.send(exchange.getRates()); next(); }; ================================================ FILE: includes/routes/i18n/get.js ================================================ var rfr = require('rfr'); var api = rfr('includes/api.js'); exports.route = '/api/i18n/bycode/:code'; exports.method = 'get'; exports.handler = function(req, res, next) { var code = req.params.code || en; var body = api.geti18njson(code); res.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'application/json' }); res.write(body); res.end(); next(); }; ================================================ FILE: includes/routes/i18n/i18n.apib ================================================ # Group i18n ### Get language strings [GET /api/i18n/bycode/{code}] Get i18n json file for selected locale. + Parameters + code: ua (string) - language code + Response 200 (application/json) + Body { "Nothing is found": "Sem resultado", "Add Income": "Adicionar Receita", "Amount": "Valor", "...": "..." } ================================================ FILE: includes/routes/index.js ================================================ var fs = require('fs'); var routes = []; var done = false; var callback; var walk = function(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var i = 0; (function next() { var file = list[i++]; if (!file) return done(null, results); file = dir + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walk(file, function(err, res) { results = results.concat(res); next(); }); } else { results.push(file); next(); } }); })(); }); }; walk(__dirname, function(err, results) { if (err) throw err; results.forEach(function(file) { if (file.indexOf('index.js') == -1 && file.slice(-3) === '.js') { var name = file.substr(file.lastIndexOf('/'), file.indexOf('.')); var inc = require(file); routes.push({ handler: inc.handler, route: inc.route, method: inc.method, docs: inc.docs }); } }); done = true; if (typeof callback == 'function') callback(routes); }); module.exports = function(cb) { if (done) cb(routes); else callback = cb; } ================================================ FILE: includes/routes/plans/del.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/plans/:plan_id'; exports.method = 'del'; exports.handler = function(req, res, next) { var plan_id = req.params.plan_id || 0; api.requireSignedIn(req, function(user) { db.Plan.findOne({ where: { id: plan_id, user_id: user.id } }) .then(function(plan) { if (!plan) throw new errors.HaveNoRightsError(); return plan.destroy(); }).then(function(plan) { res.send(true); next(); }); }); }; ================================================ FILE: includes/routes/plans/get.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/plans/:plan_id'; exports.method = 'get'; exports.handler = function(req, res, next) { var plan_id = parseInt(req.params.plan_id || 0, 10); api.requireSignedIn(req, function(user) { user.getUserPlan(plan_id).then(function(resPlan) { resPlan.checkIfFinished().then(function(plan) { res.send(plan); next(); }); }); }); }; ================================================ FILE: includes/routes/plans/list.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/plans'; exports.method = 'get'; exports.handler = function(req, res, next) { api.requireSignedIn(req, function(user) { user.getUserPlans().then(function(plans) { var resPlans = []; for (var k in plans) resPlans.push(plans[k].checkIfFinished()); db.sequelize.Promise.all(resPlans).then(function() { res.send(plans); next(); }); }); }); }; ================================================ FILE: includes/routes/plans/plans.apib ================================================ # Group Goals ### List User Goals [GET /api/plans] Get list of user's goals + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { "id":1, "name":"", "goal_balance":1000, "goal_currency":"USD", "goal_datetime":null, "start_balance":2138.02, "start_currency":"USD", "start_datetime":null, "status":"active", "wallets": [ { "id":1, "name":"Sample Bank Account Wallet", "total":2138.02 } ] } ] ### Add New Goal [POST /api/plans] Create new goal for currently signed in user's account + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + name: Somegoalname (string, required) - Goal name. + start_currency: USD (string, required) - currency identifier. USD, EUR, BTC etc + goal_currency: USD (string, required) - currency identifier. USD, EUR, BTC etc + start_balance: 2138.02 (number, required) - Current balance of wallets used in this plan + goal_balance: 1000 (number, required) - Current balance of wallets used in this plan + start_datetime: (number, required) - Current unix timestamp + goal_datetime: (number, required) - Goal unix timestamp + wallets: [12,13] (array, required) - Array of wallets ids for this goal + Response 200 (application/json) + Body { "id":1, "name":"", "goal_balance":30, "goal_currency":"USD", "goal_datetime":23423, "start_balance":2138.02, "start_currency":"USD", "start_datetime":22333, "status":"active", "wallets": [ { "id":1, "name":"Sample Bank Account Wallet", "total":2138.02 } ] } ### Update Goal [PUT /api/plans/{plan_id}] Update goal + Parameters + plan_id (number) - ID of the Plan in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + name: Somegoalname (string, required) - Goal name. + goal_currency: USD (string, required) - currency identifier. USD, EUR, BTC etc + goal_balance: 1000 (number, required) - Current balance of wallets used in this plan + goal_datetime: (number, required) - Goal unix timestamp + wallets: [12,13] (array, required) - Array of wallets ids for this goal + Response 200 (application/json) + Body { "id":1, "name":"", "goal_balance":30, "goal_currency":"USD", "goal_datetime":23423, "start_balance":2138.02, "start_currency":"USD", "start_datetime":22333, "status":"active", "wallets": [ { "id":1, "name":"Sample Bank Account Wallet", "total":2138.02 } ] } ### Remove Goal [DELETE /api/plans/{plan_id}] Remove goal from database + Parameters + plan_id (number) - ID of the Plan in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body true ================================================ FILE: includes/routes/plans/post.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/plans'; exports.method = 'post'; exports.handler = function(req, res, next) { var data = { name: api.getParam(req, 'name', 'Undefined'), goal_balance: api.getParam(req, 'goal_balance', 0), goal_currency: api.getParam(req, 'goal_currency', ''), goal_datetime: api.getParam(req, 'goal_datetime', 0), start_balance: api.getParam(req, 'start_balance', 0), start_currency: api.getParam(req, 'start_currency', ''), start_datetime: api.getParam(req, 'start_datetime', 0), status: api.getParam(req, 'status', 'active'), wallets: api.getParam(req, 'wallets', 0) }; api.requireSignedIn(req, function(user) { user.addUserPlan(data).then(function(plan) { /// loads it from db, to be sure: user.getUserPlan(plan.id).then(function(resPlan) { res.send(resPlan); next(); }); }); }); }; ================================================ FILE: includes/routes/plans/put.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/plans/:plan_id'; exports.method = 'put'; exports.handler = function(req, res, next) { var plan_id = req.params.plan_id || 0; var data = { name: api.getParam(req, 'name', null), goal_balance: api.getParam(req, 'goal_balance', null), goal_currency: api.getParam(req, 'goal_currency', null), goal_datetime: api.getParam(req, 'goal_datetime', null), wallets: api.getParam(req, 'wallets', null) }; api.requireSignedIn(req, function(user) { db.Plan.findOne({ where: { id: plan_id, user_id: user.id } }) .then(function(plan) { if (data.name !== null) plan.name = data.name; if (data.goal_balance !== null) plan.goal_balance = data.goal_balance; if (data.goal_currency !== null) plan.goal_currency = data.goal_currency; if (data.goal_datetime !== null) plan.goal_datetime = data.goal_datetime; if (data.wallets !== null) return plan.updateWalletsIds(data.wallets); else return plan.save(); }).then(function(plan) { /// loads it from db, to be sure: user.getUserPlan(plan.id).then(function(resPlan) { res.send(resPlan); next(); }); }); }); }; ================================================ FILE: includes/routes/stats/month.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/stats/month'; exports.method = 'get'; exports.handler = function(req, res, next) { var utcoffset = parseInt(req.params.utcoffset || 0, 10); // http://momentjs.com/docs/#/manipulating/utc-offset/ api.requireSignedIn(req, function(user) { user.getStats({period: 'month', utcOffset: utcoffset}).then(function(stats){ res.send(stats); next(); }); }); }; ================================================ FILE: includes/routes/stats/stats.apib ================================================ # Group Statistics ### Get Recent Week User Statistics [GET /api/stats/week] Get recent week user statistics + Request (application/json) + Attributes (object) + utcoffset: (number) - Timezone offset. In hours or minutes. http://momentjs.com/docs/#/manipulating/utc-offset/ + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { month: 4, year: 2016, day: 21, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 20, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 19, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 18, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 17, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 16, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 15, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } } ] ### Get Recent Month User Statistics [GET /api/stats/month] Get recent month user statistics + Request (application/json) + Attributes (object) + utcoffset: (number) - Timezone offset. In hours or minutes. http://momentjs.com/docs/#/manipulating/utc-offset/ + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { month: 4, year: 2016, day: 21, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } }, { month: 3, year: 2016, day: 22, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } } ] ### Get Recent Year User Statistics [GET /api/stats/year] Get recent year user statistics + Request (application/json) + Attributes (object) + utcoffset: (number) - Timezone offset. In hours or minutes. http://momentjs.com/docs/#/manipulating/utc-offset/ + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { month: 4, year: 2016, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } }, { month: 2, year: 2016, utcOffset: '-03:00', stats: { UAH: { expense: 0, profit: 198 }, USD: { expense: 90, profit: 11.99 } } } ] ================================================ FILE: includes/routes/stats/week.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/stats/week'; exports.method = 'get'; exports.handler = function(req, res, next) { var utcoffset = parseInt(req.params.utcoffset || 0, 10); // http://momentjs.com/docs/#/manipulating/utc-offset/ api.requireSignedIn(req, function(user) { user.getStats({period: 'week', utcOffset: utcoffset}).then(function(stats){ res.send(stats); next(); }); }); }; ================================================ FILE: includes/routes/stats/year.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/stats/year'; exports.method = 'get'; exports.handler = function(req, res, next) { var utcoffset = parseInt(req.params.utcoffset || 0, 10); // http://momentjs.com/docs/#/manipulating/utc-offset/ api.requireSignedIn(req, function(user) { user.getStats({period: 'year', utcOffset: utcoffset}).then(function(stats){ res.send(stats); next(); }); }); }; ================================================ FILE: includes/routes/users/get.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var api = rfr('includes/api.js'); var mailer = rfr('includes/mailer.js'); exports.route = '/api/users'; exports.method = 'get'; exports.handler = function(req, res, next) { api.requireSignedIn(req, function(user) { res.send({ login: user.login, email: user.email, id: user.id, is_demo: user.is_demo }); next(); }); }; ================================================ FILE: includes/routes/users/newpassword.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var ValidationError = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/users/newpassword'; exports.method = 'post'; exports.handler = function(req, res, next) { var code = api.getParam(req, 'code', ''); var hash = api.getParam(req, 'hash', ''); var password =api.getParam(req, 'password', ''); db.User.updatePassword(code, hash, password).then(function(user) { res.send(true); next(); }, function(e) { throw e; }); }; ================================================ FILE: includes/routes/users/post.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var ValidationError = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/users'; exports.method = 'post'; exports.handler = function(req, res, next) { var body = req.body || {}; var login = api.getParam(req, 'login', ''); var type = api.getParam(req, 'type', 'default'); var password = api.getParam(req, 'password', ''); var email = api.getParam(req, 'email', ''); var ip = api.getVisitorIp(req); var gotUser = null; db.User.removeOldDemoAccounts(); db.User.register({ login: login, type: type, password: password, email: email, ip: ip }).then(function(user) { gotUser = user; return user.auth(); }).then(function(authentication) { res.setCookie('logged_in_user', authentication.auth_code, { path: '/', maxAge: 365 * 24 * 60 * 60 }); res.setCookie('is_logged_in_user', '1', { path: '/', maxAge: 365 * 24 * 60 * 60 }); res.send({ id: gotUser.id, email: gotUser.email, login: gotUser.login, is_demo: gotUser.is_demo, auth_code: authentication.auth_code }); next(); }).catch(function(e) { throw e; }); return true; }; ================================================ FILE: includes/routes/users/put.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/users/:user_id'; exports.method = 'put'; exports.handler = function(req, res, next) { var user_id = req.params.user_id; var password = api.getParam(req, 'login', null); var email = api.getParam(req, 'email', null); var login = api.getParam(req, 'login', null); var current_password = api.getParam(req, 'current_password', null); var ip = api.getVisitorIp(req); api.requireSignedIn(req, function(user) { var promise = false; if (user.is_demo) promise = user.fillProfile({ email: email, login: login, password: password, ip: ip }); else promise = user.update({ password: password, current_password: current_password }); if (promise === false) throw new errors.HaveNoRightsError(); promise.then(function(user) { res.send({ login: user.login, email: user.email, id: user.id, is_demo: user.is_demo }); next(); }); }); }; ================================================ FILE: includes/routes/users/removeaccount.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/users/:user_id/removeaccount'; exports.method = 'post'; exports.handler = function(req, res, next) { var user_id = parseInt(req.params.user_id || 0, 10); var code = api.getParam(req, 'code', null); api.requireSignedIn(req, function(user) { if (user_id != user.id) throw 'Invalid user id'; if (code === null) /// first step, no code parameter { user.removeAccount().then(function(user) { res.send(true); next(); }); } else { /// second step, with code db.User.findOne({ where: { id: user_id, remove_account_code: code } }).then(function(user) { if (!user) { res.send(false); next(); } user.removeAccountConfirm(code).then(function(success) { res.send(success); next(); }); }); } }); }; ================================================ FILE: includes/routes/users/restore.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/users/restore'; exports.method = 'post'; exports.handler = function(req, res, next) { var email = api.getParam(req, 'email', ''); db.User.resetPassword(email).then(function(user) { res.send(true); next(); }, function(e) { throw e; }); }; ================================================ FILE: includes/routes/users/signin.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/users/signin'; exports.method = 'post'; exports.handler = function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); var username = api.getParam(req, 'username', ''); var password = api.getParam(req, 'password', ''); console.log(username); console.log(password); var gotUser = null; db.User.signIn({ username: username, password: password }).then(function(user) { gotUser = user; return user.auth(); }).then(function(authentication) { res.setCookie('logged_in_user', authentication.auth_code, { path: '/', maxAge: 365 * 24 * 60 * 60 }); res.setCookie('is_logged_in_user', '1', { path: '/', maxAge: 365 * 24 * 60 * 60 }); res.send({ id: gotUser.id, email: gotUser.email, login: gotUser.login, is_demo: gotUser.is_demo, auth_code: authentication.auth_code }); next(); }).catch(function(e) { throw e; }); return true; }; ================================================ FILE: includes/routes/users/signout.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var api = rfr('includes/api.js'); exports.route = '/api/users/signout'; exports.method = 'post'; exports.handler = function(req, res, next) { var cookies = req.cookies; var auth_code = cookies.logged_in_user || ''; res.setCookie('logged_in_user', null, { path: '/', maxAge: -1 }); res.setCookie('is_logged_in_user', null, { path: '/', maxAge: -1 }); res.send(true); next(); }; ================================================ FILE: includes/routes/users/users.apib ================================================ # Group Users ### User [GET /api/users] ### Get Signed In User Details [GET /api/users] Get currently signed in user details. + Request + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body { "id": 23, "email": "example@gmail.com", "login": "userlogin", "is_demo": 0 } ### List User Wallets [GET /api/users/:user_id/wallets] Get list of current user's wallets + Parameters + user_id (number) - ID of the User in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { "id":4, "name":"Cash", "status":"active", "currency":"EUR", "total":300, "origin":"mine" }, { "id":32, "name":"Bitcoins", "status":"active", "currency":"BTC", "total":12.99, "origin":"shared" } ] ### Sign In [POST /api/users/signin] Sign in user using username and password. Returns user record with auth_code property. Use this auth_code for signing next API calls. + Request (application/json) + Attributes (object) + username: userlogin (string) - username or email + password: Hahahahahaha (string, required) + Response 200 (application/json) + Body { "id": 23, "email": "example@gmail.com", "login": "userlogin", "is_demo": 0, "auth_code": "017957d841c8f6927c612ea1d6602c3f" } ### Register New User [POST /api/users] Register new user. Returns user record with auth_code property. Use this auth_code for signing next API calls. + Request (application/json) + Attributes (object) + email: example@example.com (string, required) + login: userlogin (string, required) + type: default (string) + password: lovesecurity (string, required) + Response 200 (application/json) + Body { "id": 23, "email": "example@gmail.com", "login": "userlogin", "is_demo": 0, "auth_code": "017957d841c8f6927c612ea1d6602c3f" } ### Fill Demo Account [PUT /api/users/:user_id] Fill demo account. + Parameters + user_id (number) - ID of the User in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + email: example@example.com (string, required) + login: userlogin (string, required) + password: dolovesecurity (string, required) + Response 200 (application/json) + Body { "id": 23, "email": "example@gmail.com", "login": "userlogin", "is_demo": 0 } ### Update User Password [PUT /api/users/:user_id] Update user password. + Parameters + user_id (number) - ID of the User in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + current_password: lovesecurity (string, required) + password: dolovesecurity (string, required) + Response 200 (application/json) + Body { "id": 23, "email": "example@gmail.com", "login": "userlogin", "is_demo": 0 } ### Reset User Password [POST /api/users/restore] Start reset password procedure. Generate restore code and hash and send message to user's email. + Request (application/json) + Attributes (object) + email: example@example.com (string, required) + Response 200 (application/json) + Body true ### Set New User Password [POST /api/users/newpassword] Update user's password using code and hash generated with 'Reset User Password' API method. + Request (application/json) + Attributes (object) + code: 234234 (string, required) + hash: 345345345 (string, required) + password: dolovesecurity (string, required) + Response 200 (application/json) + Body true ### Sign Out [POST /api/users/signout] Signs out current user. And invalidates auth_code. + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + username: userlogin (string) - username or email + password: Hahahahahaha (string, required) + Response 200 (application/json) + Body true ### Remove User Account [POST /api/users/{user_id}/removeaccount] Start user account remove process. Sends email to user with confirmation code. + Parameters + user_id (number) - ID of the User in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body true ### Confirm User Account Removal [POST /api/users/{user_id}/removeaccount] Confirm user account removal. + Parameters + user_id (number) - ID of the User in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + code: 223425234 (string, required) - confirmation code + Response 200 (application/json) + Body true ================================================ FILE: includes/routes/users/wallets/list.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var api = rfr('includes/api.js'); exports.route = '/api/users/:user_id/wallets'; exports.method = 'get'; exports.handler = function(req, res, next) { api.requireSignedIn(req, function(user) { db.sequelize.Promise.join( user.getWallets(), user.getSharedWallets(), function(own, shared) { res.send( shared.map( function(wallet) { return { id: wallet.id, name: wallet.name, status: wallet.status, currency: wallet.currency, total: wallet.total, origin: 'shared' }; } ).concat( own.map( function(wallet) { return { id: wallet.id, name: wallet.name, status: wallet.status, currency: wallet.currency, total: wallet.total, origin: 'mine' }; } ) ) ); next(); } ); }); }; ================================================ FILE: includes/routes/wallets/accesses/accesses.apib ================================================ # Group Wallet Access ### List Wallet Accesses [GET /api/wallets/{wallet_id}/accesses] Get list of accesses to wallet + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { "id":11, "to_email":"example@gmail.com", "wallet_id":4, "original_user_id":1, "to_user_id":null }, { "id":12, "to_email":"example2@gmail.com", "wallet_id":4, "original_user_id":1, "to_user_id":88 } ] ### Add new access to wallet [POST /api/wallets/{wallet_id}/accesses] Add new access to wallet. User registered(already or later) with to_email will be able to view wallet. + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + wallet_id: 1 (number, required) - Wallet ID. Should be the same as in URL param + to_email: example2@gmail.com (string, required) - Email + Response 200 (application/json) + Body { "id":12, "to_email":"example2@gmail.com", "wallet_id":4, "original_user_id":1, "to_user_id":88 } ### Remove Wallet Access [DELETE /api/wallets/{wallet_id}/accesses/{wallet_access_id}] Remove access to wallet. Works only if called by original wallet owner. + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + wallet_access_id (number) - ID of the WalletAccess in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body true ================================================ FILE: includes/routes/wallets/accesses/del.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/accesses/:wallet_access_id'; exports.method = 'del'; exports.handler = function(req, res, next) { var wallet_id = req.params.wallet_id || 0; var wallet_access_id = req.params.wallet_access_id || 0; api.requireSignedIn(req, function(user) { db.WalletAccess.findOne({ where: { id: wallet_access_id, wallet_id: wallet_id, original_user_id: user.id } }) .then(function(wallet_access) { if (!wallet_access) throw new errors.HaveNoRightsError(); return wallet_access.destroy(); }).then(function(wallet_access) { res.send(true); next(); }); }); }; ================================================ FILE: includes/routes/wallets/accesses/list.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/accesses'; exports.method = 'get'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); api.requireSignedIn(req, function(user) { db.Wallet.findOne({ where: { id: wallet_id, user_id: user.id } }) .then(function(wallet) { if (!wallet) throw new errors.HaveNoRightsError(); return db.WalletAccess.findAll({ where: { wallet_id: wallet_id } }); }) .then(function(wallet_accesses) { res.send(wallet_accesses); next(); }); }); }; ================================================ FILE: includes/routes/wallets/accesses/post.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/accesses'; exports.method = 'post'; exports.handler = function(req, res, next) { var wallet_id = parseInt(api.getParam(req, 'wallet_id', 0), 10); var to_email = api.getParam(req, 'to_email', ''); api.requireSignedIn(req, function(user) { db.Wallet.findOne({ where: { id: wallet_id, user_id: user.id } }) .then(function(wallet) { if (!wallet) throw new errors.HaveNoRightsError(); return wallet.giveAccess({ email: to_email }); }).then(function(wallet_access) { res.send(wallet_access); next(); }, function(err) { throw err; }); }); }; ================================================ FILE: includes/routes/wallets/delete.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id'; exports.method = 'del'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); api.requireSignedIn(req, function(user) { db.Wallet.findOne({ where: { id: wallet_id, user_id: user.id, status: 'hidden' } }) .then(function(wallet) { return wallet.destroy(); }).then(function(wallet) { res.send(true); next(); }); }); }; ================================================ FILE: includes/routes/wallets/get.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id'; exports.method = 'get'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); api.requireSignedIn(req, function(user) { user.getWalletIfHasAccess(wallet_id) .then(function(wallet) { if (!wallet) throw new errors.NotFoundError(); res.send(wallet); next(); }); }); }; ================================================ FILE: includes/routes/wallets/list.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var api = rfr('includes/api.js'); exports.route = '/api/wallets'; exports.method = 'get'; exports.handler = function(req, res, next) { api.requireSignedIn(req, function(user) { db.sequelize.Promise.join( user.getWallets(), user.getSharedWallets(), function(own, shared) { res.send( shared.map( function(wallet) { return { id: wallet.id, name: wallet.name, status: wallet.status, currency: wallet.currency, total: wallet.total, origin: 'shared' }; } ).concat( own.map( function(wallet) { return { id: wallet.id, name: wallet.name, status: wallet.status, currency: wallet.currency, total: wallet.total, origin: 'mine' }; } ) ) ); next(); } ); }); }; ================================================ FILE: includes/routes/wallets/plans/list.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/plans'; exports.method = 'get'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); api.requireSignedIn(req, function(user) { db.Wallet.findOne({ where: { id: wallet_id, user_id: user.id } }) .then(function(wallet) { if (!wallet) throw new errors.HaveNoRightsError(); return wallet.getWalletPlans(); }) .then(function(plans) { var resPlans = []; for (var k in plans) resPlans.push(plans[k].checkIfFinished()); db.sequelize.Promise.all(resPlans).then(function() { res.send(plans); next(); }); }); }); }; ================================================ FILE: includes/routes/wallets/post.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets'; exports.method = 'post'; exports.handler = function(req, res, next) { var name = api.getParam(req, 'name', ''); var currency = api.getParam(req, 'currency', 'USD'); api.requireSignedIn(req, function(user) { user.insertWallet({ name: name, currency: currency }) .then(function(wallet) { res.send(wallet); next(); }); }); }; ================================================ FILE: includes/routes/wallets/put.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id'; exports.method = 'put'; exports.handler = function(req, res, next) { var wallet_id = req.params.wallet_id || 0; var name = api.getParam(req, 'name', null); var currency = api.getParam(req, 'currency', null); var status = api.getParam(req, 'status', null); api.requireSignedIn(req, function(user) { db.Wallet.findOne({ where: { id: wallet_id, user_id: user.id } }) .then(function(wallet) { if (name !== null) wallet.name = name; if (currency !== null) wallet.currency = currency; if (status !== null) wallet.status = status; return wallet.save(); }).then(function(wallet) { res.send(wallet); next(); }); }); }; ================================================ FILE: includes/routes/wallets/stats/month.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/stats/month'; exports.method = 'get'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); var utcoffset = parseInt(req.params.utcoffset || 0, 10); // http://momentjs.com/docs/#/manipulating/utc-offset/ api.requireSignedIn(req, function(user) { user.getStats({period: 'month', utcOffset: utcoffset, wallet_id: wallet_id}).then(function(stats){ res.send(stats); next(); }); }); }; ================================================ FILE: includes/routes/wallets/stats/wallet_stats.apib ================================================ # Group Wallet Statistics ### Get Recent Week Wallet Statistics [GET /api/wallets/{wallet_id}/stats/week] Get recent week user statistics + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Attributes (object) + utcoffset: (number) - Timezone offset. In hours or minutes. http://momentjs.com/docs/#/manipulating/utc-offset/ + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { month: 4, year: 2016, day: 21, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 20, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 19, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 18, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 17, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 16, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } }, { month: 4, year: 2016, day: 15, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } } ] ### Get Recent Month Wallet Statistics [GET /api/wallets/{wallet_id}/stats/month] Get recent month wallet statistics + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Attributes (object) + utcoffset: (number) - Timezone offset. In hours or minutes. http://momentjs.com/docs/#/manipulating/utc-offset/ + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { month: 4, year: 2016, day: 21, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } }, { month: 3, year: 2016, day: 22, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } } ] ### Get Recent Year Wallet Statistics [GET /api/wallets/{wallet_id}/stats/year] Get recent year wallet statistics + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Attributes (object) + utcoffset: (number) - Timezone offset. In hours or minutes. http://momentjs.com/docs/#/manipulating/utc-offset/ + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { month: 4, year: 2016, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } }, { month: 2, year: 2016, utcOffset: '-03:00', stats: { USD: { expense: 90, profit: 11.99 } } } ] ================================================ FILE: includes/routes/wallets/stats/week.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/stats/week'; exports.method = 'get'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); var utcoffset = parseInt(req.params.utcoffset || 0, 10); // http://momentjs.com/docs/#/manipulating/utc-offset/ api.requireSignedIn(req, function(user) { user.getStats({period: 'week', utcOffset: utcoffset, wallet_id: wallet_id}).then(function(stats){ res.send(stats); next(); }); }); }; ================================================ FILE: includes/routes/wallets/stats/year.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/stats/year'; exports.method = 'get'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); var utcoffset = parseInt(req.params.utcoffset || 0, 10); // http://momentjs.com/docs/#/manipulating/utc-offset/ api.requireSignedIn(req, function(user) { user.getStats({period: 'year', utcOffset: utcoffset, wallet_id: wallet_id}).then(function(stats){ res.send(stats); next(); }); }); }; ================================================ FILE: includes/routes/wallets/transactions/del.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/transactions/:transaction_id'; exports.method = 'del'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); var transaction_id = parseInt(req.params.transaction_id || 0, 10); api.requireSignedIn(req, function(user) { db.Wallet.findOne({ where: { id: wallet_id, user_id: user.id } }) .then(function(wallet) { if (!wallet) throw new errors.NotFoundError(); return db.Transaction.findOne({ where: { id: transaction_id, wallet_id: wallet.id } }); }).then(function(transaction) { if (!transaction) throw new errors.NotFoundError(); return transaction.deleteAndCheckWallet(); }).then(function() { res.send(true); next(); }) }); }; ================================================ FILE: includes/routes/wallets/transactions/list.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/transactions'; exports.method = 'get'; exports.handler = function(req, res, next) { var wallet_id = parseInt(req.params.wallet_id || 0, 10); var to = parseInt(req.params.to || 0, 10); var from = parseInt(req.params.from || 0, 10); if (to === 0 || from === 0) { to = Math.floor(Date.now() / 1000); from = to - 24 * 60 * 60 * 31; } api.requireSignedIn(req, function(user) { user.getWalletIfHasAccess(wallet_id) .then(function(wallet) { if (!wallet) throw new errors.HaveNoRightsError(); return db.Transaction.findAll({ where: { wallet_id: wallet.id, datetime: { $lte: to, $gt: from } }, order: [['datetime', 'DESC']] }); }).then(function(transactions) { res.send(transactions); next(); }); }); }; ================================================ FILE: includes/routes/wallets/transactions/post.js ================================================ var rfr = require('rfr'); var db = rfr('includes/models'); var errors = rfr('includes/errors.js'); var api = rfr('includes/api.js'); exports.route = '/api/wallets/:wallet_id/transactions'; exports.method = 'post'; exports.handler = function(req, res, next) { var body = req.body || {}; var wallet_id = api.getParam(req, 'wallet_id', 0); var amount = api.getParam(req, 'amount', 0); var description = api.getParam(req, 'description', ''); var subtype = api.getParam(req, 'subtype', 'confirmed'); var datetime = api.getParam(req, 'datetime', null); api.requireSignedIn(req, function(user) { db.Wallet.findOne({ where: { id: wallet_id, user_id: user.id } }) .then(function(wallet) { if (!wallet) throw new errors.HaveNoRightsError(); if (subtype == 'setup') return wallet.setTotalTo({ description: description, amount: amount }); else return wallet.insertTransaction({ description: description, amount: amount, datetime: datetime }); }).then(function(transaction) { res.send(transaction); next(); }); }); }; ================================================ FILE: includes/routes/wallets/transactions/transactions.apib ================================================ # Group Transactions ### List Wallet Transactions [GET /api/wallets/{wallet_id}/transactions] Get list of wallet's transactions + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Attributes (object) + from: (number) - From unix timestamp. Default is now() - 1 month + to: (string) - To unix timestamp. Default is now() + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { "id":53402, "description":"Desc", "amount":-42.33, "abs_amount":42.33, "subtype":"confirmed", "datetime":1449706027, "type":"expense", "user_id":1, "wallet_id":2103 }, { "id":53412, "description":"Text", "amount":0.99, "abs_amount":0.99, "subtype":"confirmed", "datetime":1449736027, "type":"profit", "user_id":1, "wallet_id":2103 } ] ### Add New Transaction [POST /api/wallets/{wallet_id}/transactions] Add new transaction + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + wallet_id: 1 (number, required) - Wallet ID. Should be the same as in URL param + amount: 9.99 (number, required) - Transaction amount + description: Some description (string) - Transaction description + subtype: confirmed (string) - Transaction subtype. Default is 'confirmed'. If subtype is 'setup', it sets wallet total to amount. + datetime: (number) - Default is current unix timestamp + Response 200 (application/json) + Body { "id":53402, "description":"Desc", "amount":-42.33, "abs_amount":42.33, "subtype":"confirmed", "datetime":1449706027, "type":"expense", "user_id":1, "wallet_id":2103 } ### Remove Transaction [DELETE /api/wallets/{wallet_id}/transactions/{transaction_id}] Remove transaction from database. Also recalculate wallet total. + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + transaction_id (number) - ID of the Transaction in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body true ================================================ FILE: includes/routes/wallets/wallets.apib ================================================ # Group Wallets ### List User Wallets [GET /api/wallets] Get list of current user's wallets + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { "id":4, "name":"Cash", "status":"active", "currency":"EUR", "total":300, "origin":"mine" }, { "id":32, "name":"Bitcoins", "status":"active", "currency":"BTC", "total":12.99, "origin":"shared" } ] ### Create New Wallet [POST /api/wallets] Create new wallet under currently signed in user's account + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + name: Somewalletname (string, required) + currency: USD (string, required) - currency identifier. USD, EUR, BTC etc + Response 200 (application/json) + Body { "type":"default", "status":"active", "total":0, "id":2100, "name":"Name", "currency":"USD", "user_id":1 } ### Get Wallet [GET /api/wallets/{wallet_id}] Get wallet information + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { "id":4, "name":"Cash", "status":"active", "currency":"EUR", "total":300, "origin":"mine" }, { "id":32, "name":"Bitcoins", "status":"active", "currency":"BTC", "total":12.99, "origin":"shared" } ] ### Update Wallet [PUT /api/wallets/{wallet_id}] Update wallet under currently signed in user's account. + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Attributes (object) + name: Somewalletname (string) + currency: USD (string) - currency identifier. USD, EUR, BTC etc + status: active (string) - 'active' or 'hidden' + Response 200 (application/json) + Body { "type":"default", "status":"active", "total":0, "id":2100, "name":"Name", "currency":"USD", "user_id":1 } ### Remove Wallet [DELETE /api/wallets/{wallet_id}] Remove wallet from database. As additional protection, this method removes wallet only if its status == 'hidden'. So you have to call PUT method first and set wallet status to 'hidden' and call DELETE after this. + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body true ### List Wallet Goals [GET /api/wallets/{wallet_id}/plans] Get list of wallet's goals + Parameters + wallet_id (number) - ID of the Wallet in the form of an integer + Request (application/json) + Headers authCode: 421a5bbd0624efebf12b2cbe5454b753 + Response 200 (application/json) + Body [ { "id":1, "name":"", "goal_balance":1000, "goal_currency":"USD", "goal_datetime":null, "start_balance":2138.02, "start_currency":"USD", "start_datetime":null, "status":"active", "wallets": [ { "id":1, "name":"Sample Bank Account Wallet", "total":2138.02 } ] } ] ================================================ FILE: includes/servers/images_server.js ================================================ 'use strict'; var rfr = require('rfr'); var fs = require('fs'); var path = require('path'); var mime = require('mime'); function serveImage(opts) { var __cache = {}; function serveFileFromStats(file, err, stats, isGzip, req, res, next) { if (err || !stats.isFile()) { res.writeHead(404, "Not Found"); res.end(); return next(false); } var vsize = stats.size; var vmime = mime.getType(file); var vmtime = stats.mtime; __cache[file] = { size: vsize, mime: vmime, mtime: vmtime }; res.setHeader("Cache-Control", "public, max-age=2592000"); res.setHeader("Expires", new Date(Date.now() + 2592000000).toUTCString()); res.set('Content-Length', __cache[file]['size']); res.set('Content-Type', __cache[file]['mime']); res.setHeader('Content-Type', __cache[file]['mime']); res.set('Last-Modified', __cache[file]['mtime']); res.writeHead(200); fs.readFile(file, function(err, data) { __cache[file]['content'] = data; res.end(data); return next(false); }); } function serveNormal(file, req, res, next) { if (typeof(__cache[file]) !== 'undefined') { res.setHeader("Cache-Control", "public, max-age=2592000"); res.setHeader("Expires", new Date(Date.now() + 2592000000).toUTCString()); res.set('Content-Length', __cache[file]['size']); res.set('Content-Type', __cache[file]['mime']); res.setHeader('Content-Type', __cache[file]['mime']); res.set('Last-Modified', __cache[file]['mtime']); res.writeHead(200); res.end(__cache[file]['content']); next(false); } else { fs.stat(file, function(err, stats) { serveFileFromStats(file, err, stats, false, req, res, next); }); } } function serve(req, res, next) { if (req.headers["if-modified-since"]) { res.writeHead(304, "Not Modified"); res.end(); return next(false); } var file; file = decodeURIComponent(req.path()).split('images/').join(''); file = path.join(rfr.root, './public/images/', file); if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(404, "Not Found"); res.end(); return next(false); } serveNormal(file, req, res, next); } return (serve); } module.exports = serveImage; ================================================ FILE: includes/servers/index.js ================================================ var fs = require('fs'); var servers = {}; fs.readdirSync(__dirname).forEach(function(file) { if (file == "index.js") return; var name = file.substr(0, file.indexOf('.')); servers[name] = require('./' + name); }); module.exports = servers; ================================================ FILE: includes/servers/index_server.js ================================================ var restify = require('restify'); function serveIndex(opts) { var indexFile = opts.indexFile || 'index.html'; var indexDirectory = opts.indexDirectory || './public'; var index = restify.plugins.serveStatic({ directory: indexDirectory, file: indexFile }); return index; } module.exports = serveIndex; ================================================ FILE: includes/servers/minify_server.js ================================================ 'use strict'; var fs = require('fs'); var zlib = require('zlib'); var path = require('path'); var UglifyJS = require("uglify-js"); var CleanCSS = require('clean-css'); var rfr = require('rfr'); var config = rfr('includes/config.js'); function serve(name) { var name = name || 'css'; var type = 'guess'; var cachePath = { cache: path.join(rfr.root, 'data/min/' + name + '.min'), gzip: path.join(rfr.root, 'data/min/' + name + '.min.gz'), raw: path.join(rfr.root, 'data/min/' + name + '.raw') }; var need_to_minify = config.minify[name] || false; var items = config.resources[name] || []; var files = []; var __result = ''; var __raw = ''; var __gzip = ''; var mostRecentMTime = 0; var cacheMTime = 0; var initialized = false; function serve(req, res, next) { if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); res.end('Method not allowed'); return next(); } var callback = function() { doServe(req, res, next); }; if (!initialized) init(callback); else callback(); } function echoContentType(res) { if (type == 'javascript') res.setHeader('Content-Type', 'application/javascript'); else if (type == 'css') res.setHeader('Content-Type', 'text/css'); else res.setHeader('Content-Type', 'text/plain'); return res; } function doServe(req, res, next) { if (req.acceptsEncoding('gzip') && need_to_minify) { res = echoContentType(res); res.setHeader('Content-Encoding', 'gzip'); res.writeHead(200); res.end(__gzip); console.log('Send ' + type + ' resources as gzip'); } else { res = echoContentType(res); res.writeHead(200); if (need_to_minify) res.end(__result); else res.end(__raw); console.log('Send ' + type + ' resources as plain'); } next(); } function addFile(filename) { if (type == 'guess') { if (filename.slice(-3) == '.js') type = 'javascript'; if (filename.slice(-4) == '.css') type = 'css'; } files.push(filename); } function addFolder(pathname) { fs.readdirSync(pathname).forEach(function(file) { if (file.slice(-3) !== '.js' && file.slice(-4) !== '.css') return; addFile(path.join(pathname, file)); }); } function getMTimes(callback) { var gotMTimeCount = 0; var expectedMTimeCount = files.length + 3; /// cached + cached.gz + raw var cbReady = function() { gotMTimeCount++; if (gotMTimeCount == expectedMTimeCount && typeof callback == 'function') callback(); } files.forEach(function(file) { fs.stat(file, function(err, stats) { if (err) return cbReady(); if (typeof(stats['mtime']) !== 'undefined' && stats['mtime'] > mostRecentMTime) mostRecentMTime = stats['mtime']; cbReady(); }); }); var cbCached = function(err, stats) { if (err) return cbReady(); if (typeof(stats['mtime']) !== 'undefined') if (cacheMTime === 0 || stats['mtime'] < cacheMTime) cacheMTime = stats['mtime']; cbReady(); } fs.stat(cachePath.cache, cbCached); fs.stat(cachePath.gzip, cbCached); fs.stat(cachePath.raw, cbCached); } function generateJSHTML(callback) { __raw = ''; __raw += "function inc_js_file(fname) { var js = document.createElement('script'); js.type = 'text/javascript';"; __raw += "js.src = fname; js.async = false; document.body.appendChild(js); }\n"; files.forEach(function(file) { file = file.split(path.join(rfr.root, '/public/')).join('/').split('./public/').join('/').split('public/').join('/'); file = file.split("\\").join("/"); __raw += "inc_js_file(\"" + file + "\");\n"; }) } function minify(callback) { if (type == 'javascript') { console.log('Minify javascript files...'); var code = {}; for (var fName of files) { code[fName] = fs.readFileSync(fName, "utf8"); } var result = UglifyJS.minify(code, { compress: false }); // console.log(files); __result = result.code; generateJSHTML(); var buf = new Buffer(__result, 'utf-8'); zlib.gzip(buf, function(_, res) { console.log('Minify javascript files. Done.'); __gzip = res; fs.writeFileSync(cachePath.cache, __result); fs.writeFileSync(cachePath.gzip, __gzip); fs.writeFileSync(cachePath.raw, __raw); if (typeof callback === 'function') callback(); }); } else if (type == 'css') { console.log('Minify css files...'); new CleanCSS({ rebaseTo: path.join(rfr.root, 'public/'), // relativeTo: path.join(rfr.root, 'public') }).minify(files, function(error, minified) { __result = minified.styles; __raw = __result; var buf = new Buffer(__result, 'utf-8'); zlib.gzip(buf, function(_, res) { __gzip = res; fs.writeFileSync(cachePath.cache, __result); fs.writeFileSync(cachePath.raw, __raw); fs.writeFileSync(cachePath.gzip, __gzip); console.log('Minify css files. Done.'); if (typeof callback === 'function') callback(); }); }); } } function loadFromCache(callback) { var gotCount = 0; var expectedCount = 3; if (!cachePath.gzip) expectedCount--; if (!cachePath.raw) expectedCount--; if (!cachePath.cache) expectedCount--; var cbReady = function() { gotCount++; if (gotCount == expectedCount && typeof callback == 'function') { console.log(type + ' loaded'); callback(); } }; fs.readFile(cachePath.cache, function read(err, data) { if (err) return cbReady(); __result = data; cbReady(); }); fs.readFile(cachePath.gzip, function read(err, data) { if (err) return cbReady(); __gzip = data; cbReady(); }); fs.readFile(cachePath.raw, function read(err, data) { if (err) return cbReady(); __raw = data; cbReady(); }); } function init(callback) { items.forEach(function(item) { if (item.slice(-3) === '.js' || item.slice(-4) === '.css') addFile(path.join(rfr.root, item)); else addFolder(path.join(rfr.root, item)); }); getMTimes(function() { console.log('Most recent mtime(' + type + '): ' + mostRecentMTime); console.log('Cached recent mtime(' + type + '): ' + cacheMTime); if (mostRecentMTime > cacheMTime) { console.log('Minify ' + type); minify(callback); } else { console.log('Load ' + type + ' from cache'); loadFromCache(callback); } }); initialized = true; } return (serve); } module.exports = serve; ================================================ FILE: includes/servers/public_server.js ================================================ var restify = require('restify'); var rfr = require('rfr'); var path = require('path'); var server = restify.plugins.serveStatic({ directory: path.join(rfr.root, '/public/') }); module.exports = server; ================================================ FILE: includes/servers/static_file_server.js ================================================ 'use strict'; var fs = require('fs'); var path = require('path'); var mime = require('mime'); var escapeRE = require('escape-regexp-component'); function serveStatic(opts) { opts = opts || {}; var p = path.normalize(opts.directory).replace(/\\/g, '/'); var re = new RegExp('^' + escapeRE(p) + '/?.*'); function serveFileFromStats(file, err, stats, isGzip, req, res, next) { if (err) { res.writeHead(404, "Not Found"); next(); return; } else if (!stats.isFile()) { res.writeHead(404, "Not Found"); next() return; } if (res.handledGzip && isGzip) { res.handledGzip(); } var fstream = fs.createReadStream(file + (isGzip ? '.gz' : '')); var maxAge = opts.maxAge === undefined ? 3600 : opts.maxAge; fstream.once('open', function(fd) { res.cache({ maxAge: maxAge }); res.set('Content-Length', stats.size); var mimeType = mime.getType(file); if (mimeType == 'application/vnd.groove-tool-template') mimeType = 'text/html'; res.set('Content-Type', mimeType); res.set('Last-Modified', stats.mtime); res.setHeader('Access-Control-Allow-Origin', '*'); if (opts.charSet) { var type = res.getHeader('Content-Type') + '; charset=' + opts.charSet; res.setHeader('Content-Type', type); } if (opts.etag) { res.set('ETag', opts.etag(stats, opts)); } res.writeHead(200); fstream.pipe(res); fstream.once('end', function() { next(false); }); }); } function serveNormal(file, req, res, next) { fs.stat(file, function(err, stats) { if (!err && stats.isDirectory() && opts.default) { // Serve an index.html page or similar file = path.join(file, opts.default); fs.stat(file, function(dirErr, dirStats) { serveFileFromStats(file, dirErr, dirStats, false, req, res, next); }); } else { serveFileFromStats(file, err, stats, false, req, res, next); } }); } function serve(req, res, next) { var file; if (opts.file) { //serves a direct file file = path.join(opts.directory, decodeURIComponent(opts.file)); } else { file = path.join(opts.directory, decodeURIComponent(req.path())); } if (opts.suffix) file += opts.suffix; if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(404, "Not Found"); next(); return; } if (!re.test(file.replace(/\\/g, '/'))) { res.writeHead(404, "Not Found"); next(); return; } if (opts.match && !opts.match.test(file)) { res.writeHead(404, "Not Found"); next(); return; } if (opts.gzip && req.acceptsEncoding('gzip')) { fs.stat(file + '.gz', function(err, stats) { if (!err) { res.setHeader('Content-Encoding', 'gzip'); serveFileFromStats(file, err, stats, true, req, res, next); } else { serveNormal(file, req, res, next); } }); } else { serveNormal(file, req, res, next); } } return (serve); } module.exports = serveStatic; ================================================ FILE: includes/test/planning.test.js ================================================ var hippie = require('hippie'); var rfr = require('rfr'); var expect = require('chai').expect; var assert = require('chai').assert; var testHelper = rfr('includes/test.js'); var db = rfr('includes/models'); describe('API server for planning', function() { /// Data for user registration var email = 'email' + Math.random() + '@example.com'; var login = 'login' + Math.random(); var password = 'password' + Math.random(); var registeredUserId = null; var auth_code = null; var wallet_1_name = 'name ' + Math.random(); var wallet_1_currency = 'UAH'; var wallet_1_id = null; var wallet_1_initial_amount = 200.99; var wallet_2_name = 'name2 ' + Math.random(); var wallet_2_currency = 'USD'; var wallet_2_id = null; var wallet_2_initial_amount = 100.99; var plan_1_name = 'Test Name'; var plan_1_currency = 'UAH'; var plan_1_goal_balance = 1000; var plan_1_goal_datetime = (Date.now() / 1000 | 0) + 60 * 24 * 60 * 60; var plan_1_id = null; var plan_1 = null; var plan_2_name = 'Test 2 Name'; var plan_2_currency = 'USD'; var plan_2_goal_balance = 1000; var plan_2_goal_datetime = (Date.now() / 1000 | 0) + 60 * 24 * 60 * 60; var plan_2_id = null; var plan_2 = null; it('registers user', function(done) { testHelper.sendPost('/api/users', { email: email, login: login, password: password }).then(function(data) { expect(data.body.id).to.be.a('number'); expect(data.body.email).to.be.a('string'); expect(data.body.email).to.equal(email); expect(data.body.login).to.be.a('string'); expect(data.body.login).to.equal(login); expect(data.body.auth_code).to.be.a('string'); assert.ok(data.cookies.is_logged_in_user); expect(data.cookies.logged_in_user).to.equal(data.body.auth_code); registeredUserId = data.body.id; auth_code = data.body.auth_code; done(); }); }); it('signs him in on registration', function(done) { testHelper.sendGet('/api/users').then(function(data) { expect(data.body.id).to.be.a('number'); expect(data.body.id).to.equal(registeredUserId); done(); }); }); it('returns empty plans list for new user', function(done) { testHelper.sendGet('/api/plans').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(0); done(); }); }); it('adds new wallet', function(done) { testHelper.sendPost('/api/wallets', { name: wallet_1_name, currency: wallet_1_currency }).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); expect(data.body.name).to.equal(wallet_1_name); expect(data.body.total).to.equal(0); expect(data.body.status).to.equal('active'); expect(data.body.currency).to.equal(wallet_1_currency); wallet_1_id = data.body.id; done(); }); }); it('lets us add some income transaction to wallet', function(done) { testHelper.sendPost('/api/wallets/' + wallet_1_id + '/transactions/', { wallet_id: wallet_1_id, amount: wallet_1_initial_amount, description: 'Initial' }).then(function(data) { expect(data.body.amount).to.equal(wallet_1_initial_amount); done(); }); }); it('allow to create new plan', function(done) { var newData = { name: plan_1_name, goal_currency: plan_1_currency, goal_balance: plan_1_goal_balance, goal_datetime: plan_1_goal_datetime, wallets: [wallet_1_id] }; testHelper.sendPost('/api/plans', newData).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); expect(data.body.name).to.equal(newData.name); expect(data.body.goal_currency).to.equal(newData.goal_currency); expect(data.body.start_currency).to.equal(newData.goal_currency); expect(data.body.goal_balance).to.equal(newData.goal_balance); expect(data.body.goal_datetime).to.equal(plan_1_goal_datetime); expect(data.body.wallets).to.be.a('array'); expect(data.body.wallets).to.have.length(1); expect(data.body.wallets[0].id).to.equal(wallet_1_id); /// start_balance should be calculated from wallets expect(data.body.start_balance).to.equal(wallet_1_initial_amount); plan_1_id = data.body.id; plan_1 = data.body; done(); }); }); it('returns plans list with 1 plan now', function(done) { testHelper.sendGet('/api/plans').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(1); done(); }); }); it('returns plans list for wallet', function(done) { testHelper.sendGet('/api/wallets/' + wallet_1_id + '/plans').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(1); expect(data.body[0].id).to.equal(plan_1_id); done(); }); }); it('allow to edit plan', function(done) { plan_1_name = plan_1_name + 'updated'; plan_1_currency = 'USD'; plan_1_goal_balance = 2000; plan_1_goal_datetime = plan_1_goal_datetime + 60 * 24 * 60 * 60; // 120 days total var newData = { name: plan_1_name, goal_currency: plan_1_currency, goal_balance: plan_1_goal_balance, goal_datetime: plan_1_goal_datetime, wallets: [wallet_1_id] }; testHelper.sendPut('/api/plans/' + plan_1_id, newData).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); /// Updated fields expect(data.body.name).to.equal(newData.name); expect(data.body.goal_currency).to.equal(newData.goal_currency); expect(data.body.goal_balance).to.equal(newData.goal_balance); expect(data.body.goal_datetime).to.equal(plan_1_goal_datetime); // Kept fields expect(data.body.wallets).to.be.a('array'); expect(data.body.wallets).to.have.length(1); expect(data.body.wallets[0].id).to.equal(wallet_1_id); expect(data.body.start_currency).to.equal(plan_1.start_currency); expect(data.body.start_balance).to.equal(plan_1.start_balance); expect(data.body.start_datetime).to.equal(plan_1.start_datetime); plan_1 = data.body; done(); }); }); it('adds another new wallet', function(done) { testHelper.sendPost('/api/wallets', { name: wallet_2_name, currency: wallet_2_currency }).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); expect(data.body.name).to.equal(wallet_2_name); expect(data.body.total).to.equal(0); expect(data.body.status).to.equal('active'); expect(data.body.currency).to.equal(wallet_2_currency); wallet_2_id = data.body.id; done(); }); }); it('allow to edit plan, adding another wallets to it', function(done) { var newData = { wallets: [wallet_1_id, wallet_2_id] }; testHelper.sendPut('/api/plans/' + plan_1_id, newData).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); /// Updated fields expect(data.body.wallets).to.be.a('array'); expect(data.body.wallets).to.have.length(2); var found_wallet_1 = false; var found_wallet_2 = false; for (var k in data.body.wallets) { if (data.body.wallets[k].id == wallet_1_id) found_wallet_1 = true; if (data.body.wallets[k].id == wallet_2_id) found_wallet_2 = true; } assert.ok(found_wallet_1); assert.ok(found_wallet_2); // Kept fields expect(data.body.name).to.equal(plan_1.name); expect(data.body.goal_currency).to.equal(plan_1.goal_currency); expect(data.body.goal_balance).to.equal(plan_1.goal_balance); expect(data.body.goal_datetime).to.equal(plan_1.goal_datetime); expect(data.body.start_currency).to.equal(plan_1.start_currency); expect(data.body.start_balance).to.equal(plan_1.start_balance); expect(data.body.start_datetime).to.equal(plan_1.start_datetime); plan_1 = data.body; done(); }); }); it('returns plans list for wallet with 2 wallets ids in plan', function(done) { testHelper.sendGet('/api/wallets/' + wallet_1_id + '/plans').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(1); expect(data.body[0].id).to.equal(plan_1_id); var found_wallet_1 = false; var found_wallet_2 = false; for (var k in data.body[0].wallets) { if (data.body[0].wallets[k].id == wallet_1_id) found_wallet_1 = true; if (data.body[0].wallets[k].id == wallet_2_id) found_wallet_2 = true; } assert.ok(found_wallet_1); assert.ok(found_wallet_2); done(); }); }); it('allow to create another plan', function(done) { var newData = { name: plan_2_name, goal_currency: plan_2_currency, goal_balance: plan_2_goal_balance, goal_datetime: plan_2_goal_datetime, wallets: [wallet_1_id, wallet_2_id] }; testHelper.sendPost('/api/plans', newData).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); expect(data.body.name).to.equal(newData.name); expect(data.body.goal_currency).to.equal(newData.goal_currency); expect(data.body.start_currency).to.equal(newData.goal_currency); expect(data.body.goal_balance).to.equal(newData.goal_balance); expect(data.body.goal_datetime).to.equal(plan_2_goal_datetime); expect(data.body.wallets).to.be.a('array'); expect(data.body.wallets).to.have.length(2); plan_2_id = data.body.id; plan_2 = data.body; done(); }); }); it('returns plans list for wallet with 2 plans', function(done) { testHelper.sendGet('/api/wallets/' + wallet_2_id + '/plans').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(2); done(); }); }); it('allow to edit plan setting goal_datetime to the past. For testing', function(done) { var newData = { goal_datetime: (Date.now() / 1000 | 0) }; testHelper.sendPut('/api/plans/' + plan_2_id, newData).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); expect(data.body.goal_datetime).to.equal(newData.goal_datetime); plan_2 = data.body; done(); }); }); it('returns plan with status == finished now', function(done) { testHelper.sendGet('/api/wallets/' + wallet_2_id + '/plans').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(2); var foundPlan = null; for (var k in data.body) if (data.body[k].id == plan_2_id) foundPlan = data.body[k]; expect(foundPlan).to.not.equal(null); expect(foundPlan.status).to.equal('finished'); done(); }); }); it('returns plan with status == finished now', function(done) { testHelper.sendGet('/api/plans/' + plan_2_id).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); expect(data.body.status).to.equal('finished'); done(); }); }); it('lets us remove plan', function(done) { testHelper.sendDelete('/api/plans/' + plan_1_id, {}).then(function(data) { expect(data.body).to.equal(true); done(); }); }); it('returns list without removed plan now', function(done) { testHelper.sendGet('/api/plans').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(1); done(); }); }); it('lets us remove second plan', function(done) { testHelper.sendDelete('/api/plans/' + plan_2_id, {}).then(function(data) { expect(data.body).to.equal(true); done(); }); }); it('returns empty plans list now', function(done) { testHelper.sendGet('/api/plans').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(0); done(); }); }); var remove_account_code = null; it('allow to initialize remove account procedure for signed in user', function(done) { testHelper.sendPostAndExpectStatus('/api/users/' + registeredUserId + '/removeaccount', {}, '200').then(function(data) { expect(data.body).to.equal(true); db.User.findOne({ where: { id: registeredUserId } }).then(function(user) { expect(registeredUserId).to.equal(user.id); remove_account_code = user.remove_account_code; done(); }); }); }); it('allow to finish remove account procedure', function(done) { testHelper.sendPostAndExpectStatus('/api/users/' + registeredUserId + '/removeaccount', { code: remove_account_code }, '200').then(function(data) { expect(data.body).to.equal(true); /// double check that user is removed db.User.findOne({ where: { id: registeredUserId } }).then(function(user) { expect(user).to.equal(null); done(); }); }); }); }); ================================================ FILE: includes/test/stats.test.js ================================================ var hippie = require('hippie'); var rfr = require('rfr'); var expect = require('chai').expect; var assert = require('chai').assert; var testHelper = rfr('includes/test.js'); var db = rfr('includes/models'); describe('API server for statistics', function() { var email = 'email' + Math.random() + '@example.com'; var login = 'login' + Math.random(); var password = 'password' + Math.random(); var registeredUserId = null; var auth_code = null; var wallet_1_name = 'name ' + Math.random(); var wallet_1_currency = 'USD'; var wallet_1_id = null; var wallet_2_name = 'name ' + Math.random(); var wallet_2_currency = 'UAH'; var wallet_2_id = null; it('registers user', function(done) { testHelper.sendPost('/api/users', { email: email, login: login, password: password }).then(function(data) { expect(data.body.id).to.be.a('number'); registeredUserId = data.body.id; auth_code = data.body.auth_code; done(); }); }); it('adds new wallet', function(done) { testHelper.sendPost('/api/wallets', { name: wallet_1_name, currency: wallet_1_currency }).then(function(data) { wallet_1_id = data.body.id; done(); }); }); it('adds new wallet', function(done) { testHelper.sendPost('/api/wallets', { name: wallet_2_name, currency: wallet_2_currency }).then(function(data) { wallet_2_id = data.body.id; done(); }); }); it('lets us add some income transaction to wallet', function(done) { testHelper.sendPost('/api/wallets/' + wallet_1_id + '/transactions/', { wallet_id: wallet_1_id, amount: 10, description: 'Initial' }).then(function(data) { done(); }); }); it('lets us add some expense transaction to wallet', function(done) { testHelper.sendPost('/api/wallets/' + wallet_1_id + '/transactions/', { wallet_id: wallet_1_id, amount: -99, description: 'Initial' }).then(function(data) { done(); }); }); it('lets us add some income transaction to wallet 2', function(done) { testHelper.sendPost('/api/wallets/' + wallet_2_id + '/transactions/', { wallet_id: wallet_2_id, amount: 99, description: 'Initial' }).then(function(data) { done(); }); }); it('lets us add some income transaction to wallet 2', function(done) { testHelper.sendPost('/api/wallets/' + wallet_2_id + '/transactions/', { wallet_id: wallet_2_id, amount: 99, description: 'Initial' }).then(function(data) { done(); }); }); it('gets week transactions', function(done) { testHelper.sendGet('/api/stats/week?utcoffset=-3').then(function(data) { expect(data.body).to.have.length(7); expect(data.body[0].stats).to.be.an('object'); expect(data.body[0].stats[wallet_1_currency]).to.be.an('object'); expect(data.body[0].stats[wallet_2_currency]).to.be.an('object'); expect(data.body[0].stats[wallet_1_currency].expense).to.equal(99); expect(data.body[0].stats[wallet_2_currency].expense).to.equal(0); expect(data.body[0].stats[wallet_1_currency].profit).to.equal(10); expect(data.body[0].stats[wallet_2_currency].profit).to.equal(198); done(); }); }); it('gets by wallet week transactions', function(done) { testHelper.sendGet('/api/wallets/'+wallet_1_id+'/stats/week?utcoffset=-3').then(function(data) { expect(data.body).to.have.length(7); expect(data.body[0].stats).to.be.an('object'); expect(data.body[0].stats[wallet_1_currency]).to.be.an('object'); expect(data.body[0].stats[wallet_1_currency].expense).to.equal(99); expect(data.body[0].stats[wallet_1_currency].profit).to.equal(10); done(); }); }); it('gets by wallet2 week transactions', function(done) { testHelper.sendGet('/api/wallets/'+wallet_2_id+'/stats/week?utcoffset=-3').then(function(data) { expect(data.body).to.have.length(7); expect(data.body[0].stats).to.be.an('object'); expect(data.body[0].stats[wallet_2_currency]).to.be.an('object'); expect(data.body[0].stats[wallet_2_currency].expense).to.equal(0); expect(data.body[0].stats[wallet_2_currency].profit).to.equal(198); done(); }); }); it('shoud not return others wallets stats', function(done) { testHelper.sendGetAndExpectStatus('/api/wallets/1/stats/week?utcoffset=-3', "!200").then(function() { done(); }); }); it('gets year transactions', function(done) { testHelper.sendGet('/api/stats/year?utcoffset=-3').then(function(data) { expect(data.body).to.have.length(12); expect(data.body[0].stats).to.be.an('object'); expect(data.body[0].stats[wallet_1_currency]).to.be.an('object'); expect(data.body[0].stats[wallet_2_currency]).to.be.an('object'); expect(data.body[0].stats[wallet_1_currency].expense).to.equal(99); expect(data.body[0].stats[wallet_2_currency].expense).to.equal(0); expect(data.body[0].stats[wallet_1_currency].profit).to.equal(10); expect(data.body[0].stats[wallet_2_currency].profit).to.equal(198); done(); }); }); var remove_account_code = null; it('allow to initialize remove account procedure for signed in user', function(done) { testHelper.sendPostAndExpectStatus('/api/users/' + registeredUserId + '/removeaccount', {}, '200').then(function(data) { expect(data.body).to.equal(true); db.User.findOne({ where: { id: registeredUserId } }).then(function(user) { remove_account_code = user.remove_account_code; done(); }); }); }); it('allow to finish remove account procedure', function(done) { testHelper.sendPostAndExpectStatus('/api/users/' + registeredUserId + '/removeaccount', { code: remove_account_code }, '200').then(function(data) { expect(data.body).to.equal(true); done(); }); }); }); ================================================ FILE: includes/test/wallet.test.js ================================================ var hippie = require('hippie'); var rfr = require('rfr'); var expect = require('chai').expect; var assert = require('chai').assert; var testHelper = rfr('includes/test.js'); var db = rfr('includes/models'); describe('API server', function() { /// Data for user registration var email = 'email' + Math.random() + '@example.com'; var login = 'login' + Math.random(); var password = 'password' + Math.random(); var registeredUserId = null; var auth_code = null; var wallet_1_name = 'name ' + Math.random(); var wallet_1_currency = 'USD'; var wallet_1_id = null; var wallet_1_initial_amount = 200.99; it('registers user', function(done) { testHelper.sendPost('/api/users', { email: email, login: login, password: password }).then(function(data) { expect(data.body.id).to.be.a('number'); expect(data.body.email).to.be.a('string'); expect(data.body.email).to.equal(email); expect(data.body.login).to.be.a('string'); expect(data.body.login).to.equal(login); expect(data.body.auth_code).to.be.a('string'); expect(data.cookies.is_logged_in_user).to.be.ok; expect(data.cookies.logged_in_user).to.equal(data.body.auth_code); registeredUserId = data.body.id; auth_code = data.body.auth_code; done(); }); }); it('signs him in on registration', function(done) { testHelper.sendGet('/api/users').then(function(data) { expect(data.body.id).to.be.a('number'); expect(data.body.id).to.equal(registeredUserId); done(); }); }); it('returns empty wallets list for new (not demo) user', function(done) { testHelper.sendGet('/api/wallets').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(0); done(); }); }); it('allows him to sign out', function(done) { testHelper.sendPost('/api/users/signout', null).then(function(data) { done(); }); }); it('does not allow to remove account for signed out user', function(done) { testHelper.sendGetAndExpectStatus('/api/users/' + registeredUserId + '/removeaccount', "!200").then(function() { done(); }); }); it('does not show signed out user info', function(done) { testHelper.sendGetAndExpectStatus('/api/users', 500).then(function() { done(); }); }); it('allows him to sign in', function(done) { testHelper.sendPost('/api/users/signin', { username: login, password: password }).then(function(data) { expect(data.cookies.is_logged_in_user).to.be.ok; expect(data.cookies.logged_in_user).to.equal(data.body.auth_code); expect(data.body.id).to.equal(registeredUserId); auth_code = data.body.auth_code; done(); }); }); it('allows to confirm that user is signed in', function(done) { testHelper.sendGet('/api/users').then(function(data) { expect(data.body.id).to.be.a('number'); expect(data.body.id).to.equal(registeredUserId); done(); }); }); it('adds new wallet', function(done) { testHelper.sendPost('/api/wallets', { name: wallet_1_name, currency: wallet_1_currency }).then(function(data) { expect(data.body.user_id).to.equal(registeredUserId); expect(data.body.name).to.equal(wallet_1_name); expect(data.body.total).to.equal(0); expect(data.body.status).to.equal('active'); expect(data.body.currency).to.equal(wallet_1_currency); wallet_1_id = data.body.id; done(); }); }); it('returns updated wallets list', function(done) { testHelper.sendGet('/api/wallets').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(1); expect(data.body[0].id).to.equal(wallet_1_id); expect(data.body[0].name).to.equal(wallet_1_name); expect(data.body[0].status).to.equal('active'); expect(data.body[0].origin).to.equal('mine'); expect(data.body[0].currency).to.equal(wallet_1_currency); done(); }); }); it('lets us edit wallet name and currency', function(done) { wallet_1_name = wallet_1_name + '_updated'; wallet_1_currency = 'EUR'; testHelper.sendPut('/api/wallets/' + wallet_1_id, { name: wallet_1_name, currency: wallet_1_currency }).then(function(data) { expect(data.body.name).to.equal(wallet_1_name); expect(data.body.currency).to.equal(wallet_1_currency); done(); }); }); it('lets us add some income transaction to wallet', function(done) { testHelper.sendPost('/api/wallets/' + wallet_1_id + '/transactions/', { wallet_id: wallet_1_id, amount: wallet_1_initial_amount, description: 'Initial' }).then(function(data) { expect(data.body).to.be.a('object'); expect(data.body.amount).to.equal(wallet_1_initial_amount); expect(data.body.wallet_id).to.equal(wallet_1_id); expect(data.body.user_id).to.equal(registeredUserId); expect(data.body.description).to.equal('Initial'); done(); }); }); it('updates wallet total with transactions', function(done) { testHelper.sendGet('/api/wallets/' + wallet_1_id).then(function(data) { expect(data.body).to.be.a('object'); expect(data.body.total).to.equal(wallet_1_initial_amount); done(); }); }); // wallet_1_initial_amount = 200.99 var testTransactions = []; testTransactions.push({ amount: -0.99, shouldSetTotalTo: wallet_1_initial_amount - 0.99, // 200 whenRemovedShouldSetTotalTo: 900 }); testTransactions.push({ amount: -100, shouldSetTotalTo: wallet_1_initial_amount - 0.99 - 100, // 100 whenRemovedShouldSetTotalTo: 900 }); testTransactions.push({ subtype: 'setup', amount: 201, /// setup amount is +101.00 shouldSetTotalTo: 201, //// setup transaction set wallet total to its amount, whenRemovedShouldSetTotalTo: 900 }); testTransactions.push({ amount: 99, shouldSetTotalTo: 300, whenRemovedShouldSetTotalTo: 900 }); testTransactions.push({ subtype: 'setup', amount: 1000, /// setup amount is +700.00 shouldSetTotalTo: 1000, whenRemovedShouldSetTotalTo: 100.99 //// initial - last }); testTransactions.push({ amount: -100, shouldSetTotalTo: 900, whenRemovedShouldSetTotalTo: 200.99 /// initial }); testTransactions.forEach(function(testTransaction, index, array) { it('lets us add another sample transaction', function(done) { var data = { wallet_id: wallet_1_id, amount: testTransaction.amount, description: 'fasd' }; if (typeof(testTransaction.subtype) !== 'undefined') data.subtype = testTransaction.subtype; testHelper.sendPost('/api/wallets/' + wallet_1_id + '/transactions/', data).then(function(data) { expect(data.body).to.be.a('object'); if (data.body.subtype === 'confirmed') expect(data.body.amount).to.equal(testTransaction.amount); array[index]['id'] = data.body.id; done(); }); }); it('updates wallet total with sample transactions', function(done) { testHelper.sendGet('/api/wallets/' + wallet_1_id).then(function(data) { expect(data.body).to.be.a('object'); expect(data.body.total).to.equal(testTransaction.shouldSetTotalTo); done(); }); }); }); it('should allow to check that all transactions added', function(done) { testHelper.sendGet('/api/wallets/' + wallet_1_id + '/transactions/').then(function(data) { expect(data.body).to.be.a('array'); var somethingIsNotFound = false; testTransactions.forEach(function(testTransaction) { var found = false; for (var k in data.body) if (data.body[k].id == testTransaction.id) found = true; if (!found) somethingIsNotFound = true; }); expect(somethingIsNotFound).to.equal(false); done(); }); }); testTransactions.forEach(function(testTransaction) { it('should let us remove transaction', function(done) { testHelper.sendDelete('/api/wallets/' + wallet_1_id + '/transactions/' + testTransaction.id).then(function(data) { expect(data.body).to.equal(true); done(); }); }); it('should allow to double check that transaction is removed', function(done) { testHelper.sendGet('/api/wallets/' + wallet_1_id + '/transactions').then(function(data) { expect(data.body).to.be.a('array'); var found = false; for (var k in data.body) if (data.body[k].id == testTransaction.id) found = true; expect(found).to.equal(false); done(); }); }); it('updates wallet total when transaction is removed', function(done) { testHelper.sendGet('/api/wallets/' + wallet_1_id).then(function(data) { expect(data.body).to.be.a('object'); expect(+parseFloat(data.body.total).toFixed(2)).to.equal(testTransaction.whenRemovedShouldSetTotalTo); done(); }); }); }); it('does not allow to remove wallet instantly', function(done) { testHelper.sendDeleteAndExpectStatus('/api/wallets/' + wallet_1_id, '!200').then(function(data) { done(); }); }); it('hides wallet with PUT method', function(done) { testHelper.sendPut('/api/wallets/' + wallet_1_id, { status: 'hidden' }).then(function(data) { expect(data.body.status).to.equal('hidden'); done(); }); }); it('allow to remove hidden wallet', function(done) { testHelper.sendDelete('/api/wallets/' + wallet_1_id).then(function(data) { expect(data.body).to.equal(true); done(); }); }); it('returns empty wallets list now, as we have removed the only wallet', function(done) { testHelper.sendGet('/api/wallets').then(function(data) { expect(data.body).to.be.a('array'); expect(data.body).to.have.length(0); done(); }); }); var remove_account_code = null; it('allow to initialize remove account procedure for signed in user', function(done) { testHelper.sendPostAndExpectStatus('/api/users/' + registeredUserId + '/removeaccount', {}, '200').then(function(data) { expect(data.body).to.equal(true); db.User.findOne({ where: { id: registeredUserId } }).then(function(user) { expect(registeredUserId).to.equal(user.id); remove_account_code = user.remove_account_code; done(); }); }); }); it('does not allow to finish account remove procedure with wrong remove_account_code', function(done) { testHelper.sendPostAndExpectStatus('/api/users/' + registeredUserId + '/removeaccount', { code: 'wrong' }, '200').then(function(data) { expect(data.body).to.equal(false); done(); }); }); it('does not allow to finish account remove procedure with good remove_account_code, but wrong user_id parameter', function(done) { testHelper.sendPostAndExpectStatus('/api/users/' + registeredUserId - 2 + '/removeaccount', { code: remove_account_code }, '!200').then(function(data) { done(); }); }); it('allow to finish remove account procedure', function(done) { testHelper.sendPostAndExpectStatus('/api/users/' + registeredUserId + '/removeaccount', { code: remove_account_code }, '200').then(function(data) { expect(data.body).to.equal(true); /// double check that user is removed db.User.findOne({ where: { id: registeredUserId } }).then(function(user) { expect(user).to.equal(null); done(); }); }); }); }); ================================================ FILE: includes/test.js ================================================ var hippie = require('hippie'); var expect = require('chai').expect; var Sequelize = require('sequelize'); var rfr = require('rfr'); var config = rfr('includes/config.js'); var base = 'http://localhost:' + config.port; var timeout = 500; var prepareResolve = function(err, res, body, resolve) { if (err) throw err; var headers = res.headers; var cookies = {}; if (typeof(headers['set-cookie']) !== 'undefined' && headers['set-cookie']) { headers['set-cookie'].forEach(function(cookie) { var parts = cookie.split('='); cookies[parts.shift().trim()] = decodeURI(parts.join('=').split('; ')[0]); }); } var bodyTypeIsGood = false; if (Array.isArray(body) || (typeof body === 'object' && Object.prototype.toString.call(body) === '[object Array]')) bodyTypeIsGood = true; else if (body !== null && typeof body === 'object') bodyTypeIsGood = true; else if (typeof body === 'boolean') bodyTypeIsGood = true; expect(bodyTypeIsGood).to.equal(true, "Invalid response body. Should be one of(array, object, boolean)"); resolve({ body: body, headers: headers, cookies: cookies }); }; var prepareResolveStatus = function(err, res, body, resolve, status) { var resStatus = 0; if (typeof res !== 'undefined' && typeof res.statusCode !== 'undefined') resStatus = res.statusCode; if (typeof(status) === 'string' && status.substr(0, 1) === '!') { var statusToNotExpect = parseInt(status.split('!').join(''), 10); if (statusToNotExpect == resStatus) { console.error("Body:"); console.error(body); } expect(resStatus).to.not.equal(statusToNotExpect, "Invalid response status code"); } else { var statusToExpect = parseInt(status, 10); if (statusToExpect != resStatus) { console.error("Body:"); console.error(body); } expect(resStatus).to.equal(statusToExpect, "Invalid response status code"); } resolve({ body: body }); }; var prepareHippie = function(method, endpoint, data) { var hippieCall = hippie() .json() .base(base) .timeout(timeout) .use(persistCookies); if (method == 'post') { return hippieCall.post(endpoint).send(data); } else if (method == 'delete' || method == 'del') { return hippieCall.del(endpoint); } else if (method == 'put') { return hippieCall.put(endpoint).send(data); } else return hippieCall.get(endpoint); } var sendPostAndExpectStatus = function(endpoint, data, status) { return new Sequelize.Promise(function(resolve, reject) { prepareHippie('post', endpoint, data) .end(function(err, res, body) { prepareResolveStatus(err, res, body, resolve, status); }); }); }; var sendPost = function(endpoint, data) { return new Sequelize.Promise(function(resolve, reject) { prepareHippie('post', endpoint, data) .end(function(err, res, body) { prepareResolve(err, res, body, resolve); }); }); }; var sendGetAndExpectStatus = function(endpoint, status) { return new Sequelize.Promise(function(resolve, reject) { prepareHippie('get', endpoint) .end(function(err, res, body) { prepareResolveStatus(err, res, body, resolve, status); }); }); }; var sendGet = function(endpoint) { return new Sequelize.Promise(function(resolve, reject) { prepareHippie('get', endpoint) .end(function(err, res, body) { prepareResolve(err, res, body, resolve); }); }); }; var sendDeleteAndExpectStatus = function(endpoint, status) { return new Sequelize.Promise(function(resolve, reject) { prepareHippie('del', endpoint) .end(function(err, res, body) { prepareResolveStatus(err, res, body, resolve, status); }); }); }; var sendDelete = function(endpoint) { return new Sequelize.Promise(function(resolve, reject) { prepareHippie('del', endpoint) .end(function(err, res, body) { prepareResolve(err, res, body, resolve); }); }); }; var sendPut = function(endpoint, data) { return new Sequelize.Promise(function(resolve, reject) { prepareHippie('put', endpoint, data) .end(function(err, res, body) { prepareResolve(err, res, body, resolve); }); }); }; var persistCookies = function(opts, next) { opts.jar = true; next(opts); }; exports.sendPost = sendPost; exports.sendGet = sendGet; exports.sendPut = sendPut; exports.sendDelete = sendDelete; exports.sendPostAndExpectStatus = sendPostAndExpectStatus; exports.sendGetAndExpectStatus = sendGetAndExpectStatus; exports.sendDeleteAndExpectStatus = sendDeleteAndExpectStatus; ================================================ FILE: index.js ================================================ var CookieParser = require('restify-cookies'); var restify = require('restify'); var rfr = require('rfr'); var db = rfr('includes/models'); var routes = rfr('includes/routes'); var servers = rfr('includes/servers'); var pages = rfr('config/pages.json'); var config = rfr('includes/config.js'); var path = require('path'); var startServer = function(options, callback) { options = options || {}; var server = restify.createServer({ name: 'DimeShift', handleUncaughtExceptions: true }); // Server settings server.pre(restify.pre.sanitizePath()); server.on('uncaughtException', function(req, res, route, err) { try { res.json(500, err); } catch (e) { res.end(); } return true; }); db.Sequelize.Promise.onPossiblyUnhandledRejection(function(reason) { throw reason; }); server.use(CookieParser.parse); server.use(restify.plugins.queryParser()); server.use(restify.plugins.bodyParser()); // API routes routes(function(routes) { routes.forEach(function(route) { server[route.method](route.route, route.handler); }); }); // Templates var templatesDirectory = path.join(rfr.root, './public'); server.get('/jstemplates/*', servers.static_file_server({ directory: templatesDirectory, suffix: '.tpl' })); // Static files and css/js minification server.get('/images/*', servers.images_server()); server.get('/scripts/*', servers.public_server); server.get('/vendors/*', servers.public_server); server.get('/resources/js.js', servers.minify_server('javascript')); server.get('/css.css', servers.minify_server('css')); // App index html file for (var k in pages) { server.get(k, servers.index_server({ indexFile: options.indexFile, indexDirectory: options.indexDirectory })); } // Sync db and start server db.sequelize.sync() .then(function(err) { var port = config.port || process.env.PORT || 8080; var doStart = function(selectedPort) { server.listen(selectedPort); console.log("Server started: http://localhost:" + selectedPort + "/"); if (typeof(callback) === 'function') callback(selectedPort); } if (typeof(port) === 'function') port(doStart); else doStart(port); }); }; if (!module.parent) { startServer(); } else { module.exports = startServer; } ================================================ FILE: package.json ================================================ { "name": "dimeshift", "version": "0.1.42", "description": "Webapp to track and manage personal finances", "main": "index.js", "engines": { "node": "10.15.2" }, "scripts": { "start": "node index.js", "test": "node_modules/.bin/mocha includes/test", "postinstall": "bower install" }, "repository": { "type": "git", "url": "https://github.com/jeka-kiselyov/dimeshift.git" }, "author": "Jeka Kiselyov (https://github.com/jeka-kiselyov)", "license": "AGPL-3.0", "keywords": [ "finance", "financial", "single page", "single page application", "application", "saas", "api", "currency", "economy", "ukrainian", "russian", "backbonejs", "restify" ], "bundledDependencies": [ "rfr" ], "dependencies": { "bower": "^1.6.3", "clean-css": "^4.2.1", "escape-regexp-component": "^1.0.2", "grunt-contrib-concat": "^1.0.0", "grunt-exec": "^3.0.0", "mime": "^2.4.2", "moment": "^2.13.0", "money": "^0.2.0", "mysql": "^2.17.1", "mysql2": "^1.6.5", "nodemailer": "^6.1.1", "open-exchange-rates": "^0.3.0", "pg": "^6.4.2", "pg-hstore": "^2.3.2", "request": "^2.88.0", "restify": "^8.3.0", "restify-cookies": "^0.2.5", "restify-errors": "^7.0.0", "rfr": "^1.2.2", "sequelize": "^3.10.0", "sqlite3": "^4.0.9", "uglify-js": "^3.5.6" }, "devDependencies": { "chai": "^4.2.0", "grunt": "^1.0.4", "grunt-concurrent": "^2.0.3", "grunt-contrib-watch": "^1.1.0", "grunt-env": "^0.4.4", "grunt-mocha-cli": "^4.0.0", "grunt-nodemon": "^0.4.0", "grunt-run": "^0.8.1", "hippie": "^0.5.2", "mocha": "^6.1.4", "open": "^6.1.0" } } ================================================ FILE: public/css/.gitignore ================================================ dist/* fonts/* ================================================ FILE: public/css/main.css ================================================ ================================================ FILE: public/css/parts/dialogs/base.css ================================================ .modal-loading { height: 100px; text-indent: -9999px; background: white url('/images/loading.gif') center center no-repeat; } ================================================ FILE: public/css/parts/dialogs/registration.css ================================================ .social_signin { text-align: left; margin-bottom: 20px; } .registration_dialog h3, .signin_dialog h3 { margin: 0; padding: 0 0 10px 0; color: #333; font-size: 15px; font-weight: normal; } .social_signin_divider { margin: 15px 0 18px 0; } .social_signin_divider_h { float: left; width: 45%; overflow: hidden; height: 11px; border-bottom: 1px solid #333; } .social_signin_divider_or { float: left; width: 10%; overflow: hidden; height: 20px; font-size: 16px; vertical-align: middle; line-height: 20px; text-align: center; color: #333 } .social_signin_divider_cl { clear: both; } ================================================ FILE: public/css/parts/dialogs/signin.css ================================================ .dialog_signin { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .dialog_signin_container input[type="password"], .dialog_signin_container input[type="text"] { width: 355px; height: 25px; } .dialog_signin_container h3, .dialog_signin_container h4 { cursor: default; } .dialog_signin_container .alert{ position: absolute; z-index: 9999999; width: 318px; display: none; margin-top: -5px; } .dialog_signin_container .modal-social { background: white; } .dialog_signin_container .modal-forget-password { float: right; padding: 5px 2px 3px 0; } .dialog_signin_container .modal-link-to-registration { } .modal-link-to-registration a { color: white; display: block; text-align: center; } .social_button_icon { float: left; width: 30px; text-align: center; font-weight: bold; display: block; border-right: 1px solid #ccc; height: 24px; margin-top: -3px; padding-top: 3px; overflow: hidden; } ================================================ FILE: public/css/parts/head.css ================================================ .navbar-inverse { border-radius: 0; background: white; border-bottom: 1px solid #DDDDDD; min-height: 45px; overflow: hidden; padding-top: 0px; margin-bottom: 0; } .btn-logo { border-radius: 0; } .navbar-inverse *:focus { outline: 0; } @media (max-width: 767px) { .navbar-inverse { background: rgba(255,255,255,.9); } .navbar-toggle { margin-top: 7px; border-color: #31B0D5; margin-bottom: 0; } } .navbar-inverse .navbar-toggle .icon-bar { background-color: #31B0D5; } .navbar-inverse .navbar-toggle:focus, .navbar-inverse .navbar-toggle:hover { background-color: #EEEEEE; } .navbar-inverse .navbar-nav > li > a, .navbar-inverse .navbar-nav > .open ul > a { color: rgba(0, 0, 0, .7); padding-bottom: 0; padding-top: 0; line-height: 45px; } .navbar-inverse .navbar-nav > .active > a, .navbar-inverse .navbar-nav > .active > a:hover, .navbar-inverse .navbar-nav > .active > a:focus { color: rgba(0, 0, 0, 1); background: none; padding-bottom: 0; } .navbar-inverse .navbar-nav > .open > a { background: none; color: rgba(0, 0, 0, 1); } .navbar-inverse .navbar-nav>li>a:hover, .navbar-inverse .navbar-nav>li>a:focus, .navbar-inverse .navbar-nav>.open>a:hover, .navbar-inverse .navbar-nav>.open>a:focus { background: none; color: rgba(0, 0, 0, 1); } .navbar-inverse .navbar-nav > .active > a { background: none; color: rgba(0, 0, 0, 1); } .navbar-inverse .navbar-brand img { margin-top: -20px; height: 60px; } .navbar-nav .dropdown-menu { left: -5px; font-size: 13px; background-color: rgba(0, 0, 0, .7); border: 0px none; -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); } .navbar-nav .dropdown-menu > li > a { color: rgba(0, 0, 0, .7); padding: 7px 20px; } .navbar-nav .dropdown-menu > li > a:hover, .navbar-nav .dropdown-menu > li > a:focus, .navbar-nav .dropdown-menu > .active > a:hover { background: rgba(0, 0, 0, .1); color: white; } .navbar-nav .dropdown-menu > .active > a, .navbar-nav .dropdown-menu > .active > a:focus { background: none; color: #fff; } .navbar-nav .btn { border: 0; margin: 10px 0 0 10px; border-radius: 5px; padding: 5px; box-shadow: none; } .navbar-nav a.btn:focus, .navbar-nav a.btn:hover { border: 0; box-shadow: none; } .navbar-collapse { border: 0 none; border-top: 0 none; box-shadow: none; } @media (max-width: 767px) { .navbar-collapse ul { text-align: center; width: 100%; padding-bottom: 10px; } .navbar-collapse ul .btn{ max-width: 50%; margin:0 auto; } } .navbar-static-top, .navbar-fixed-top, .navbar-fixed-bottom { border-radius: 0; } .slideUp { top: -45px; } .headroom { -webkit-transition: all 0.4s ease-out; -moz-transition: all 0.4s ease-out; -o-transition: all 0.4s ease-out; transition: all 0.4s ease-out; } #container { padding-top: 55px; } .navbar-nav a.icon_holder { padding-top: 11px !important; line-height: 20px !important; font-size: 20px; } ================================================ FILE: public/css/parts/home.css ================================================ .home_features { } .home_features img { margin-top: 10px; margin-right: 5px; } .home_features .media-heading { margin-top: 30px; } .img-thumbnail { margin-bottom: 10px; } .home_screenshots { } .home_screenshots .image-link { display: block; height: 161px; background-size: cover; border: 1px solid #31B0D5; background-position: left top; margin-bottom: 15px; background-repeat: no-repeat; } .home_screenshots .image-link-contain { background-size: contain; background-position: center center; } .home_screenshots .image-link:hover { border: 1px solid #337AB7; } ================================================ FILE: public/css/parts/icons.css ================================================ .btn-social{position:relative;padding-left:44px;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .btn-social>:first-child{position:absolute;left:0;top:0;bottom:0;width:32px;line-height:34px;font-size:1.6em;text-align:center;border-right:1px solid rgba(0,0,0,0.2)} .btn-facebook{color:#fff;background-color:#3b5998;border-color:rgba(0,0,0,0.2)}.btn-facebook:focus,.btn-facebook.focus{color:#fff;background-color:#2d4373;border-color:rgba(0,0,0,0.2)} .btn-facebook:hover{color:#fff;background-color:#2d4373;border-color:rgba(0,0,0,0.2)} .btn-facebook:active,.btn-facebook.active,.open>.dropdown-toggle.btn-facebook{color:#fff;background-color:#2d4373;border-color:rgba(0,0,0,0.2)}.btn-facebook:active:hover,.btn-facebook.active:hover,.open>.dropdown-toggle.btn-facebook:hover,.btn-facebook:active:focus,.btn-facebook.active:focus,.open>.dropdown-toggle.btn-facebook:focus,.btn-facebook:active.focus,.btn-facebook.active.focus,.open>.dropdown-toggle.btn-facebook.focus{color:#fff;background-color:#23345a;border-color:rgba(0,0,0,0.2)} .btn-facebook:active,.btn-facebook.active,.open>.dropdown-toggle.btn-facebook{background-image:none} .btn-facebook.disabled,.btn-facebook[disabled],fieldset[disabled] .btn-facebook,.btn-facebook.disabled:hover,.btn-facebook[disabled]:hover,fieldset[disabled] .btn-facebook:hover,.btn-facebook.disabled:focus,.btn-facebook[disabled]:focus,fieldset[disabled] .btn-facebook:focus,.btn-facebook.disabled.focus,.btn-facebook[disabled].focus,fieldset[disabled] .btn-facebook.focus,.btn-facebook.disabled:active,.btn-facebook[disabled]:active,fieldset[disabled] .btn-facebook:active,.btn-facebook.disabled.active,.btn-facebook[disabled].active,fieldset[disabled] .btn-facebook.active{background-color:#3b5998;border-color:rgba(0,0,0,0.2)} .btn-facebook .badge{color:#3b5998;background-color:#fff} .btn-google{color:#fff;background-color:#dd4b39;border-color:rgba(0,0,0,0.2)}.btn-google:focus,.btn-google.focus{color:#fff;background-color:#c23321;border-color:rgba(0,0,0,0.2)} .btn-google:hover{color:#fff;background-color:#c23321;border-color:rgba(0,0,0,0.2)} .btn-google:active,.btn-google.active,.open>.dropdown-toggle.btn-google{color:#fff;background-color:#c23321;border-color:rgba(0,0,0,0.2)}.btn-google:active:hover,.btn-google.active:hover,.open>.dropdown-toggle.btn-google:hover,.btn-google:active:focus,.btn-google.active:focus,.open>.dropdown-toggle.btn-google:focus,.btn-google:active.focus,.btn-google.active.focus,.open>.dropdown-toggle.btn-google.focus{color:#fff;background-color:#a32b1c;border-color:rgba(0,0,0,0.2)} .btn-google:active,.btn-google.active,.open>.dropdown-toggle.btn-google{background-image:none} .btn-google.disabled,.btn-google[disabled],fieldset[disabled] .btn-google,.btn-google.disabled:hover,.btn-google[disabled]:hover,fieldset[disabled] .btn-google:hover,.btn-google.disabled:focus,.btn-google[disabled]:focus,fieldset[disabled] .btn-google:focus,.btn-google.disabled.focus,.btn-google[disabled].focus,fieldset[disabled] .btn-google.focus,.btn-google.disabled:active,.btn-google[disabled]:active,fieldset[disabled] .btn-google:active,.btn-google.disabled.active,.btn-google[disabled].active,fieldset[disabled] .btn-google.active{background-color:#dd4b39;border-color:rgba(0,0,0,0.2)} .btn-google .badge{color:#dd4b39;background-color:#fff} .btn-twitter{color:#fff;background-color:#55acee;border-color:rgba(0,0,0,0.2)}.btn-twitter:focus,.btn-twitter.focus{color:#fff;background-color:#2795e9;border-color:rgba(0,0,0,0.2)} .btn-twitter:hover{color:#fff;background-color:#2795e9;border-color:rgba(0,0,0,0.2)} .btn-twitter:active,.btn-twitter.active,.open>.dropdown-toggle.btn-twitter{color:#fff;background-color:#2795e9;border-color:rgba(0,0,0,0.2)}.btn-twitter:active:hover,.btn-twitter.active:hover,.open>.dropdown-toggle.btn-twitter:hover,.btn-twitter:active:focus,.btn-twitter.active:focus,.open>.dropdown-toggle.btn-twitter:focus,.btn-twitter:active.focus,.btn-twitter.active.focus,.open>.dropdown-toggle.btn-twitter.focus{color:#fff;background-color:#1583d7;border-color:rgba(0,0,0,0.2)} .btn-twitter:active,.btn-twitter.active,.open>.dropdown-toggle.btn-twitter{background-image:none} .btn-twitter.disabled,.btn-twitter[disabled],fieldset[disabled] .btn-twitter,.btn-twitter.disabled:hover,.btn-twitter[disabled]:hover,fieldset[disabled] .btn-twitter:hover,.btn-twitter.disabled:focus,.btn-twitter[disabled]:focus,fieldset[disabled] .btn-twitter:focus,.btn-twitter.disabled.focus,.btn-twitter[disabled].focus,fieldset[disabled] .btn-twitter.focus,.btn-twitter.disabled:active,.btn-twitter[disabled]:active,fieldset[disabled] .btn-twitter:active,.btn-twitter.disabled.active,.btn-twitter[disabled].active,fieldset[disabled] .btn-twitter.active{background-color:#55acee;border-color:rgba(0,0,0,0.2)} .btn-twitter .badge{color:#55acee;background-color:#fff} .btn-social-icon>:first-child{border:none;text-align:center;width:100% !important} ================================================ FILE: public/css/parts/import.css ================================================ .sample_cell { max-height: 40px; max-width: 190px; word-wrap: break-word; overflow: hidden; } .import_row_type { width: 130px; } .import_row_date_format { width: 130px; } .import_row_time_format { width: 130px; } ================================================ FILE: public/css/parts/overload.css ================================================ #wrap { background-color: #F8F8F8; } .row.no-gutter { margin-left: 0; margin-right: 0; } .row.no-gutter [class*='col-']:not(:first-child), .row.no-gutter [class*='col-']:not(:last-child) { padding-right: 0; padding-left: 0; } .hideme { display: none; } .disable-selection { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .disable-selection a:hover { outline: 0; } .navbar-default { -webkit-box-shadow: none; box-shadow: none; background-image: none; } .btn-danger, .btn-default, .btn-info, .btn-primary, .btn-success, .btn-warning { text-shadow: none; } .modal-footer { border-top: 0; } @media (max-width: 480px) { body { font-size: 11px; } h4 { font-size: 12px; } } ================================================ FILE: public/css/parts/page_transitions.css ================================================ .page_holder { } .page { } .page_loading { background: url('/images/loading.gif') center center no-repeat; min-height: 200px; } #preloader { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: white url('/images/loading.gif') center center no-repeat; z-index: 999; } ================================================ FILE: public/css/parts/sticked_footer.css ================================================ html, body { height: 100%; /* The html and body elements cannot have any padding or margin. */ margin: 0; padding: 0; } /* Wrapper for page content to push down footer */ #wrap { min-height: 100%; height: auto !important; height: 100%; /* Negative indent footer by it's height */ margin: 0 auto -50px; } /* Set the fixed height of the footer here */ #push, #footer { height: 50px; } #footer { background-color: #DDD; border-top: 1px solid #AAA; } #footer .credit a { } #footer .credit a:hover { } #footer .container, #footer .container-fluid { padding-top: 14px; } ================================================ FILE: public/css/parts/text_format.css ================================================ .text_format { } .text_format img { max-width: 100%; } .text_format img[style*="float: left"] { margin: 0 10px 5px 0; } .text_format img { } .text_format hr { margin-top: 10px; margin-bottom: 10px; border-top: 1px solid #666; } .text_format table { margin-bottom: 10px; } .text_format blockquote p { font-size: 14px; } ================================================ FILE: public/css/parts/wallets.css ================================================ .wallet_total { font-size: 24px; } a.action { border-bottom: 1px dashed #2a6496; text-decoration: none; } a.action:hover { border-bottom: 1px dashed #2a6496; text-decoration: none; } .transaction_amount { text-align: right; } .transaction_description { margin-left: 170px; } .transaction_time { font-size: 12px; width: 170px; overflow: hidden; } .transaction_time_date { float: left; width: 100px; overflow: hidden; font-weight: bold; margin-bottom: 5px; line-height: 1.1; } .transaction_time_time { float: left; width: 70px; overflow: hidden; font-weight: bold; margin-bottom: 5px; line-height: 1.1; } #add_transaction_amount { margin-top: 3px; } .wallet_item { } .wallet_item .wallet_buttons { float: right; margin-right: 10px; } @media (max-width: 480px) { .transaction_time { font-size: 11px; } .transaction_description { clear: both; margin-left: 100px; margin-bottom: 0; } } ================================================ FILE: public/css/parts/widgets.css ================================================ .widget h1:first-child { margin-top: 0; } .widget h2:first-child { margin-top: 0; } .widget h3:first-child { margin-top: 0; } .widget h4:first-child { margin-top: 0; } .widget h5:first-child { margin-top: 0; } ================================================ FILE: public/index.html ================================================ DimeShift
================================================ FILE: public/jstemplates/404.tpl ================================================

{t}Nothing is found{/t}

================================================ FILE: public/jstemplates/dialogs/add_profit.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/add_wallet.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/change_language.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/edit_wallet.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/fill_profile.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/hide_wallet.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/registration.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/remove_access.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/remove_plan.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/remove_transaction.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/restore.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/set_total_to.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/signin.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/transaction_details.tpl ================================================ ================================================ FILE: public/jstemplates/dialogs/wallet_accesses.tpl ================================================ ================================================ FILE: public/jstemplates/months.tpl ================================================ {t}January{/t} {t}February{/t} {t}March{/t} {t}April{/t} {t}May{/t} {t}June{/t} {t}July{/t} {t}August{/t} {t}September{/t} {t}October{/t} {t}November{/t} {t}December{/t} for dmy: {t}january{/t} {t}february{/t} {t}march{/t} {t}april{/t} {t}may{/t} {t}june{/t} {t}july{/t} {t}august{/t} {t}september{/t} {t}october{/t} {t}november{/t} {t}december{/t} ================================================ FILE: public/jstemplates/pages/import/xls.tpl ================================================
{if $step == 1 && !$sample}
{tp}Step 1. Select .xls file to import{/tp}

{tp}Please select your local .xls file{/tp}

{tp}Cancel{/tp}
{/if} {if $step == 1 && $sample}
{tp}Step 2. Select columns to import{/tp}
{if $sample} {for $var=1 to $sampleWidth} {/for} {foreach from=$sample item=row key=i} {if $row.items|count} {foreach from=$row.items item=c} {/foreach} {else} {/if} {/foreach}
{$c}
... {$row.skiped} {tp}more rows{/tp}
{/if}

{tp}Amount and Date fields are required{/tp}

{/if} {if $step == 2}
{tp}Step 3. Preview and settings{/tp}
{if $importPreview} {foreach from=$importPreview item=i} {/foreach}
{tp}Date{/tp} {tp}Time{/tp} {tp}Description{/tp} {tp}Amount{/tp}
{$i.date|wallet_date} {$i.date|wallet_time} {if $i.description}{$i.description|escape}{else} {/if} {$i.amount|escape}
{tp}Few more rows{/tp}
{/if}
{/if} {if $step == 3}
{tp}Step 4. Import{/tp}
 
{/if} {if $step == 4}
{tp}Finished{/tp}

{tp}Import operation is finished{/tp}. {tp}Check out you updated wallet{/tp}

{/if}
================================================ FILE: public/jstemplates/pages/index/index.tpl ================================================

DimeShift – {tp}the easiest way to track your expenses{/tp}

{tp}To demonstrate how simple it is{/tp} – {tp}we don't even ask you to register{/tp}.

{tp}Screenshots{/tp}

================================================ FILE: public/jstemplates/pages/plans/index.tpl ================================================

{tp}Your plans{/tp}

    {if $plans|count == 0} {else} {foreach from=$plans item=p}
  • {$p->name|escape:'html'} 
  • {/foreach} {/if}

{tp}Basic settings{/tp}

{tp}Plan name{/tp}

name|default:'Undefined' != 'Undefined'}value="{$preparedData->name|escape:'html'}"{/if} placeholder="{t}Plan name{/t}">

{tp}Wallets to use for planning{/tp}

{if $wallets|count == 0} {else}
{foreach from=$wallets item=w} {assign var="checked" value=0} {if $preparedData->wallets|default:''} {foreach from=$preparedData->wallets item=pwid} {if $pwid == $w->id} {assign var="checked" value=1} {/if} {/foreach} {/if} {$w->name|escape:'html'}  {/foreach}
{/if}

{tp}Plan settings{/tp}

{tp}Current balance is{/tp}

-$0.00 USD

or

-$0.00 USD

{tp}And on{/tp}

{tp}Plan is to keep{/tp}

{tp}So you{/tp} {tp}can spend up to{/tp} {tp}have to get{/tp} $100.00 USD {tp}on the next day{/tp} {tp}in next{/tp} 32 {tp}days{/tp}. $100.00 USD {tp}per day{/tp}.

================================================ FILE: public/jstemplates/pages/plans/view.tpl ================================================

{tp}Goal Details{/tp}

{tp}From:{/tp} {if $plan->start_balance < 0}-{/if}{if $plan->start_currency == 'USD'}${/if}{$plan->start_balance|rational}.{$plan->start_balance|decimal}{if $plan->start_currency != 'USD'} {$plan->start_currency}{/if}

{tp}To:{/tp} {if $plan->goal_balance < 0}-{/if}{if $plan->goal_currency == 'USD'}${/if}{$plan->goal_balance|rational}.{$plan->goal_balance|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if}

{if $stats|count > 1}{$stats|count} {tp}days{/tp}.{/if} {tp}From{/tp} {$plan->start_datetime|wallet_date} {tp}to{/tp} {$plan->goal_datetime|wallet_date}

{if $adviceData.hasToday} {if $adviceData.todaysPlan < 0} Your goal for today is to spend at most {if $plan->goal_currency == 'USD'}${/if}{$adviceData.todaysPlan|rational}.{$adviceData.todaysPlan|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} {else} Your goal for today is to earn at least {if $plan->goal_currency == 'USD'}${/if}{$adviceData.todaysPlan|rational}.{$adviceData.todaysPlan|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} {/if} {if $adviceData.todaysAlreadyTotal != 0} {if $adviceData.todaysAlreadyTotal < 0} At this point, you've spent {if $plan->goal_currency == 'USD'}${/if}{$adviceData.todaysAlreadyTotal|rational}.{$adviceData.todaysAlreadyTotal|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} today already. {else} At this point, you've already earned {if $plan->goal_currency == 'USD'}${/if}{$adviceData.todaysAlreadyTotal|rational}.{$adviceData.todaysAlreadyTotal|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} today. {/if} {else} {if $adviceData.todaysPlan < 0} You have no spendings for today. {else} You've earned nothing today. {/if} {/if} {if $adviceData.hasTomorrow} {if $adviceData.tomorrowPlan < 0} Which means you can spend up to {if $plan->goal_currency == 'USD'}${/if}{$adviceData.tomorrowPlan|rational}.{$adviceData.tomorrowPlan|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} tomorrow. {else} Which means you have to earn at least {if $plan->goal_currency == 'USD'}${/if}{$adviceData.tomorrowPlan|rational}.{$adviceData.tomorrowPlan|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} tomorrow. {/if} {else} {if $adviceData.todaysDif < 0} Today is the last day of your plan, be sure to spend no more than {if $plan->goal_currency == 'USD'}${/if}{$adviceData.todaysDif|rational}.{$adviceData.todaysDif|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} more to achieve success with this goal. {else} Today is the last day of your plan, be sure to earn {if $plan->goal_currency == 'USD'}${/if}{$adviceData.todaysDif|rational}.{$adviceData.todaysDif|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} more to achieve success with this goal. {/if} {/if} {if $adviceData.hasFuture} {if $adviceData.futureMaxPlan < 0} Spend less than DimeShift suggests you each day and you will have more money available for spending each day. Up to {if $plan->goal_currency == 'USD'}${/if}{$adviceData.futureMaxPlan|rational}.{$adviceData.futureMaxPlan|decimal}{if $plan->goal_currency != 'USD'} {$plan->goal_currency}{/if} on {$adviceData.futureEndDate|wallet_date}! {else} Of course, feel free to earn more than DimeShift suggests you each day. {/if} {/if} {/if}

{tp}Day by day report{/tp}

{if $stats|count == 0} {else} {assign var="possibleLowestSpending" value=null} {foreach from=$stats item=s} {if $s->date->unix_from > $currentTimestamp} {else} {/if} {/foreach} {/if}
{tp}Date{/tp} {tp}Total On Start{/tp} {tp}Spent{/tp} {tp}Profit{/tp} {tp}Plan{/tp}
{$s->date->unix|wallet_date} {if $s->date->unix_from < $currentTimestamp && $s->date->unix_to > $currentTimestamp} currentTotalOnStart >= 0}style="visibility: hidden;" class="hidden-xs hidden-sm"{/if}>-{$s->currentTotalOnStart|rational}.{$s->currentTotalOnStart|decimal} {else} currentTotalOnStart >= 0}style="visibility: hidden;"{/if}>-{$s->currentTotalOnStart|rational}.{$s->currentTotalOnStart|decimal} {/if}  {$s->expensesTotal|rational}.{$s->expensesTotal|decimal} {$s->profitsTotal|rational}.{$s->profitsTotal|decimal} {if $s->date->unix_from > $currentTimestamp && $possibleLowestSpending !== null} {$possibleLowestSpending|rational}.{$possibleLowestSpending|decimal} – {/if} {$s->allowedToSpend|rational}.{$s->allowedToSpend|decimal} {if $s->date->unix_from > $currentTimestamp && $possibleLowestSpending == null} {assign var="possibleLowestSpending" value=$s->allowedToSpend} {/if}
================================================ FILE: public/jstemplates/pages/profile/index.tpl ================================================
================================================ FILE: public/jstemplates/pages/user/confirm.tpl ================================================

Confirm your email address

{if $confirmed}
Your email has been confirmed. You can now.
{else}
Invalid confirmation code.
{/if} ================================================ FILE: public/jstemplates/pages/user/index.tpl ================================================

Dashboard

================================================ FILE: public/jstemplates/pages/user/registration.tpl ================================================ ================================================ FILE: public/jstemplates/pages/user/restore.tpl ================================================ ================================================ FILE: public/jstemplates/pages/user/signin.tpl ================================================ ================================================ FILE: public/jstemplates/pages/user/update_password.tpl ================================================
================================================ FILE: public/jstemplates/pages/wallets/index.tpl ================================================ ================================================ FILE: public/jstemplates/pages/wallets/view.tpl ================================================

{$item->name|escape:'html'}

{if $item->total < 0}-{/if}{if $item->currency == 'USD'}${/if}{$item->total|rational}.{$item->total|decimal}{if $item->currency != 'USD'} {$item->currency}{/if}

{tp}Transactions{/tp} {tp}Import{/tp}

{tp}Expenses per day trends{/tp}

================================================ FILE: public/jstemplates/parts/transactions.tpl ================================================ {if $state == 'loading'}
{else}
{if $collection|default:false && $collection.hasNextPeriod()} {if $collection.diffToCurrentPeriod() < 2}
{else}
{/if} {/if} {if $transactions|count > 0} {foreach from=$transactions item=t}
{assign var="current_transaction_time_date" value=$t->datetime|wallet_date}
{if $last_time_date|default:'' != $current_transaction_time_date}{$current_transaction_time_date}{else} {/if}
{$t->datetime|wallet_time}
{assign var="last_time_date" value=$current_transaction_time_date}
  {if $item->currency == 'USD'}${/if}{$t->amount|rational}.{$t->amount|decimal}{if $item->currency != 'USD'} {$item->currency}{/if}
{$t->description|escape:'html'|default:' '}
{/foreach} {else}
{tp}No transactions for{/tp} {$collection.periodToReadableFormat()}
{/if} {if $collection|default:false && $collection.hasPrevPeriod()}
{/if}
{/if} ================================================ FILE: public/jstemplates/parts/wallet_plans.tpl ================================================ ================================================ FILE: public/scripts/.gitignore ================================================ dist/* ================================================ FILE: public/scripts/app/abstract/dialog.js ================================================ // dialog.js App.Views.Abstract.Dialog = Backbone.View.extend({ el: $("#dialog_wrapper"), isVisible: false, focusOnInit: false, initialFocus: function() { if ('ontouchstart' in window || navigator.maxTouchPoints) return false; /// do not focus on touch devices if (!this.focusOnInit) return false; this.$(this.focusOnInit).focus(); return true; }, show: function(data) { if (!$("#dialog_wrapper").length) $('body').append("
"); this.setElement($("#dialog_wrapper")); if (typeof(data) === 'undefined') data = {}; this.renderLoading(); var that = this; var rendered = new $.Deferred(); var shown = new $.Deferred(); $.when(rendered, shown).done(function() { that.initialFocus(); that.trigger('ready'); }); this.$el.children().on('shown.bs.modal', function(e) { that.isVisible = true; console.log("Dialog " + that.dialogName + " is shown. Firing shown event."); that.trigger('shown'); shown.resolve(); }); this.$el.children().on('hidden.bs.modal', function(e) { that.isVisible = false; that.undelegateEvents(); $("#dialog_wrapper").html(''); console.log("Dialog " + that.dialogName + " is hidden. Firing hidden event."); that.trigger('hidden'); }); this.once('rendered', function() { rendered.resolve(); }); this.isVisible = true; this.$el.children().modal(); this.renderHTML(data); }, renderLoading: function() { console.log('Dialog ' + this.dialogName + ' rendered loading'); this.$el.html(''); }, renderHTML: function(data) { var that = this; App.templateManager.fetch('dialogs/' + this.dialogName, data, function(html) { console.log('Dialog ' + that.dialogName + ' rendering'); that.$(".modal").html(html); that.trigger('rendered'); console.log('Dialog ' + that.dialogName + ' rendered'); }); }, hide: function() { console.log("Hide dialog"); this.$el.children().modal('hide'); } }); ================================================ FILE: public/scripts/app/abstract/page.js ================================================ // page.js App.Views.Abstract.Page = Backbone.View.extend({ isReady: false, requiresSignedIn: false, widgets: [], parts: [], partsInitialized: false, requireSingedIn: function(callback) { this.requiresSignedIn = true; this.listenToOnce(App.currentUser, 'signedout', function() { console.log('abstract/page.js | Clearing stack and redirect user back to the root'); App.viewStack.clear(); App.router.redirect('/'); }); if (typeof(App.currentUser) !== 'undefined' && App.currentUser.isSignedIn()) { if (typeof(callback) === 'function') callback(App.currentUser); return App.currentUser; } else { this.listenToOnce(App.currentUser, 'signedin', function() { callback(App.currentUser); }); App.showDialog('Signin'); App.dialog.on('hidden', function() { if (!App.currentUser.isSignedIn()) { App.viewStack.clear(); App.router.navigate('/', { trigger: true }); } }); } }, setURL: function(url) { if (typeof(url) === 'undefined') { url = ''; if (typeof(this.url) === 'function') url = this.url(); else if (typeof(this.url) === 'string') url = this.url; } if (url) { App.router.setUrl(url); App.log.setURL(url); } else { App.log.setURL(''); } App.log.pageView(); }, setTitle: function(title) { if (typeof(title) === 'undefined') { title = ''; if (typeof(this.title) === 'function') title = this.title(); else if (typeof(this.title) === 'string') title = this.title; } if (typeof(App.settings.title) == 'function') title = App.settings.title(title); if (title) { console.log("Document title changed to '" + title + "'"); $(document).attr('title', title); App.log.setTitle(title); } }, wakeUp: function() { App.setProgress(false); this.holderReady = false; this.render(); }, sleep: function() { for (var k in this.parts) { this.parts[k].undelegateEvents(); this.parts[k].stopListening(); } this.undelegateEvents(); this.stopListening(); }, proccessWidgets: function() { this.widgets = []; var that = this; this.$('.client-side-widget').each(function() { var data = $(this).data(); if (typeof(data.widgetName) === 'undefined' || !data.widgetName) return false; if (typeof(App.Views.Widgets[data.widgetName]) === 'undefined') { console.error('Widget class for ' + data.widgetName + ' is not defined'); return false; } var widgetView = new App.Views.Widgets[data.widgetName]({ el: $(this) }); that.widgets.push(widgetView); }); }, renderHTML: function(data) { if (typeof(this.templateName) === 'undefined' || !this.templateName) throw 'templateName is undefined'; if (typeof(data) === 'undefined') data = {}; this.switchBuffers(); var that = this; App.templateManager.fetch(this.templateName, data, function(html) { that.$el.html('
' + html + '
'); $('.page', "#page_holder_" + App.currentHolder).removeClass('page_loading'); that.proccessWidgets(); that.trigger('render'); that.trigger('loaded'); App.setProgress(true); }); this.setTitle(); this.setURL(); this.isReady = true; return this; }, switchBuffers: function() { if (typeof(this.holderReady) !== 'undefined' && this.holderReady === true) return true; console.log('Switching buffers'); var holderToRenderTo = 2; if (typeof(App.currentHolder) !== 'undefined' && App.currentHolder == 2) holderToRenderTo = 1; var holderToFadeOut = (holderToRenderTo == 1) ? 2 : 1; $("#page_holder_" + holderToFadeOut).hide(); $("#page_holder_" + holderToFadeOut).html(''); $("#page_holder_" + holderToRenderTo).show(); this.setElement($("#page_holder_" + holderToRenderTo)); App.currentHolder = holderToRenderTo; this.holderReady = true; }, renderLoading: function() { /// ask templateManager to prepare template App.setProgress(false); App.templateManager.fetch(this.templateName, {}); this.switchBuffers(); this.$el.html('
'); this.setTitle(); this.setURL(); console.log('Displaying loading'); this.trigger('loading'); } }); ================================================ FILE: public/scripts/app/collections/plans.js ================================================ //plans.js App.Collections.Plans = Backbone.Collection.extend({ model: App.Models.Plan, user_id: false, wallet_id: false, url: function() { if (this.wallet_id) return App.settings.apiEntryPoint + 'wallets/' + this.wallet_id + '/plans'; else return App.settings.apiEntryPoint + 'plans'; }, setUserId: function(user_id) { this.user_id = user_id; }, setWalletId: function(wallet_id) { this.wallet_id = wallet_id; }, }); ================================================ FILE: public/scripts/app/collections/transactions.js ================================================ //transactions.js App.Collections.Transactions = Backbone.Collection.extend({ model: App.Models.Transaction, wallet_id: false, state: 'loading', periodMonth: false, periodYear: false, comparator: function(item) { return -item.get('datetime'); // Note the minus! }, url: function() { if (this.wallet_id) return App.settings.apiEntryPoint + 'wallets/' + this.wallet_id + '/transactions/' + this.periodToGETParams(); else return App.settings.apiEntryPoint + 'transactions/' + this.periodToGETParams(); }, periodToReadableFormat: function(month, year) { var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; if (typeof(month) == 'undefined' || typeof(year) == 'undefined') { if (!this.periodMonth || !this.periodYear) this.setPeriod(); return App.i18n.translate(monthNames[this.periodMonth - 1]) + ' ' + this.periodYear; } else { return App.i18n.translate(monthNames[month - 1]) + ' ' + year; } }, nextPeriodToReadableFormat: function() { if (!this.periodMonth || !this.periodYear) this.setPeriod(); var month = this.periodMonth + 1; var year = this.periodYear; if (month == 13) { year++; month = 1; } return this.periodToReadableFormat(month, year); }, prevPeriodToReadableFormat: function() { if (!this.periodMonth || !this.periodYear) this.setPeriod(); var month = this.periodMonth - 1; var year = this.periodYear; if (month === 0) { year--; month = 12; } return this.periodToReadableFormat(month, year); }, currentPeriodToReadableFormat: function() { var d = new Date(); return this.periodToReadableFormat(d.getMonth() + 1, d.getFullYear()); }, diffToCurrentPeriod: function() { if (!this.periodMonth || !this.periodYear) this.setPeriod(); var d = new Date(); var curMonth = d.getMonth() + 1; var curYear = d.getFullYear(); return (curMonth - this.periodMonth) + (curYear - this.periodYear) * 12; }, periodToGETParams: function() { if (!this.periodMonth || !this.periodYear) this.setPeriod(); var to = 0; if (this.periodMonth < 12) /// don't forget that the month is 0 based for new Date, but 1 based in periodMonth to = (new Date(this.periodYear, this.periodMonth, 1, 0, 0, 0, 0)).getTime() / 1000 - 1; else to = (new Date(this.periodYear + 1, 0, 1, 0, 0, 0, 0)).getTime() / 1000 - 1; var from = (new Date(this.periodYear, this.periodMonth - 1, 1, 0, 0, 0, 0)).getTime() / 1000; return '?to=' + to + '&from=' + from; }, setWalletId: function(wallet_id) { this.wallet_id = wallet_id; }, hasNextPeriod: function() { if (this.periodMonth === false || this.periodYear === false) return false; var d = new Date(); /// don't forget that the month is 0 based for new Date, but 1 based in periodMonth if (this.periodYear < d.getFullYear() || (this.periodYear == d.getFullYear() && this.periodMonth < d.getMonth() + 1)) return true; return false; }, hasPrevPeriod: function() { if (this.periodMonth === false || this.periodYear === false) return true; var d = new Date(); if (this.periodYear <= 1970) return false; return true; }, nextPeriod: function() { if (!this.periodMonth || !this.periodYear) this.setPeriod(); if (!this.hasNextPeriod()) return false; this.periodMonth++; if (this.periodMonth > 12) { this.periodMonth = 1; this.periodYear++; } return true; }, currentPeriod: function() { if (!this.periodMonth || !this.periodYear) { this.setPeriod(); return true; } if (!this.hasNextPeriod()) return false; var d = new Date(); var curMonth = d.getMonth() + 1; var curYear = d.getFullYear(); this.periodMonth = curMonth; this.periodYear = curYear; return true; }, prevPeriod: function() { if (!this.periodMonth || !this.periodYear) this.setPeriod(); if (!this.hasPrevPeriod()) return false; this.periodMonth--; if (this.periodMonth < 1) { this.periodMonth = 12; this.periodYear--; } return true; }, setPeriod: function(month, year) { var d = new Date(); if (typeof(month) == 'undefined') { this.periodMonth = d.getMonth() + 1; } else { if (month >= 1 && month <= 12) this.periodMonth = month; else console.error('Invalid month parameter'); } if (typeof(year) == 'undefined') { this.periodYear = d.getFullYear(); } else { if (year >= 1970) this.periodYear = year; else console.error('Invalid year parameter'); } }, gotoNext: function() { if (this.nextPeriod()) { this.fetch(); this.trigger('changedperiod'); return true; } return false; }, gotoPrev: function() { if (this.prevPeriod()) { this.fetch(); this.trigger('changedperiod'); return true; } return false; }, gotoCurrent: function() { if (this.currentPeriod()) { this.fetch(); this.trigger('changedperiod'); return true; } return false; }, initialize: function() { this.state = 'loading'; this.on('request', function() { this.state = 'loading'; }, this); this.on('sync', function() { this.state = 'ready'; }, this); } }); ================================================ FILE: public/scripts/app/collections/users.js ================================================ //users.js App.Collections.Users = Backbone.Collection.extend({ model: App.Models.User, url: function() { return App.settings.apiEntryPoint + 'users'; }, }); ================================================ FILE: public/scripts/app/collections/wallets.js ================================================ //wallets.js App.Collections.Wallets = Backbone.Collection.extend({ model: App.Models.Wallet, user_id: false, url: function() { if (this.user_id) return App.settings.apiEntryPoint + 'users/' + this.user_id + '/wallets'; else return App.settings.apiEntryPoint + 'wallets'; }, search: function(opts) { var result = this.where(opts); var resultCollection = new App.Collections.Wallets(result); return resultCollection; }, setUserId: function(user_id) { this.user_id = user_id; }, }); ================================================ FILE: public/scripts/app/collections/wallets_accesses.js ================================================ //wallets_accesses.js App.Collections.WalletsAccesses = Backbone.Collection.extend({ model: App.Models.WalletsAccess, wallet_id: false, url: function() { if (this.wallet_id) return App.settings.apiEntryPoint + 'wallets/' + this.wallet_id + '/accesses'; else return App.settings.apiEntryPoint + 'wallets_accesses'; }, setWalletId: function(wallet_id) { this.wallet_id = wallet_id; } }); ================================================ FILE: public/scripts/app/exchange.js ================================================ // exchange.js App.exchange = { rates: {}, base: 'USD', loaded: false, loadRates: function(callback) { // @todo: reload exchange rates once per hour if (this.loaded) { if (typeof(callback) == 'function') callback(); return; } var that = this; var process = function(data) { if (typeof(data.rates) === 'undefined' || typeof(data.base) === 'undefined') { console.error('Invalid api/exchange/rates rasponse. Maybe you need to check openexchangerates api_key in server settings'); return; } that.rates = data.rates; that.base = data.base; that.loaded = true; if (typeof(callback) == 'function') callback(); }; $.ajax({ url: App.settings.apiEntryPoint + 'exchange/rates', data: {}, success: process, dataType: 'json', mimeType: 'application/json', cache: false }); }, convert: function(value, from, to) { return value * this.getRate(to, from); }, getRate: function(to, from) { this.rates[this.base] = 1; if (!this.rates[to] || !this.rates[from]) { console.error('No exchange rates FROM:' + from + ' TO:' + to + '. Converting by 1:1'); return 1; } if (from === this.base) { return this.rates[to]; } if (to === this.base) { return 1 / this.rates[from]; } return this.rates[to] * (1 / this.rates[from]); } }; ================================================ FILE: public/scripts/app/helper.js ================================================ // helper.js App.helper = { loadedAdditionalScripts: {}, loadAdditionalScripts: function(scripts, callback) { var that = this; var expectedScripts = {}; var addLoadHandler = function(scriptObj, scriptURL) { scriptObj.onload = function() { that.loadAdditionalScripts[scriptURL] = true; expectedScripts[scriptURL] = false; for (var k in expectedScripts) if (expectedScripts[k]) { loadScript(k); return; } if (typeof(callback) === 'function') callback(); }; }; var loadScript = function(src) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = src; addLoadHandler(script, src); head.appendChild(script); }; for (var k in scripts) expectedScripts[scripts[k]] = true; if (scripts.length > 0) loadScript(scripts[0]); } }; ================================================ FILE: public/scripts/app/i18n.js ================================================ // i18n.js App.i18n = { strings: {}, loaded: false, setLanguage: function(languageCode, callback) { this.languageCode = languageCode; App.localStorage.set('selected_interface_locale', languageCode); this.loadStrings(callback); }, getLanguage: function(languageCode) { return this.languageCode; }, translate: function(string, stringId) { if (typeof(stringId) == 'undefined') stringId = string; if (typeof(this.strings[stringId]) === 'undefined' || this.strings[stringId] === false || this.strings[stringId] === '') return string; else return this.strings[stringId]; }, translateDOM: function() { var that = this; $("[data-i18n]").each(function() { var string = $(this).data('i18n'); string = that.translate(string); $(this).text(string); }); $("[data-i18nvalue]").each(function() { var string = $(this).data('i18nvalue'); string = that.translate(string); $(this).val(string); }); $("[data-i18nplaceholder]").each(function() { var string = $(this).data('i18nplaceholder'); string = that.translate(string); $(this).attr('placeholder', string); }); }, loadStrings: function(callback) { var that = this; var process = function(data) { that.strings = data; that.loaded = true; that.translateDOM(); if (typeof(callback) == 'function') callback(); }; this.loaded = false; if (this.languageCode == 'default') process({}); else $.ajax({ url: App.settings.apiEntryPoint + 'i18n/bycode/' + this.languageCode.split('-').join(''), data: {}, success: process, dataType: 'json', mimeType: 'application/json', cache: true }); } }; ================================================ FILE: public/scripts/app/local_storage.js ================================================ // local_storage.js App.localStorage = { invalidate: function(currentVersion) { var prev = this.get('current_app_version'); if (prev && currentVersion != prev) this.clear(); this.set('current_app_version', currentVersion); }, set: function(name, data) { if (typeof(data) === 'undefined') return this.remove(name); window.localStorage.setItem(name, this._serialize(data)); return data; }, get: function(name) { return this._deserialize(window.localStorage.getItem(name)); }, remove: function(name) { window.localStorage.removeItem(name); return true; }, clear: function() { window.localStorage.clear(); return true; }, isSupported: function() { if (typeof(window) === 'undefined') return false; try { return ('localStorage' in window && window.localStorage); } catch (err) { return false; } return true; }, _serialize: function(data) { return JSON.stringify(data); }, _deserialize: function(data) { if (typeof data != 'string') return undefined; try { return JSON.parse(data); } catch (e) { return data || undefined; } } }; ================================================ FILE: public/scripts/app/log.js ================================================ // log.js App.log = { currentURL: null, currentTitle: null, currentVisitTime: null, hasToForce: false, setURL: function(url) { if (url != this.currentURL) { this.setUserId(); this.hasToForce = true; this.currentURL = url; if (typeof(ga) === 'function') { ga('set', 'page', '/' + url); } } }, setTitle: function(title) { if (title != this.currentTitle) { this.setUserId(); this.currentTitle = title; this.hasToForce = true; if (typeof(ga) === 'function') { ga('set', 'title', title); } } }, setUserId: function() { if (App && App.currentUser && App.currentUser.id && typeof(ga) === 'function') ga('set', '&uid', '' + App.currentUser.id); }, pageView: function() { var time = Date.now(); if (this.currentVisitTime === null || (time - this.currentVisitTime) > 1000 || this.hasToForce) /// 100 microseconds { this.setUserId(); if (typeof(ga) === 'function') { ga('send', 'pageview'); } this.hasToForce = false; } this.currentVisitTime = time; }, event: function(category, action, label, count) { this.setUserId(); if (typeof(label) === 'undefined') label = ''; if (typeof(ga) === 'function') { if (typeof(count) !== 'undefined') ga('send', 'event', category, action, label, count); else ga('send', 'event', category, action, label); } } }; ================================================ FILE: public/scripts/app/models/plan.js ================================================ // plan.js App.Models.Plan = Backbone.Model.extend({ defaults: { name: null, }, loadedWallets: [], transactions: {}, stats: [], walletsCurrencies: {}, areStatsReady: false, url: function() { return App.settings.apiEntryPoint + 'plans/' + (typeof(this.id) === 'undefined' ? '' : this.id); }, getPlanForToday: function() { var today = new Date(); return this.getPlanForTheDay(today.getDate(), today.getMonth() + 1, today.getFullYear()); }, getPlanForTheDay: function(day, month, year) { if (!this.areStatsReady) throw 'call getPlanForTheDay only when stats are ready'; // @todo: cache index for (var di = 0; di < this.stats.length; di++) { if (this.stats[di].date.day == day && this.stats[di].date.month == month && this.stats[di].date.year == year) { return this.stats[di].allowedToSpend; } } return null; }, reloadStats: function() { App.localStorage.remove('plan_' + this.id + '_data'); this.areStatsReady = false; return this.getStats(); }, getStats: function() { var deferred = jQuery.Deferred(); if (this.areStatsReady) { this.trigger('statsready'); deferred.resolve(this.stats); return deferred; } var cached = App.localStorage.get('plan_' + this.id + '_data'); if (cached !== null && cached !== undefined) { var cachedDate = new Date(1000 * cached.saved); var curDate = new Date(); if (cachedDate.getMonth() == curDate.getMonth() && cachedDate.getDate() == curDate.getDate() && cachedDate.getFullYear() == curDate.getFullYear()) { console.log('plan.js | restore stats from cache'); this.stats = cached.stats; this.areStatsReady = true; this.trigger('statsready'); deferred.resolve(this.stats); return deferred; } else { console.log('plan.js | cache is too old'); } } var plan = this; var daysCount = Math.ceil((this.get('goal_datetime') - this.get('start_datetime')) / (24 * 60 * 60)); this.stats = []; var lastDayDate = new Date(1000 * this.get('goal_datetime')); for (var i = 0; i < daysCount; i++) { var dayStat = {}; dayStat.date = {}; dayStat.date.unix = (this.get('start_datetime') + 24 * 60 * 60 * i); dayStat.date.date = new Date(1000 * dayStat.date.unix); dayStat.date.month = dayStat.date.date.getMonth() + 1; dayStat.date.year = dayStat.date.date.getFullYear(); dayStat.date.day = dayStat.date.date.getDate(); dayStat.date.unix_from = (new Date(dayStat.date.year, dayStat.date.month - 1, dayStat.date.day, 0, 0, 0, 0)).getTime() / 1000; dayStat.date.unix_to = dayStat.date.unix_from + 24 * 60 * 60; dayStat.expenses = {}; dayStat.expensesTotal = 0; dayStat.profits = {}; dayStat.profitsTotal = 0; dayStat.dayTotal = 0; if (dayStat.date.day != lastDayDate.getDate() || dayStat.date.month != lastDayDate.getMonth() + 1 || dayStat.date.year != lastDayDate.getFullYear()) { // push stats othen than for the last day to stats array this.stats.push(dayStat); } } this.once('walletsloadded', function() { for (var wk in plan.loadedWallets) plan.walletsCurrencies[plan.loadedWallets[wk].id] = plan.loadedWallets[wk].get('currency'); for (var di = 0; di < plan.stats.length; di++) { for (var tk in plan.transactions) { plan.stats[di].expenses[tk] = 0; plan.stats[di].profits[tk] = 0; } } /// get spending per day for (var di = 0; di < plan.stats.length; di++) { for (var tk in plan.transactions) { for (var wti = 0; wti < plan.transactions[tk].length; wti++) { if (plan.transactions[tk][wti].get('datetime') >= plan.stats[di].date.unix_from && plan.transactions[tk][wti].get('datetime') < plan.stats[di].date.unix_to) { var absInWalletCurrency = Math.abs(plan.transactions[tk][wti].get('amount')); var absInGoalCurrency = App.exchange.convert(absInWalletCurrency, plan.walletsCurrencies[tk], plan.get('goal_currency')); if (plan.transactions[tk][wti].get('amount') < 0) { // expense plan.stats[di].expenses[tk] += absInGoalCurrency; plan.stats[di].expensesTotal += absInGoalCurrency; plan.stats[di].dayTotal -= absInGoalCurrency; } else { // profit plan.stats[di].profits[tk] += absInGoalCurrency; plan.stats[di].profitsTotal += absInGoalCurrency; plan.stats[di].dayTotal += absInGoalCurrency; } } } } } /// average spendings by empty days var emptyFrom = null; var groupExpenses = 0; var groupProfits = 0; var groupCount = 0; for (var di = 0; di < plan.stats.length; di++) { if (plan.stats[di].expensesTotal == 0 && plan.stats[di].profitsTotal == 0) { if (emptyFrom === null) emptyFrom = di; groupCount++; } else { groupCount++; groupExpenses = plan.stats[di].expensesTotal; groupProfits = plan.stats[di].profitsTotal; if (emptyFrom !== null) { groupExpenses = groupExpenses / groupCount; groupProfits = groupProfits / groupCount; for (var dgi = emptyFrom; dgi <= di; dgi++) { plan.stats[dgi].expensesTotal = groupExpenses; plan.stats[dgi].profitsTotal = groupProfits; plan.stats[dgi].dayTotal = groupProfits - groupExpenses; } } emptyFrom = null; groupCount = 0; groupExpenses = 0; groupProfits = 0; } } var currentTotal = App.exchange.convert(plan.get('start_balance'), plan.get('start_currency'), plan.get('goal_currency')); var goalTotal = plan.get('goal_balance'); for (var di = 0; di < plan.stats.length; di++) { plan.stats[di].currentTotalOnStart = currentTotal; plan.stats[di].allowedToSpend = (goalTotal - currentTotal) / (plan.stats.length - di); currentTotal += plan.stats[di].dayTotal; plan.stats[di].currentTotalOnEnd = currentTotal; } plan.areStatsReady = true; App.localStorage.set('plan_' + plan.id + '_data', { stats: plan.stats, saved: (new Date().getTime() / 1000) }); plan.trigger('statsready'); deferred.resolve(plan.stats); }); this.loadWallets(); return deferred; }, loadWallets: function() { var plan = this; var wallets = this.get('wallets'); for (var k in wallets) { var wallet = new App.Models.Wallet(); wallet.id = wallets[k].id; this.loadedWallets.push(wallet); } var complete = _.invoke(this.loadedWallets, 'fetch'); $.when.apply($, complete).done(function() { var completeTransactions = _.invoke(plan.loadedWallets, 'getTransactionsForPeriod', plan.get('start_datetime'), plan.get('goal_datetime')); $.when.apply($, completeTransactions).done(function() { var allTransactions = Array.prototype.slice.call(arguments); for (var k in allTransactions) { var wallet_id = plan.loadedWallets[k].id; plan.transactions[wallet_id] = allTransactions[k]; } plan.trigger('walletsloadded'); }); }); } }); ================================================ FILE: public/scripts/app/models/transaction.js ================================================ // transaction.js App.Models.Transaction = Backbone.Model.extend({ defaults: function() { return { user_id: null, wallet_id: null, description: null, type: null, subtype: null, amount: null, abs_amount: null, datetime: Math.floor((new Date().getTime()) / 1000) } }, url: function() { if (!this.get('wallet_id')) return App.settings.apiEntryPoint + 'transactions/' + (typeof(this.id) === 'undefined' ? '' : this.id); else return App.settings.apiEntryPoint + 'wallets/' + this.get('wallet_id') + '/transactions/' + (typeof(this.id) === 'undefined' ? '' : this.id); } }); ================================================ FILE: public/scripts/app/models/user.js ================================================ // user.js App.Models.User = Backbone.Model.extend({ validate: function(attrs, options) { var errors = []; if (typeof(this.get('email')) !== 'string' || !isEmail(this.get('email'))) errors.push({ msg: 'Invalid email', attr: 'email' }); else if (this.get('email').length > 255) errors.push({ msg: 'Email is too long', attr: 'email' }); if (typeof(this.get('login')) !== 'string' || this.get('login').length < 2) errors.push({ msg: 'Username is too short', attr: 'login' }); else if (this.get('login').length > 255) errors.push({ msg: 'Username is too long', attr: 'login' }); if (typeof(this.get('password')) !== 'string' || this.get('password').length < 6) errors.push({ msg: 'Password is too short', attr: 'password' }); if (errors.length) return errors; }, defaults: { auth_code: null, email: null, password: null, is_demo: null, login: null, }, signedIn: false, signInError: null, url: function() { return App.settings.apiEntryPoint + 'users' + (typeof(this.id) === 'undefined' ? '' : '/' + this.id); }, getWallets: function() { if (typeof(this.wallets) === 'undefined') { this.wallets = new App.Collections.Wallets(); this.wallets.setUserId(this.id); } return this.wallets; }, getPlans: function() { if (typeof(this.plans) === 'undefined') { this.plans = new App.Collections.Plans(); this.plans.setUserId(this.id); } return this.plans; }, isSignedIn: function() { return this.signedIn; }, isAdmin: function() { return false; }, isDemo: function() { return (this.get('is_demo') == true); // yep, == }, signInWithData: function(data) { if (typeof(data) !== 'undefined') { this.set(data); if (this.signedIn === false) { this.signedIn = true; this.trigger('signedInStatusChanged'); } } else { if (this.signedIn === true) { this.signedIn = false; this.trigger('signedInStatusChanged'); } } }, demoRegister: function() { this.register('demo', 'demo@demo.com', 'demonstration'); }, changePassword: function(currentPassword, newPassword) { var that = this; this.set('current_password', currentPassword); this.set('password', newPassword); return this.save(null, { success: function(model, data) { if (typeof(data.id) !== 'undefined') { console.log("Server side change password success"); that.set('password', ''); that.trigger('changed'); } }, error: function(model, response) { console.log("Server side change password error"); if (typeof(response.responseJSON) !== 'undefined' && typeof(response.responseJSON.message) !== 'undefined') { if (!(that.validationError instanceof Array)) that.validationError = []; for (var k in response.responseJSON.message) that.validationError.push({ msg: response.responseJSON.message[k] }); } that.trigger('invalid'); } }); }, fillProfile: function(login, email, password) { var that = this; this.set('login', login); this.set('email', email); this.set('password', password); this.set('is_demo', false); return this.save(null, { success: function(model, data) { if (typeof(data.id) !== 'undefined') { console.log("Server side fill profile success"); that.set('password', ''); that.trigger('filled'); } }, error: function(model, response) { console.log("Server side fill profile error"); if (typeof(response.responseJSON) !== 'undefined' && typeof(response.responseJSON.message) !== 'undefined') { if (!(that.validationError instanceof Array)) that.validationError = []; if (typeof(response.responseJSON.message) === 'string') { that.validationError.push({ msg: response.responseJSON.message }); } else { for (var k in response.responseJSON.message) that.validationError.push({ msg: response.responseJSON.message[k] }); } } that.trigger('invalid'); } }); }, register: function(login, email, password) { var that = this; this.set('login', login); this.set('email', email); this.set('password', password); return this.save(null, { success: function(model, data) { if (typeof(data.id) !== 'undefined') { console.log("Server side registration success"); that.set('password', ''); that.trigger('registered'); if (typeof(data.auth_code) !== 'undefined') { // And signed in that.signedIn = true; that.trigger('signedInStatusChanged'); console.log("Server side registration - signed in"); } } }, error: function(model, response) { console.log("Server side registration error"); if (typeof(response.responseJSON) !== 'undefined' && typeof(response.responseJSON.message) !== 'undefined') { if (!(that.validationError instanceof Array)) that.validationError = []; if (typeof(response.responseJSON.message) === 'string') { that.validationError.push({ msg: response.responseJSON.message }); } else { for (var k in response.responseJSON.message) that.validationError.push({ msg: response.responseJSON.message[k] }); } } that.trigger('invalid'); } }); }, newPassword: function(code, hash, password) { var that = this; var url = App.settings.apiEntryPoint + 'users/newpassword'; this.clear(); $.ajax({ url: url, type: 'POST', dataType: "json", data: { code: code, hash: hash, password: password }, success: function(data) { console.log('Success setting new password'); that.trigger('newpassword:success'); }, error: function(data) { console.log('Error setting new password'); that.validationError = []; if (typeof(data.responseJSON) != 'undefined' && typeof(data.responseJSON.code) != 'undefined' && typeof(data.responseJSON.message) != 'undefined') if (data.responseJSON.message instanceof Array) { for (var k in data.responseJSON.message) that.validationError.push({ msg: data.responseJSON.message[k] }); } else { that.validationError.push({ msg: data.responseJSON.message }); } that.trigger('newpassword:error'); } }); return true; }, restorePassword: function(email) { var that = this; var url = App.settings.apiEntryPoint + 'users/restore'; this.clear(); $.ajax({ url: url, type: 'POST', dataType: "json", data: { email: email }, success: function(data) { console.log('Success restoring password'); that.trigger('restore:success'); }, error: function(data) { console.log('Error restoring password'); that.validationError = []; if (typeof(data.responseJSON) != 'undefined' && typeof(data.responseJSON.message) != 'undefined') if (data.responseJSON.message instanceof Array) { for (var k in data.responseJSON.message) that.validationError.push({ msg: data.responseJSON.message[k] }); } else { that.validationError.push({ msg: data.responseJSON.message }); } that.trigger('restore:error'); } }); return true; }, signIn: function(username, password) { var that = this; var url = App.settings.apiEntryPoint + 'users/signin'; $.ajax({ url: url, type: 'POST', dataType: "json", data: { username: username, password: password }, success: function(data) { if (typeof(data.auth_code) != 'undefined' && data.auth_code) { console.log('Logged in successfully'); that.trigger('signedin'); that.signInWithData(data); } }, error: function(data) { console.log('Cannot log in'); that.signInWithData(); if (!(that.validationError instanceof Array)) that.validationError = []; if (typeof(data.responseJSON) != 'undefined' && typeof(data.responseJSON.code) != 'undefined' && typeof(data.responseJSON.message) != 'undefined') for (var k in data.responseJSON.message) that.validationError.push({ msg: data.responseJSON.message[k] }); that.trigger('invalid'); } }); return true; }, signOut: function() { var that = this; var url = App.settings.apiEntryPoint + 'users/signout'; if (!this.isSignedIn()) { return false; } this.signedIn = false; this.clear().set(this.defaults); delete this.wallets; $.ajax({ url: url, type: 'POST', dataType: "json", success: function(data) { console.log('Signed out'); that.trigger('signedout'); that.signInWithData(); }, error: function(data) { console.error('Error signing out'); } }); return true; }, removeAccount: function() { var that = this; var url = App.settings.apiEntryPoint + 'users/' + this.id + '/removeaccount'; $.ajax({ url: url, type: 'POST', dataType: "json", success: function(data) { console.log('Asked server to start user account removal'); that.trigger('removeaccountstart'); }, error: function(data) {} }); return true; }, removeAccountConfirm: function(code) { var that = this; var url = App.settings.apiEntryPoint + 'users/' + this.id + '/removeaccount'; var data = { code: code }; $.ajax({ url: url, data: data, type: 'POST', dataType: "json", success: function(data) { console.log('Asked server to finish user account removal'); if (data) { that.trigger('removeaccountdone'); } else that.trigger('removeaccountwrongcode'); }, error: function(data) { that.trigger('removeaccountwrongcode'); } }); return true; } }); ================================================ FILE: public/scripts/app/models/wallet.js ================================================ // wallet.js App.Models.Wallet = Backbone.Model.extend({ defaults: { name: null, type: null, status: 'active', total: null, currency: 'USD' }, getTotal: function() { return parseFloat(this.get('total'), 10); }, url: function() { return App.settings.apiEntryPoint + 'wallets/' + (typeof(this.id) === 'undefined' ? '' : this.id); }, hide: function() { if (this.get('status') == 'active') { this.set('status', 'hidden'); this.save(); } else if (this.get('status') == 'hidden') { this.destroy(); } }, getTransactions: function() { if (typeof(this.transactions) === 'undefined') { this.transactions = new App.Collections.Transactions(); this.transactions.setWalletId(this.id); var that = this; this.transactions.fetch().done(function() {}); } this.transactions.setWalletId(this.id); return this.transactions; }, getPlans: function() { if (typeof(this.plans) === 'undefined') { this.plans = new App.Collections.Plans(); this.plans.setWalletId(this.id); var that = this; this.plans.fetch().done(function() { that.trigger('plansloaded'); }); } this.plans.setWalletId(this.id); return this.plans; }, getTransactionsForPeriod: function(from, to, callback) { var deferred = jQuery.Deferred(); var transactions = new App.Collections.Transactions(); var aTransactions = []; transactions.setWalletId(this.id); var fromDate = new Date(from * 1000); var fromMonth = fromDate.getMonth() + 1; var fromYear = fromDate.getFullYear(); var toDate = new Date(to * 1000); var toMonth = toDate.getMonth() + 1; var toYear = toDate.getFullYear(); var curMonth = fromMonth; var curYear = fromYear; var fetched = function() { transactions.forEach(function(t) { if (t.get('datetime') >= from && t.get('datetime') <= to) aTransactions.push(t); }); fetchNext(); }; var fetch = function() { transactions.setPeriod(curMonth, curYear); transactions.fetch().done(fetched); }; var fetchNext = function() { if (curMonth >= toMonth && curYear >= toYear) { if (typeof(callback) === 'function') callback(aTransactions); deferred.resolve(aTransactions); return false; } curMonth++; if (curMonth > 12) { curMonth = 1; curYear++; } fetch(); return true; }; fetch(); return deferred; }, addProfit: function(amount, description) { var profit = new App.Models.Transaction(); var amountValue = Math.abs(parseFloat(amount, 10)); amountValue = Math.round(amountValue * 100) / 100; profit.set('description', description); profit.set('amount', amountValue); profit.set('wallet_id', this.id); profit.save(); this.getTransactions().add(profit); this.set('total', this.getTotal() + amountValue); this.trigger('addTransaction', profit); //this.trigger('change'); }, setTotalTo: function(total) { var transaction = new App.Models.Transaction(); var totalValue = parseFloat(total, 10); totalValue = Math.round(totalValue * 100) / 100; transaction.set('amount', totalValue); transaction.set('subtype', 'setup'); transaction.set('wallet_id', this.id); transaction.save(); this.getTransactions().add(transaction); this.set('total', totalValue); this.trigger('addTransaction', transaction); //this.trigger('change'); }, addExpense: function(amount, description) { var expense = new App.Models.Transaction(); var amountValue = -Math.abs(parseFloat(amount, 10)); amountValue = Math.round(amountValue * 100) / 100; expense.set('description', description); expense.set('amount', amountValue); expense.set('wallet_id', this.id); expense.save(); this.getTransactions().add(expense); this.set('total', this.getTotal() + amountValue); this.trigger('addTransaction', expense); this.trigger('addExpense'); //this.trigger('change'); }, removeTransaction: function(transaction) { var newTotal = this.get('total') - transaction.get('amount'); var transactionId = transaction.id; this.getTransactions().remove(transaction); transaction.destroy(); this.set('total', newTotal); this.trigger('removeTransaction', transactionId); } }); ================================================ FILE: public/scripts/app/models/wallets_access.js ================================================ // wallets_access.js App.Models.WalletsAccess = Backbone.Model.extend({ defaults: { wallet_id: null, to_user_id: null, original_user_id: null, to_email: null }, url: function() { if (!this.get('wallet_id')) return App.settings.apiEntryPoint + 'wallets_accesses/' + (typeof(this.id) === 'undefined' ? '' : this.id); else return App.settings.apiEntryPoint + 'wallets/' + this.get('wallet_id') + '/accesses/' + (typeof(this.id) === 'undefined' ? '' : this.id); }, getGravatarURL: function() { return "http://www.gravatar.com/avatar/" + md5(this.get('to_email').replace(/^\s+|\s+$/g, '').toLowerCase()); } }); ================================================ FILE: public/scripts/app/router.js ================================================ // router.js App.router = new(Backbone.Router.extend({ setUrl: function(path) { this.navigate(path); }, redirect: function(path) { if (typeof(App.page) !== 'undefined' && App.page && typeof(App.page.isReady) !== 'undefined' && !App.page.isReady) App.loadingStatus(false); this.navigate(path, { trigger: true }); }, routes: { "(/)": "index", // #help "profile(/)": "profile", "plans(/)": "plans", "plans/:id": "plan", "wallets(/)": "wallets", "wallets/:id": "wallet", "wallets/:id/import(/)": "importXLS", "user/updatepassword/:code/:hash": "updatePassword" }, dialogs: { "user/signin": "Signin", "user/registration": "Registration", "user/restore": "Restore", "user/logout": "Logout", "user/fillprofile": "FillProfile", "wallets/add": "AddWallet", "user/change_language": "ChangeLanguage" }, index: function() { App.showPage('Index'); }, plans: function() { App.showPage('Plans'); }, plan: function(id) { App.showPage('Plan', { id: id }); }, profile: function() { App.showPage('Profile'); }, updatePassword: function(code, hash) { App.showPage('UpdatePassword', { password_restore_code: code, password_restore_hash: hash }); }, wallet: function(id) { App.showPage('Wallet', { id: id }); }, importXLS: function(wallet_id) { App.showPage('ImportXLS', { wallet_id: wallet_id }); }, wallets: function() { App.showPage('Wallets'); }, init: function() { Backbone.history.start({ pushState: App.settings.history.pushState, silent: App.settings.history.startSilent }); Backbone.history.isRoutingURL = function(fragment) { for (var k in this.handlers) if (this.handlers[k].route.test(fragment)) return true; return false; }; var that = this; if (Backbone.history && Backbone.history._hasPushState) { $(document).on("click", "a", function(evt) { if (typeof(evt.ctrlKey) !== 'undefined' && evt.ctrlKey) return true; var href = $(this).attr("href"); var protocol = this.protocol + "//"; href = href.split(App.settings.sitePath).join(''); href = href.slice(-1) == '/' ? href.slice(0, -1) : href; href = href.slice(0, 1) == '/' ? href.slice(1) : href; /// trying to find dialog for (var k in that.dialogs) if (k == href) { console.log('Showing "' + that.dialogs[k] + '" dialog from document click event'); App.showDialog(that.dialogs[k]); return false; } // Ensure the protocol is not part of URL, meaning its relative. if (href.slice(protocol.length) !== protocol && Backbone.history.isRoutingURL(href)) { console.log('Navigating to "' + href + '" from document click event'); evt.preventDefault(); App.router.navigate(href, { trigger: true }); return false; } return true; }); } } }))(); ================================================ FILE: public/scripts/app/settings.js ================================================ // settings.js App.settings = { sitePath: site_path, apiEntryPoint: site_path + '/api/', templatePath: site_path + '/jstemplates/', version: (typeof(app_version) !== 'undefined') ? app_version : '', title: function(title) { return title + ' | ' + 'DimeShift'; }, availiableLocales: { 'default': { code: 'en', name: 'English', timeFormat: '12', dateFormat: 'mdy' }, 'ua': { name: 'Українська', timeFormat: '24', dateFormat: 'dmy' }, 'ru': { name: 'Русский', timeFormat: '24', dateFormat: 'dmy' }, 'pt-br': { name: 'Português Brasileiro', timeFormat: '24', dateFormat: 'dmy' } }, detectLanguage: function() { var language = 'default'; if (App.localStorage.get('selected_interface_locale')) language = App.localStorage.get('selected_interface_locale'); else { language = window.navigator.userLanguage || window.navigator.language; if (language && typeof(this.availiableLocales[language]) == 'undefined' && language.indexOf('-') != -1) { language = language.split('-')[0]; } } if (typeof(this.availiableLocales[language]) == 'undefined') language = 'default'; this.timeFormat = this.availiableLocales[language][0]; this.dateFormat = this.availiableLocales[language][1]; this.language = language; return language; }, language: 'en', timeFormat: '24', // 12 or 24 dateFormat: 'dmy', // mdy or dmy allowRealTimeTranslation: true, enableTemplatesCache: false, enablePagesStack: true, pagesStackMaxLength: 25, history: { pushState: true, startSilent: false }, inviteMode: true, site_path: site_path, invite_mode: this.inviteMode, client_side: true, currencies: { "AED": "United Arab Emirates Dirham", "AFN": "Afghan Afghani", "ALL": "Albanian Lek", "AMD": "Armenian Dram", "ANG": "Netherlands Antillean Guilder", "AOA": "Angolan Kwanza", "ARS": "Argentine Peso", "AUD": "Australian Dollar", "AWG": "Aruban Florin", "AZN": "Azerbaijani Manat", "BAM": "Bosnia-Herzegovina Convertible Mark", "BBD": "Barbadian Dollar", "BDT": "Bangladeshi Taka", "BGN": "Bulgarian Lev", "BHD": "Bahraini Dinar", "BIF": "Burundian Franc", "BMD": "Bermudan Dollar", "BND": "Brunei Dollar", "BOB": "Bolivian Boliviano", "BRL": "Brazilian Real", "BSD": "Bahamian Dollar", "BTC": "Bitcoin", "BTN": "Bhutanese Ngultrum", "BWP": "Botswanan Pula", "BYR": "Belarusian Ruble", "BZD": "Belize Dollar", "CAD": "Canadian Dollar", "CDF": "Congolese Franc", "CHF": "Swiss Franc", "CLF": "Chilean Unit of Account (UF)", "CLP": "Chilean Peso", "CNY": "Chinese Yuan", "COP": "Colombian Peso", "CRC": "Costa Rican Colón", "CUP": "Cuban Peso", "CVE": "Cape Verdean Escudo", "CZK": "Czech Republic Koruna", "DJF": "Djiboutian Franc", "DKK": "Danish Krone", "DOP": "Dominican Peso", "DZD": "Algerian Dinar", "EEK": "Estonian Kroon", "EGP": "Egyptian Pound", "ERN": "Eritrean Nakfa", "ETB": "Ethiopian Birr", "EUR": "Euro", "FJD": "Fijian Dollar", "FKP": "Falkland Islands Pound", "GBP": "British Pound Sterling", "GEL": "Georgian Lari", "GGP": "Guernsey Pound", "GHS": "Ghanaian Cedi", "GIP": "Gibraltar Pound", "GMD": "Gambian Dalasi", "GNF": "Guinean Franc", "GTQ": "Guatemalan Quetzal", "GYD": "Guyanaese Dollar", "HKD": "Hong Kong Dollar", "HNL": "Honduran Lempira", "HRK": "Croatian Kuna", "HTG": "Haitian Gourde", "HUF": "Hungarian Forint", "IDR": "Indonesian Rupiah", "ILS": "Israeli New Sheqel", "IMP": "Manx pound", "INR": "Indian Rupee", "IQD": "Iraqi Dinar", "IRR": "Iranian Rial", "ISK": "Icelandic Króna", "JEP": "Jersey Pound", "JMD": "Jamaican Dollar", "JOD": "Jordanian Dinar", "JPY": "Japanese Yen", "KES": "Kenyan Shilling", "KGS": "Kyrgystani Som", "KHR": "Cambodian Riel", "KMF": "Comorian Franc", "KPW": "North Korean Won", "KRW": "South Korean Won", "KWD": "Kuwaiti Dinar", "KYD": "Cayman Islands Dollar", "KZT": "Kazakhstani Tenge", "LAK": "Laotian Kip", "LBP": "Lebanese Pound", "LKR": "Sri Lankan Rupee", "LRD": "Liberian Dollar", "LSL": "Lesotho Loti", "LTL": "Lithuanian Litas", "LVL": "Latvian Lats", "LYD": "Libyan Dinar", "MAD": "Moroccan Dirham", "MDL": "Moldovan Leu", "MGA": "Malagasy Ariary", "MKD": "Macedonian Denar", "MMK": "Myanma Kyat", "MNT": "Mongolian Tugrik", "MOP": "Macanese Pataca", "MRO": "Mauritanian Ouguiya", "MTL": "Maltese Lira", "MUR": "Mauritian Rupee", "MVR": "Maldivian Rufiyaa", "MWK": "Malawian Kwacha", "MXN": "Mexican Peso", "MYR": "Malaysian Ringgit", "MZN": "Mozambican Metical", "NAD": "Namibian Dollar", "NGN": "Nigerian Naira", "NIO": "Nicaraguan Córdoba", "NOK": "Norwegian Krone", "NPR": "Nepalese Rupee", "NZD": "New Zealand Dollar", "OMR": "Omani Rial", "PAB": "Panamanian Balboa", "PEN": "Peruvian Nuevo Sol", "PGK": "Papua New Guinean Kina", "PHP": "Philippine Peso", "PKR": "Pakistani Rupee", "PLN": "Polish Zloty", "PYG": "Paraguayan Guarani", "QAR": "Qatari Rial", "RON": "Romanian Leu", "RSD": "Serbian Dinar", "RUB": "Russian Ruble", "RWF": "Rwandan Franc", "SAR": "Saudi Riyal", "SBD": "Solomon Islands Dollar", "SCR": "Seychellois Rupee", "SDG": "Sudanese Pound", "SEK": "Swedish Krona", "SGD": "Singapore Dollar", "SHP": "Saint Helena Pound", "SLL": "Sierra Leonean Leone", "SOS": "Somali Shilling", "SRD": "Surinamese Dollar", "STD": "São Tomé and Príncipe Dobra", "SVC": "Salvadoran Colón", "SYP": "Syrian Pound", "SZL": "Swazi Lilangeni", "THB": "Thai Baht", "TJS": "Tajikistani Somoni", "TMT": "Turkmenistani Manat", "TND": "Tunisian Dinar", "TOP": "Tongan Paʻanga", "TRY": "Turkish Lira", "TTD": "Trinidad and Tobago Dollar", "TWD": "New Taiwan Dollar", "TZS": "Tanzanian Shilling", "UAH": "Ukrainian Hryvnia", "UGX": "Ugandan Shilling", "USD": "United States Dollar", "UYU": "Uruguayan Peso", "UZS": "Uzbekistan Som", "VEF": "Venezuelan Bolívar Fuerte", "VND": "Vietnamese Dong", "VUV": "Vanuatu Vatu", "WST": "Samoan Tala", "XAF": "CFA Franc BEAC", "XAG": "Silver (troy ounce)", "XAU": "Gold (troy ounce)", "XCD": "East Caribbean Dollar", "XDR": "Special Drawing Rights", "XOF": "CFA Franc BCEAO", "XPF": "CFP Franc", "YER": "Yemeni Rial", "ZAR": "South African Rand", "ZMK": "Zambian Kwacha (pre-2013)", "ZMW": "Zambian Kwacha", "ZWL": "Zimbabwean Dollar" } }; ================================================ FILE: public/scripts/app/template_manager.js ================================================ // template_manager.js App.templateManager = { _cache: {}, _templates: {}, _loadingStates: {}, _loadingCallbacks: {}, _initialized: false, modifiers: { decimal: function(s) { var decimal = Math.round((Math.abs(+s) % 1).toFixed(2) * 100); if (decimal === 0) return '00'; if (decimal < 10) return '0' + decimal; if (decimal === 100) return '99'; return decimal; }, rational: function(s) { var rational = Math.floor(Math.abs(+s)); return rational; } }, initialize: function() { jSmart.prototype.getTemplate = function(name) { if (name.indexOf('shared/widgets/') === 0) { /// It's a widget! var widgetName = name.split('shared/widgets/').join('').split('.tpl').join(''); console.log('template_manager.js | Including widget "' + widgetName + '"'); return '
'; } if (typeof(App.templateManager._templates[name]) !== 'undefined') { return App.templateManager._cache[name]; } else { throw new Error('Template ' + name + ' is not yet loaded'); } }; jSmart.prototype.registerPlugin( 'modifier', 'decimal', this.modifiers.decimal ); jSmart.prototype.registerPlugin( 'modifier', 'rational', this.modifiers.rational ); Date.prototype.format = function(e) { var t = ""; var n = Date.replaceChars; for (var r = 0; r < e.length; r++) { var i = e.charAt(r); if (r - 1 >= 0 && e.charAt(r - 1) == "\\") { t += i } else if (n[i]) { t += n[i].call(this) } else if (i != "\\") { t += i } } return t }; Date.replaceChars = { shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], longMonths: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], longDays: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], d: function() { return (this.getDate() < 10 ? "0" : "") + this.getDate() }, D: function() { return Date.replaceChars.shortDays[this.getDay()] }, j: function() { return this.getDate() }, l: function() { return Date.replaceChars.longDays[this.getDay()] }, N: function() { return this.getDay() + 1 }, S: function() { return this.getDate() % 10 == 1 && this.getDate() != 11 ? "st" : this.getDate() % 10 == 2 && this.getDate() != 12 ? "nd" : this.getDate() % 10 == 3 && this.getDate() != 13 ? "rd" : "th" }, w: function() { return this.getDay() }, z: function() { var e = new Date(this.getFullYear(), 0, 1); return Math.ceil((this - e) / 864e5) }, W: function() { var e = new Date(this.getFullYear(), 0, 1); return Math.ceil(((this - e) / 864e5 + e.getDay() + 1) / 7) }, F: function() { return Date.replaceChars.longMonths[this.getMonth()] }, m: function() { return (this.getMonth() < 9 ? "0" : "") + (this.getMonth() + 1) }, M: function() { return Date.replaceChars.shortMonths[this.getMonth()] }, n: function() { return this.getMonth() + 1 }, t: function() { var e = new Date; return (new Date(e.getFullYear(), e.getMonth(), 0)).getDate() }, L: function() { var e = this.getFullYear(); return e % 400 == 0 || e % 100 != 0 && e % 4 == 0 }, o: function() { var e = new Date(this.valueOf()); e.setDate(e.getDate() - (this.getDay() + 6) % 7 + 3); return e.getFullYear() }, Y: function() { return this.getFullYear() }, y: function() { return ("" + this.getFullYear()).substr(2) }, a: function() { return this.getHours() < 12 ? "am" : "pm" }, A: function() { return this.getHours() < 12 ? "AM" : "PM" }, B: function() { return Math.floor(((this.getUTCHours() + 1) % 24 + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1e3 / 24) }, g: function() { return this.getHours() % 12 || 12 }, G: function() { return this.getHours() }, h: function() { return ((this.getHours() % 12 || 12) < 10 ? "0" : "") + (this.getHours() % 12 || 12) }, H: function() { return (this.getHours() < 10 ? "0" : "") + this.getHours() }, i: function() { return (this.getMinutes() < 10 ? "0" : "") + this.getMinutes() }, s: function() { return (this.getSeconds() < 10 ? "0" : "") + this.getSeconds() }, u: function() { var e = this.getMilliseconds(); return (e < 10 ? "00" : e < 100 ? "0" : "") + e }, e: function() { return "Not Yet Supported" }, I: function() { var e = null; for (var t = 0; t < 12; ++t) { var n = new Date(this.getFullYear(), t, 1); var r = n.getTimezoneOffset(); if (e === null) e = r; else if (r < e) { e = r; break } else if (r > e) break } return this.getTimezoneOffset() == e | 0 }, O: function() { return (-this.getTimezoneOffset() < 0 ? "-" : "+") + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? "0" : "") + Math.abs(this.getTimezoneOffset() / 60) + "00" }, P: function() { return (-this.getTimezoneOffset() < 0 ? "-" : "+") + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? "0" : "") + Math.abs(this.getTimezoneOffset() / 60) + ":00" }, T: function() { var e = this.getMonth(); this.setMonth(0); var t = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, "$1"); this.setMonth(e); return t }, Z: function() { return -this.getTimezoneOffset() * 60 }, c: function() { return this.format("Y-m-d\\TH:i:sP") }, r: function() { return this.toString() }, U: function() { return this.getTime() / 1e3 } }; jSmart.prototype.registerPlugin( 'modifier', 'date_format', function(s, fmt, defaultDate) { var date = new Date(s * 1000); return date.format(fmt ? fmt : 'M j, Y', s ? s : defaultDate); } ); jSmart.prototype.registerPlugin( 'modifier', 'wallet_time', function(s) { var date = new Date(s * 1000); if (App.settings.timeFormat == '12') return date.format('g:i a', s); else return date.format('H:i', s); } ); jSmart.prototype.registerPlugin( 'modifier', 'wallet_date', function(s) { var date = new Date(s * 1000); if (App.settings.dateFormat == 'mdy') return date.format('M j, Y', s); else { var monthName = date.format('F', s).toLowerCase(); return date.format('j', s) + ' ' + App.i18n.translate(monthName) + ' ' + date.format('Y', s); } } ); jSmart.prototype.registerPlugin( 'block', 't', function(params, content, data, repeat) { if (typeof(App) === 'undefined' || typeof(App.i18n) === 'undefined') return content; else return App.i18n.translate(content); } ); jSmart.prototype.registerPlugin( 'block', 'tp', function(params, content, data, repeat) { if (typeof(App) === 'undefined' || typeof(App.i18n) === 'undefined') return '' + content + ""; else return '' + App.i18n.translate(content) + ""; } ); this._initialized = true; }, commonData: function() { return { settings: _.extend(App.settings, { site_path: App.settings.sitePath, client_side: true, invite_mode: App.settings.inviteMode }) }; }, fetch: function(name, data, success) { if (!this._initialized) this.initialize(); data = _.extend(data, this.commonData()); if (typeof(this._templates[name]) !== 'undefined' || this.tryToLoadFromStorage(name)) { var res = this._templates[name].fetch(data); if (typeof(success) === 'function') success(res); return res; } var that = this; if (typeof(success) === 'function') { if (typeof(this._loadingStates[name]) !== 'undefined' && this._loadingStates[name] === 'loading') { // already fetched if (typeof(this._loadingCallbacks[name]) === 'undefined') { this._loadingCallbacks[name] = []; } this._loadingCallbacks[name].push(function(tpl) { success(tpl.fetch(data)); }); } else { // fetch template this.loadFromServer(name, function(tpl) { success(tpl.fetch(data)); }); } } else { this.loadFromServer(name); } return false; }, tryToLoadFromStorage: function(name) { if (!App.settings.enableTemplatesCache) { console.log('Templates cache is disabled'); return false; } if (!App.localStorage.isSupported()) { console.log('Local storage is disabled'); return false; } var data = App.localStorage.get('app_temapltes_' + name); if (data) { this._cache[name] = data; this._templates[name] = new jSmart(data); this._loadingStates[name] = 'ready'; return true; } return false; }, loadFromServer: function(name, callback) { this._loadingStates[name] = 'loading'; var that = this; var templateName = name; var callbackFunc = callback; console.time("template_manager.js | Fetch " + templateName + " from server"); var process = function(data) { console.timeEnd("template_manager.js | Fetch " + templateName + " from server"); console.group("Template name: " + templateName); console.log("Callback function present: " + typeof(callbackFunc)); if (typeof(that._loadingCallbacks[templateName]) === 'undefined') console.log("No additional callbacks"); else console.log("Additional callbacks: " + that._loadingCallbacks[templateName].length); console.groupEnd(); if (data) { App.localStorage.set('app_temapltes_' + templateName, data); that._cache[templateName] = data; that._templates[templateName] = new jSmart(data); that._loadingStates[templateName] = 'ready'; if (typeof(callbackFunc) === 'function') callbackFunc(that._templates[templateName]); if (typeof(that._loadingCallbacks[templateName]) !== 'undefined') { for (var k in that._loadingCallbacks[templateName]) that._loadingCallbacks[templateName][k](that._templates[templateName]); that._loadingCallbacks[templateName] = []; } } }; var use_cache = true; if (!App.settings.enableTemplatesCache) use_cache = false; $.ajax({ url: App.settings.templatePath + name, data: {}, success: process, dataType: 'html', mimeType: 'text/plain', cache: use_cache }); } }; ================================================ FILE: public/scripts/app/view_stack.js ================================================ // view_stack.js App.viewStack = { stack: {}, inStackCount: 0, addView: function(name, params, view) { if (!App.settings.enablePagesStack) return false; var hash = name; if (typeof(params) !== 'undefined') for (var k in params) { if (typeof(params[k].id) !== 'undefined') hash += '-' + k + '_id' + params[k].id; else hash += '-' + k + '_' + params[k]; } this.stack[hash] = { view: view, hash: hash, added: new Date() }; this.inStackCount++; this.removeOldestIfNeeded(); return true; }, getView: function(name, params) { if (!App.settings.enablePagesStack) return false; var hash = name; if (typeof(params) !== 'undefined') for (var k in params) { if (typeof(params[k].id) !== 'undefined') hash += '-' + k + '_id' + params[k].id; else hash += '-' + k + '_' + params[k]; } if (typeof(this.stack[hash]) !== 'undefined') return this.stack[hash].view; else return false; }, clear: function() { this.stack = {}; this.inStackCount = 0; }, removeOldestIfNeeded: function() { var maxElements = App.settings.pagesStackMaxLength; if (this.inStackCount <= maxElements) return; var sort = []; for (var k in this.stack) sort.push({ hash: this.stack[k].hash, added: this.stack[k].added }); sort.sort(function(a, b) { return a.added - b.added; }); console.log("Removing " + sort[0].hash + " from pages stack"); delete this.stack[sort[0].hash]; this.inStackCount--; } }; ================================================ FILE: public/scripts/app/views/charts/balance.js ================================================ // balance.js App.Views.Charts.Balance = Backbone.View.extend({ events: {}, chart: false, aTransactions: [], _data: {}, dataReady: false, dataFetched: false, libReady: false, drawChart: function() { var that = this; $('#' + that.id).fadeOut(20, function() { $('#balance_canvas_container').show(); var options = { title: 'Expenses', curveType: 'function', legend: { position: 'none' }, width: that.containerWidth, height: that.containerHeight, chartArea: { left: 0, top: 0, width: that.containerWidth, height: '85%' }, colors: ['#a94442'], vAxis: { textPosition: 'in', viewWindow: { min: 0 } }, hAxis: { minValue: 0, baseline: 0, textStyle: { fontSize: 8 }, // ticks: [1, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30], slantedTextAngle: 30, maxAlternation: 1, slantedText: true } }; if (that._data.length > 1) { var chart = new google.visualization.LineChart(document.getElementById(that.id)); chart.draw(google.visualization.arrayToDataTable(that._data), options); } else { $('#balance_canvas_container').hide(); } $('#' + that.id).fadeIn(400); }); }, initialize: function() { if (!this.model || !this.id) console.error('views/charts/balance.js | model(wallet) and id of canvas should be provided for this view'); var that = this; google.load('visualization', '1.0', { 'packages': ['corechart'], 'callback': function() { /// visualization library loaded that.trigger('libReady'); that.libReady = true; } }); this.model.on('addTransaction', this.appendTransaction, this); this.model.on('removeTransaction', this.removeTransaction, this); this.on('dataReady', function() { console.log('views/charts/balance.js | dataReady'); if (that.libReady) that.drawChart(); else that.once('libReady', that.drawChart); }); }, resize: function() { if (typeof(this.__resizeThrottled) === 'undefined') { var that = this; this.__resizeThrottled = _.throttle(function() { if (that.libReady && that.dataReady) that.drawChart(); }, 100); } this.containerWidth = $('#balance_canvas').width(); this.containerHeight = $('#balance_canvas').height(); this.__resizeThrottled(); }, appendTransaction: function(transaction) { this.aTransactions.push(transaction); this.trigger('transactionsReady'); }, removeTransaction: function(transactionId) { this.aTransactions = _.filter(this.aTransactions, function(t) { return t.id != transactionId; }); this.trigger('transactionsReady'); }, getMissedTransactionsFromPage: function() { var isUpdated = false; }, fetchTransactions: function() { if (this.aTransactions.length) { this.trigger('transactionsReady'); return this.aTransactions; } var transactions = new App.Collections.Transactions(); this.aTransactions = []; transactions.setWalletId(this.model.id); var that = this; transactions.once('sync', function() { console.log('Synced current month'); transactions.forEach(function(t) { that.aTransactions.push(t); }); transactions.once('sync', function() { console.log('Synced prev month'); transactions.forEach(function(t) { that.aTransactions.push(t); }); that.trigger('transactionsReady'); }); transactions.gotoPrev(); }); transactions.fetch(); }, fetchData: function() { if (this.dataFetched) return false; if (this.dataReady) { this.trigger('dataReady'); return this._data; } this.dataFetched = true; var that = this; this.on('transactionsReady', function() { console.log('views/charts/balance.js | transactionsReady'); //// first step. Filter expenses var a = _.filter(this.aTransactions, function(t) { return t.get('amount') < 0; }); //// second step. For each day var days = {}; var curTime = new Date(); var curDay = curTime.getDate(); var curMonth = curTime.getMonth(); var curYear = curTime.getYear(); curTime = curTime.getTime(); var eachDayFunc = function(t) { var tDate = new Date(t.get('datetime') * 1000); if (tDate.getDate() === day && tDate.getMonth() === month) dayTotal += Math.abs(t.get('amount')); }; for (var i = 60; i >= 0; i--) { var d = new Date(curTime - 24 * 60 * 60 * 1000 * i); var day = d.getDate(); var month = d.getMonth(); var year = d.getYear(); var dayTotal = 0; _.each(a, eachDayFunc); days[day + '-' + month] = { day: day, month: month, year: year, total: Math.abs(dayTotal) }; } /// third step. Find first day from a set at which transaction occurs. var firstDay = 0; var firstMonth = 0; var firstYear = 0; _.each(days, function(day) { if (day.total > 0) { if (firstDay === 0 && firstMonth === 0) { firstDay = day.day; firstMonth = day.month; firstYear = day.year; } if ((day.month < firstMonth && day.year == firstYear) || (day.day < firstDay && day.month == firstMonth)) { firstDay = day.day; firstMonth = day.month; firstYear = day.year; } } }); /// forth step. Fill days without transactions by values from next days started from firstDay if (firstDay) _.each(days, function(d) { if (firstYear < d.year || (firstMonth < d.month && firstYear <= d.year) || (firstDay < d.day && firstMonth == d.month)) { if (d.total === 0 && typeof(d.filledMissed) === 'undefined') { var foundTotal = 0; var foundEmpty = []; var iDay = d.day + 1; var iMonth = d.month; var iYear = d.year; foundEmpty.push(d.day + '-' + d.month); while ((foundTotal === 0) && ((curMonth == iMonth && curDay >= iDay) || (curYear == iYear && curMonth > iMonth) || curYear > iYear)) if (typeof(days[iDay + '-' + iMonth]) !== 'undefined') { if (days[iDay + '-' + iMonth].total === 0) { /// another empty day foundEmpty.push(iDay + '-' + iMonth); } else { /// day with total set foundEmpty.push(iDay + '-' + iMonth); foundTotal = days[iDay + '-' + iMonth].total; } iDay++; } else { /// next month iMonth++; iDay = 1; if (iMonth == 12) { iMonth = 0; iYear++; } } //// fill missed sum foundEmpty = _.uniq(foundEmpty); if (foundEmpty.length > 0) { var total = foundTotal / foundEmpty.length; _.each(foundEmpty, function(found) { days[found].total = total; days[found].filledMissed = true; }); } } } }); /// fifth step. Filter days with total set and truncate to 30 max //days = _.filter(days, function(d){ return d.total > 0; }); //days = _.last(days, 30); /// generate labels //days.reverse(); var values = []; _.each(days, function(day, key) { values.push({ label: day.day + '/' + (day.month + 1), value: day.total }); }); //values.reverse(); values = _.last(values, 31); /// remove empty from the start var alreadyStarted = false; values = _.filter(values, function(item) { if (item.value > 0 || alreadyStarted) { alreadyStarted = true; return true; } else return false; }); /// group by // if (values.length > 10) { // var rvalues = []; // var i = 0; // if (values.length > 20) { // /// by 3 // while (typeof(values[i]) !== 'undefined') { // var rvalue = values[i].value; // if (typeof(values[i + 1]) !== 'undefined') rvalue += values[i + 1].value; // if (typeof(values[i + 2]) !== 'undefined') rvalue += values[i + 2].value; // if (typeof(values[i + 1]) !== 'undefined' && typeof(values[i + 2]) !== 'undefined') // rvalue = rvalue / 3; // else if (typeof(values[i + 1]) !== 'undefined') // rvalue = rvalue / 2; // var rlabel = values[i].label; // if (typeof(values[i + 2]) !== 'undefined') rlabel += ' -
' + values[i + 2].label; // else // if (typeof(values[i + 1]) !== 'undefined') rlabel += ' -
' + values[i + 1].label; // rvalues.push({ // label: rlabel, // value: rvalue // }); // i = i + 3; // } // } else { // /// by 2 // while (typeof(values[i]) !== 'undefined') { // var rvalue = values[i].value; // if (typeof(values[i + 1]) !== 'undefined') rvalue += values[i + 1].value; // if (typeof(values[i + 1]) !== 'undefined') // rvalue = rvalue / 2; // var rlabel = values[i].label; // if (typeof(values[i + 1]) !== 'undefined') rlabel += ' -
' + values[i + 1].label; // rvalues.push({ // label: rlabel, // value: rvalue // }); // i = i + 2; // } // } // values = rvalues; // } var labels = _.map(values, function(item) { return item.label; }); var series = [ [] ]; series[0] = _.map(values, function(item) { return item.value; }); that._data = []; that._data.push(['Date', 'Amount']); for (var k in values) that._data.push([values[k].label, +values[k].value.toFixed(2)]); that.dataFetched = false; that.dataReady = true; that.trigger('dataReady'); }); this.fetchTransactions(); }, wakeUp: function() { this.render(); }, sleep: function() { $(window).off('resize'); }, render: function() { console.log('Rendering chart'); if (!$('#' + this.id).length) return; var that = this; that.resize(); $(window).on('resize', function() { that.resize(); }); this.fetchData(); } }); ================================================ FILE: public/scripts/app/views/dialogs/add_profit.js ================================================ // add_profit.js App.Views.Dialogs.AddProfit = App.Views.Abstract.Dialog.extend({ dialogName: 'add_profit', events: { "submit form": "onSubmit" }, focusOnInit: '#input_amount', initialize: function(params) { this.wallet = params.wallet || false; this.show(); }, onSubmit: function() { var that = this; this.$('.btn-primary').button('loading'); var amount = this.$('#input_amount').val(); var description = this.$('#input_description').val(); amount = +amount; if (amount && amount > 0) { this.wallet.addProfit(amount, description); } this.hide(); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/add_wallet.js ================================================ // add_wallet.js App.Views.Dialogs.AddWallet = App.Views.Abstract.Dialog.extend({ dialogName: 'add_wallet', events: { "submit form": "onSubmit" }, focusOnInit: '#input_name', initialize: function() { this.show(); }, onSubmit: function() { var that = this; this.$('.btn-primary').button('loading'); var name = this.$('#input_name').val(); var currency = this.$('#input_currency').val(); var error = ''; if (!currency) error = 'Please select wallet currency'; if (error) { this.$('.errors-container').html(error); this.$('.errors-container').slideDown(); this.$('#input_currency').focus(); this.$('.btn-primary').button('reset'); var that = this; setTimeout(function() { that.$('.errors-container').slideUp(); }, 2000); } else { var item = new App.Models.Wallet(); item.set('name', name); item.set('currency', currency); item.set('total', 0); item.set('status', 'active'); if (typeof(App.page) !== 'undefined' && App.page && typeof(App.page.items) !== 'undefined' && App.page.items.model == App.Models.Wallet) { App.page.items.add(item); } item.save(); this.hide(); } return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/change_language.js ================================================ // change_language.js App.Views.Dialogs.ChangeLanguage = App.Views.Abstract.Dialog.extend({ dialogName: 'change_language', events: { "submit form": "onSubmit", "click .process_button": "doProcess" }, currentlyUpdating: false, initialize: function() { var that = this; this.on('ready', function() { }); this.show({ locales: App.settings.availiableLocales, current_locale: App.settings.language }); }, doProcess: function(ev) { if (this.currentlyUpdating) return false; var code = $(ev.currentTarget).data('code'); if (code == App.settings.language) this.hide(); else { // alert('set '+code); this.currentlyUpdating = true; var that = this; that.$('.process_button_container').fadeTo(0.1, 0.1); App.i18n.setLanguage(code, function() { that.currentlyUpdating = false; that.$('.process_button_container').fadeTo(1, 1); App.settings.language = code; that.hide(); }); } }, onSubmit: function() { this.hide(); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/edit_wallet.js ================================================ // edit_wallet.js App.Views.Dialogs.EditWallet = App.Views.Abstract.Dialog.extend({ dialogName: 'edit_wallet', events: { "submit form": "onSubmit" }, focusOnInit: '#input_name', initialize: function(params) { if (typeof(params.item) != 'undefined') this.item = params.item; else throw 'Can not initialize dialog without param.item'; this.show({ item: this.item.toJSON() }); }, onSubmit: function() { var that = this; this.$('.btn-primary').button('loading'); var name = this.$('#input_name').val(); var currency = this.$('#input_currency').val(); var error = ''; if (!currency) error = 'Please select wallet currency'; if (error) { this.$('.errors-container').html(error); this.$('.errors-container').slideDown(); this.$('#input_currency').focus(); this.$('.btn-primary').button('reset'); var that = this; setTimeout(function() { that.$('.errors-container').slideUp(); }, 2000); } else { this.item.set('name', name); this.item.set('currency', currency); this.item.save(); this.hide(); } return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/fill_profile.js ================================================ // fill_profile.js App.Views.Dialogs.FillProfile = App.Views.Abstract.Dialog.extend({ dialogName: 'fill_profile', events: { "submit form": "onSubmit" }, focusOnInit: '#input_login', initialize: function() { this.show(); }, onSubmit: function() { var that = this; this.$('.btn-primary').button('loading'); var login = this.$('#input_login').val(); var password = this.$('#input_password').val(); var email = this.$('#input_email').val(); this.listenTo(App.currentUser, 'invalid', function() { var html = ""; for (var k in App.currentUser.validationError) html += App.currentUser.validationError[k].msg + "
"; this.$('.errors-container').html(html); this.$('.errors-container').slideDown(); this.$('#input_login').focus(); /// @todo: focus to input with error this.$('.btn-primary').button('reset'); var that = this; setTimeout(function() { that.$('.errors-container').slideUp(); }, 2000); }); this.listenTo(App.currentUser, 'filled', function() { $('#fill_profile_invitation').slideUp(); this.$('.modal-body-default').slideUp(); this.$('.modal-body-success').slideDown(); setTimeout(function() { App.dialog.hide(); }, 2000); }); App.currentUser.fillProfile(login, email, password); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/hide_wallet.js ================================================ // hide_wallet.js App.Views.Dialogs.HideWallet = App.Views.Abstract.Dialog.extend({ dialogName: 'hide_wallet', events: { "submit form": "onSubmit", "click .process_button": "doProcess" }, initialize: function(params) { if (typeof(params.item) != 'undefined') this.item = params.item; else throw 'Can not initialize dialog without param.item'; this.show({ item: this.item.toJSON() }); }, doProcess: function() { this.$('.btn-danger').button('loading'); this.item.hide(); this.hide(); }, onSubmit: function() { this.hide(); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/logout.js ================================================ // logout.js App.Views.Dialogs.Logout = App.Views.Abstract.Dialog.extend({ dialogName: 'logout', // don't need template for this one, as we are not going to show it initialize: function() { App.currentUser.signOut(); App.viewStack.clear(); App.router.redirect('/'); $('#fill_profile_invitation').hide(); } }); ================================================ FILE: public/scripts/app/views/dialogs/registration.js ================================================ // registration.js App.Views.Dialogs.Registration = App.Views.Abstract.Dialog.extend({ dialogName: 'registration', events: { "submit form": "onSubmit" }, focusOnInit: '#input_login', initialize: function() { this.show(); }, onSubmit: function() { var that = this; this.$('.btn-primary').button('loading'); var login = this.$('#input_login').val(); var password = this.$('#input_password').val(); var email = this.$('#input_email').val(); App.currentUser.clear(); this.listenTo(App.currentUser, 'signedInStatusChanged', function() { App.userChanged(); this.hide(); }); this.listenTo(App.currentUser, 'registered', function() { this.$('.modal-body-default').slideUp(); this.$('.modal-body-success').slideDown(); }); this.listenTo(App.currentUser, 'invalid', function() { var html = ""; for (var k in App.currentUser.validationError) html += App.currentUser.validationError[k].msg + "
"; this.$('.errors-container').html(html); this.$('.errors-container').slideDown(); this.$('#input_login').focus(); /// @todo: focus to input with error this.$('.btn-primary').button('reset'); var that = this; setTimeout(function() { that.$('.errors-container').slideUp(); }, 2000); }); App.currentUser.register(login, email, password); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/remove_access.js ================================================ // remove_access.js App.Views.Dialogs.RemoveAccess = App.Views.Abstract.Dialog.extend({ dialogName: 'remove_access', events: { "submit form": "onSubmit", "click .process_button": "doProcess" }, initialize: function(params) { if (typeof(params.item) != 'undefined') this.item = params.item; else throw 'Can not initialize dialog without param.item'; if (typeof(params.access) != 'undefined') this.access = params.access; else throw 'Can not initialize dialog without param.access'; this.show({ item: this.item.toJSON(), access: this.access.toJSON() }); }, doProcess: function() { var that = this; this.$('.btn-danger').button('loading'); this.listenToOnce(this.access, 'sync error', function() { App.showDialog('WalletAccesses', { item: that.item }); }); this.access.destroy(); }, onSubmit: function() { App.showDialog('WalletAccesses', { item: this.item }); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/remove_plan.js ================================================ // remove_plan.js App.Views.Dialogs.RemovePlan = App.Views.Abstract.Dialog.extend({ dialogName: 'remove_plan', events: { "submit form": "onSubmit", "click .process_button": "doProcess" }, initialize: function(params) { if (typeof(params.item) != 'undefined') this.item = params.item; else throw 'Can not initialize dialog without param.item'; this.show({ item: this.item.toJSON() }); }, doProcess: function() { this.$('.btn-danger').button('loading'); App.localStorage.remove('plan_' + this.item.id + '_data'); this.item.destroy(); App.page.render(); this.hide(); return false; }, onSubmit: function() { this.hide(); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/remove_transaction.js ================================================ // remove_transaction.js App.Views.Dialogs.RemoveTransaction = App.Views.Abstract.Dialog.extend({ dialogName: 'remove_transaction', events: { "submit form": "onSubmit", "click .process_button": "doProcess" }, initialize: function(params) { if (typeof(params.item) != 'undefined') this.item = params.item; else throw 'Can not initialize dialog without param.item'; if (typeof(params.wallet) != 'undefined') this.wallet = params.wallet; else throw 'Can not initialize dialog without param.wallet'; this.show({ item: this.item.toJSON() }); }, doProcess: function() { var that = this; this.$('.btn-danger').button('loading'); App.page.model.removeTransaction(this.item); this.hide(); return false; // var that = this; // this.$('.btn-danger').button('loading'); // this.listenToOnce(this.item, 'sync error', function(){ // that.hide(); // if (typeof(App.page) !== 'undefined' && typeof(App.page.reloadWallet) === 'function') // App.page.reloadWallet(); // }); // this.item.destroy(); }, onSubmit: function() { App.showDialog('TransactionDetails', { item: this.item, wallet: this.wallet }); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/restore.js ================================================ // restore.js App.Views.Dialogs.Restore = App.Views.Abstract.Dialog.extend({ dialogName: 'restore', events: { "submit form": "onSubmit" }, focusOnInit: '#input_email', initialize: function() { this.show(); }, onSubmit: function() { var that = this; this.$('.btn-primary').button('loading'); var email = this.$('#input_email').val(); this.listenTo(App.currentUser, 'restore:error', function() { var html = ""; for (var k in App.currentUser.validationError) html += App.currentUser.validationError[k].msg + "
"; this.$('.errors-container').html(html); this.$('.errors-container').slideDown(); this.$('#input_email').focus(); /// @todo: focus to input with error this.$('.btn-primary').button('reset'); var that = this; setTimeout(function() { that.$('.errors-container').slideUp(); }, 2000); }); this.listenTo(App.currentUser, 'restore:success', function() { this.$('.modal-body-default').slideUp(); this.$('.modal-body-success').slideDown(); }); // App.currentUser.on("signedInStatusChanged", function(){ // App.userChanged(); // that.hide(); // }); App.currentUser.restorePassword(email); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/set_total_to.js ================================================ // set_total_to.js App.Views.Dialogs.SetTotalTo = App.Views.Abstract.Dialog.extend({ dialogName: 'set_total_to', events: { "submit form": "onSubmit" }, focusOnInit: '#input_total', initialize: function(params) { this.wallet = params.wallet || false; this.show(); }, onSubmit: function() { var that = this; this.$('.btn-primary').button('loading'); var total = this.$('#input_total').val(); //var description = this.$('#input_description').val(); if (Number(total) === parseFloat(total, 10)) { total = +total; this.wallet.setTotalTo(total); } this.hide(); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/signin.js ================================================ // signin.js App.Views.Dialogs.Signin = App.Views.Abstract.Dialog.extend({ dialogName: 'signin', events: { "submit form": "onSubmit" }, focusOnInit: '#input_username', initialize: function() { this.show(); }, onSubmit: function() { this.$('.btn-primary').button('loading'); var username = this.$('#input_username').val(); var password = this.$('#input_password').val(); App.currentUser.set('login', username); App.currentUser.set('password', password); this.listenTo(App.currentUser, 'signedin', function() { this.$('.btn-primary').button('reset'); this.hide(); }); this.listenTo(App.currentUser, 'invalid', function() { this.$('.btn-primary').button('reset'); this.$('.errors-container').slideDown(); this.$('#input_username').focus(); var that = this; setTimeout(function() { that.$('.errors-container').slideUp(); }, 2000); }); // App.currentUser.on('signedin', function(){ // }); // App.currentUser.on('invalid', function(){ // that.$('.btn-primary').button('reset'); // that.$('.errors-container').slideDown(); // that.$('#input_username').focus(); // setTimeout(function() { // that.$('.errors-container').slideUp(); // }, 2000); // }); App.currentUser.signIn(username, password); return false; }, onResponse: function(user) { var that = this; if (user.isSignedIn()) { this.$('#signin_modal_form_submit').button('reset'); this.hide(); } else { this.$('#signin_invalid_password_alert').slideDown(); this.$('#signin_modal_form_submit').button('reset'); this.$('#input_username').focus(); setTimeout(function() { that.$('#signin_invalid_password_alert').slideUp(); }, 1000); } } }); ================================================ FILE: public/scripts/app/views/dialogs/transaction_details.js ================================================ // transaction_details.js App.Views.Dialogs.TransactionDetails = App.Views.Abstract.Dialog.extend({ dialogName: 'transaction_details', events: { "submit form": "onSubmit", "click #remove_transaction_button": "removeTransaction" }, removeTransaction: function() { App.showDialog('RemoveTransaction', { item: this.item, wallet: this.wallet }); return false; }, initialize: function(params) { if (typeof(params.item) != 'undefined') this.item = params.item; else throw 'Can not initialize dialog without param.item'; if (typeof(params.wallet) != 'undefined') this.wallet = params.wallet; else throw 'Can not initialize dialog without param.wallet'; this.show({ item: this.item.toJSON(), wallet: this.wallet.toJSON() }); }, onSubmit: function() { var that = this; this.$('.btn-primary').button('loading'); this.hide(); return false; } }); ================================================ FILE: public/scripts/app/views/dialogs/wallet_accesses.js ================================================ // wallet_accesses.js App.Views.Dialogs.WalletAccesses = App.Views.Abstract.Dialog.extend({ status: 'loading', dialogName: 'wallet_accesses', events: { "submit form": "onSubmit", "click .item_button_remove_access": "removeAccess" }, removeAccess: function(ev) { var data = $(ev.currentTarget).data(); if (typeof(data.id) === 'undefined') return true; var id = parseInt(data.id, 10); var access = this.accesses.get(id); if (!access) return true; App.showDialog('RemoveAccess', { item: this.item, access: access }); return false; }, initialize: function(params) { if (typeof(params.item) != 'undefined') this.item = params.item; else throw 'Can not initialize dialog without param.item'; this.accesses = new App.Collections.WalletsAccesses(); this.accesses.setWalletId(this.item.id); this.listenTo(this.accesses, 'sync', this.loaded); this.accesses.fetch(); var that = this; this.on('ready', function() { that.$('#input_email').focus(); }); this.show(this.data()); }, data: function() { var ret_accesses = []; if (this.accesses && this.accesses.length) for (var i = 0; i < this.accesses.length; i++) { var acc = this.accesses.at(i).toJSON(); acc['gravatar'] = this.accesses.at(i).getGravatarURL(); ret_accesses.push(acc); } return { item: this.item.toJSON(), accesses: ret_accesses, status: this.status } }, loaded: function() { this.status = 'ready'; this.render(); }, render: function() { this.renderHTML(this.data()); }, onSubmit: function() { var that = this; var email = this.$('#input_email').val(); if (!email) return false; var already = this.accesses.where({ to_email: email }); if (already && already.length) { $("#emails_with_access_" + already[0].id).animate({ opacity: 0.5 }, 500).animate({ opacity: 1 }, 500); return false; } this.$('.btn-primary').button('loading'); var access = new App.Models.WalletsAccess(); access.set('to_email', email); access.set('wallet_id', this.item.id); access.save(); this.accesses.add(access); //this.item.set('name', name); //this.item.save(); //this.hide(); return false; } }); ================================================ FILE: public/scripts/app/views/header.js ================================================ // header.js App.Views.Header = Backbone.View.extend({ el: $("#header"), events: {}, render: function() { this.setElement($("#header")); if (App.currentUser.isSignedIn()) { console.log('header.js | Rendering for signed in user'); this.$('.header_is_not_signed_in').hide(); this.$('.header_is_signed_in').show(); } else { console.log('header.js | Rendering for not signed in user'); this.$('.header_is_not_signed_in').show(); this.$('.header_is_signed_in').hide(); } $(".menu_category").parent().removeClass('active'); if (typeof(App.page) !== 'undefined' && App.page && typeof(App.page.category) !== 'undefined') { $(".menu_category_" + App.page.category).parent().addClass('active'); } else { $(".menu_category_home").parent().addClass('active'); } console.log('header.js | Header rendered'); return this; } }); ================================================ FILE: public/scripts/app/views/pages/404.js ================================================ // 404.js App.Views.Pages.NotFound = App.Views.Abstract.Page.extend({ templateName: '404', title: 'Nothing is found. 404', render: function() { this.renderHTML(); }, initialize: function(params) { this.render(); } }); ================================================ FILE: public/scripts/app/views/pages/import_xls.js ================================================ // import_xls.js App.Views.Pages.ImportXLS = App.Views.Abstract.Page.extend({ templateName: 'pages/import/xls', additionalScripts: [ '/vendors/js-xlsx/dist/xlsx.min.js', '/vendors/moment/min/moment.min.js' ], category: 'wallets', events: { 'change #file_input': 'fileInputChanged', 'change .import_row_type': 'checkRowsToImport', 'click .select_file_button': 'selectFile', 'click #proccess_step1_button': 'goToPreview', 'click #proccess_step2_cancel': 'goToFirstStep', 'click #proccess_step2_button': 'goToImport' }, worksheet: null, sample: null, sampleWidth: null, sampleHeight: null, importPreview: null, step: 1, selectedFields: { date: false, time: false, description: false, amount: false, abs_amount: false }, selectedTimeFormat: false, selectedDateFormat: false, dateFormats: [ 'DD.MM.YYYY', 'MM.DD.YYYY', 'DD-MM-YYYY', 'MM-DD-YYYY', 'YYYY-MM-DD', 'YYYY-DD-MM', 'YYYY.MM.DD', 'YYYY.DD.MM' ], timeFormats: [ 'H:m', 'h:m a' ], title: function() { return 'Import'; }, selectFile: function() { this.$('#file_input').click(); }, goToFirstStep: function() { this.step = 1; this.render(); }, goToPreview: function() { this.step = 2; this.render(); }, goToImport: function() { this.step = 3; this.render(); this.import(); }, render: function() { this.renderHTML({ sample: this.sample, sampleHeight: this.sampleHeight, sampleWidth: this.sampleWidth, dateFormats: this.dateFormats, timeFormats: this.timeFormats, importPreview: this.importPreview, step: this.step, selectedFields: this.selectedFields, wallet_id: this.model.id }); }, wakeUp: function() { this.holderReady = false; this.render(); }, alreadyImportedRowN: 0, alreadyGotDataRowN: 0, rowToImportCount: 0, minImportedRowDate: null, maxImportedRowDate: null, rowsToImport: [], import: function() { this.alreadyImportedRowN = 0; this.rowsToImport = []; this.alreadyGotDataRowN = 0; this.rowToImportCount = this.worksheet['!range'].e.r; var that = this; setTimeout(function() { that.getNextRowData(); }, 100); }, getNextRowData: function() { var that = this; this.alreadyGotDataRowN++; var date = null; var description = null; var amount = null; /// date var date_format = this.selectedDateFormat; var time_format = this.selectedTimeFormat; if (this.selectedFields.date) { var txt_date = that.getValueForCell(this.selectedFields.date, this.alreadyGotDataRowN); if (this.selectedFields.time && this.selectedFields.time != this.selectedFields.date) txt_date += ' ' + that.getValueForCell(this.selectedFields.time, this.alreadyGotDataRowN); date_format += ' ' + time_format; var parsed = moment(txt_date, date_format); if (parsed.isValid()) { date = parsed.unix(); if (!this.minImportedRowDate || date < this.minImportedRowDate) this.minImportedRowDate = date; if (!this.maxImportedRowDate || date < this.maxImportedRowDate) this.maxImportedRowDate = date; } } /// description if (this.selectedFields.description) { var value = that.getValueForCell(this.selectedFields.description, this.alreadyGotDataRowN); value = value.replace(/<\/?[^>]+(>|$)/g, ""); value = value.substring(0, 250); if (value) description = value; } /// amount if (this.selectedFields.amount) { var value = that.getValueForCell(this.selectedFields.amount, this.alreadyGotDataRowN); value = parseFloat(value, 10); if (!isNaN(value)) amount = value; } if (this.selectedFields.abs_amount) { var value = that.getValueForCell(this.selectedFields.amount, this.alreadyGotDataRowN); value = Math.abs(parseFloat(value, 10)); if (!isNaN(value)) amount = -value; } if (amount !== null && date !== null) this.rowsToImport.push({ amount: amount, datetime: date, description: description }); var progress = Math.floor((this.alreadyGotDataRowN / this.rowToImportCount) * 100 / 2); this.$('#import_progress_bar').css('width', progress + '%'); if (this.alreadyGotDataRowN < this.rowToImportCount) { setTimeout(function() { that.getNextRowData(); }, 100); } else { this.rowToImportCount = this.rowsToImport.length; setTimeout(function() { that.getTransactionsToCheckForDuplicates(); }, 100); } }, trasactionsToCheckForDuplicates: [], getTransactionsToCheckForDuplicates: function() { var that = this; this.trasactionsToCheckForDuplicates = []; var minDate = new Date(this.minImportedRowDate * 1000); var maxDate = new Date(this.maxImportedRowDate * 1000); var minMonth = minDate.getMonth() + 1; var minYear = minDate.getFullYear(); var maxMonth = maxDate.getMonth() + 1; var maxYear = maxDate.getFullYear(); var curMonth = minMonth; var curYear = minYear; do { var transactions = new App.Collections.Transactions(); transactions.setPeriod(curMonth, curYear); transactions.setWalletId(this.model.id); this.trasactionsToCheckForDuplicates.push(transactions); if (curMonth == 12) { curMonth = 1; curYear++; } else { curMonth++; } } while ((curMonth <= maxMonth && curYear == maxYear) || curYear < maxYear); var promises = []; for (var k in this.trasactionsToCheckForDuplicates) promises.push(this.trasactionsToCheckForDuplicates[k].fetch()); $.when.apply($, promises).done(function() { that.importNextRow(); }); }, checkIfNoDuplicates: function(row) { for (var k in this.trasactionsToCheckForDuplicates) for (var i = 0; i < this.trasactionsToCheckForDuplicates[k].length; i++) { var transaction = this.trasactionsToCheckForDuplicates[k].models[i]; if (transaction.get('amount') == row.amount && transaction.get('datetime') == row.datetime && transaction.get('description') == row.description) return false; }; return true; }, importNextRow: function() { var that = this; var row = this.rowsToImport[this.alreadyImportedRowN]; this.alreadyImportedRowN++; var onNext = function() { var progress = 50 + Math.floor((that.alreadyImportedRowN / that.rowToImportCount) * 100 / 2); that.$('#import_progress_bar').css('width', progress + '%'); if (that.alreadyImportedRowN < that.rowToImportCount) { setTimeout(function() { that.importNextRow(); }, 100); } else { that.step = 4; that.render(); } } if (row && this.checkIfNoDuplicates(row)) { var transaction = new App.Models.Transaction(); transaction.set('amount', row.amount); transaction.set('description', row.description); transaction.set('datetime', row.datetime); transaction.set('wallet_id', this.model.id); transaction.save().then(function() { onNext(); }); } else { onNext(); } }, checkRowsToImport: function() { var x = 1; var y = 1; var height = this.worksheet['!range'].e.r; var badToImport = []; var that = this; var date_column_x = false; var time_column_x = false; var has_date = false; var has_amount = false; var importPreview = {}; $('.import_row_date_format').hide(); $('.import_row_time_format').hide(); $('.import_row_type').each(function() { var type = $(this).val(); if (type == 'date') $('#import_row_' + x + '_date_format').show(); if (type == 'time') $('#import_row_' + x + '_time_format').show(); for (y = 1; y < height; y++) { var value = that.getValueForCell(x, y); if (type == 'amount') { if (isNaN(parseFloat(value))) badToImport.push(y); else { if (typeof(importPreview[y]) == 'undefined') importPreview[y] = {}; importPreview[y]['amount'] = value; has_amount = true; that.selectedFields.amount = x; } } else if (type == 'abs_amount') { if (isNaN(parseFloat(value)) || value < 0) badToImport.push(y); else { if (typeof(importPreview[y]) == 'undefined') importPreview[y] = {}; importPreview[y]['amount'] = -parseFloat(value); has_amount = true; that.selectedFields.abs_amount = x; } } else if (type == 'description') { if (typeof(importPreview[y]) == 'undefined') importPreview[y] = {}; importPreview[y]['description'] = value; that.selectedFields.description = x; } else if (type == 'date') { date_column_x = x; that.selectedFields.date = x; that.selectedDateFormat = that.$('#import_row_' + x + '_date_format').val(); } else if (type == 'time') { time_column_x = x; that.selectedFields.time = x; that.selectedTimeFormat = that.$('#import_row_' + x + '_time_format').val(); } else if (type == 'datetime') { date_column_x = x; time_column_x = x; that.selectedFields.datetime = x; that.selectedDateFormat = that.$('#import_row_' + x + '_date_format').val(); that.selectedTimeFormat = that.$('#import_row_' + x + '_time_format').val(); } } x++; }); var date_format = this.selectedDateFormat; var time_format = this.selectedTimeFormat; if (date_column_x) for (y = 1; y < height; y++) { var date = that.getValueForCell(date_column_x, y); if (time_column_x && time_column_x != date_column_x) { date += ' ' + that.getValueForCell(time_column_x, y); date_format += ' ' + time_format; } var parsed = moment(date, date_format); if (!parsed.isValid()) badToImport.push(y); else { if (typeof(importPreview[y]) == 'undefined') importPreview[y] = {}; importPreview[y]['date'] = parsed.unix(); has_date = true; } } this.importPreview = null; for (var k in importPreview) { if (typeof(importPreview[k]['date']) != 'undefined' && typeof(importPreview[k]['amount']) != 'undefined') if (!this.importPreview || this.importPreview.length < 10) { if (!this.importPreview) this.importPreview = []; this.importPreview.push(importPreview[k]); } } $('.sample_import_row').addClass('info'); badToImport.forEach(function(y) { $('#sample_import_row_' + y).removeClass('info'); }); if (has_date && has_amount) { this.$('#proccess_step1_warning').hide(); this.$('#proccess_step1_button').prop('disabled', false); } else { this.$('#proccess_step1_warning').show(); this.$('#proccess_step1_button').prop('disabled', 'disabled'); } }, getValueForCell: function(x, y) { var cell = this.worksheet[String.fromCharCode(64 + x) + y]; if (typeof(cell) == 'undefined') return ''; else return cell.v; }, newData: function(workbook) { var first_sheet_name = workbook.SheetNames[0]; this.worksheet = workbook.Sheets[first_sheet_name]; var width = this.worksheet['!range'].e.c; var height = this.worksheet['!range'].e.r; var skip_line_from = 3; var skip_line_to = height - 4; var skiped_count = height - 6; var sample = []; for (var y = 1; y < height; y++) { if (height > 6 && y > skip_line_from && y < skip_line_to) { y = skip_line_to; sample.push({ skiped: skiped_count }); } else { var line = []; for (var x = 1; x <= width; x++) { var value = this.getValueForCell(x, y); line.push(value); } sample.push({ items: line, y: y }); } } this.sample = sample; this.sampleWidth = width; this.sampleHeight = height; this.render(); }, fileInputChanged: function(e) { this.$('.select_file_button').button('loading'); if (typeof(e.target.files) !== 'undefined' && e.target.files.length > 0) this.fileChanged(e.target.files[0]); }, fileChanged: function(file) { var reader = new FileReader(); var that = this; that.$('.alert', '#step_1').hide(); reader.onload = function(e) { var data = e.target.result; var workbook = null; try { workbook = XLSX.read(data, { type: 'binary' }); } catch (e) { that.$('.alert', '#step_1').show(); } if (workbook) that.newData(workbook); that.$('.select_file_button').button('reset'); } reader.readAsBinaryString(file); }, initialize: function(params) { this.renderLoading(); var that = this; App.helper.loadAdditionalScripts(this.additionalScripts, function() { if (typeof(params.wallet_id) !== 'undefined') { that.model = new App.Models.Wallet(); that.model.id = params.wallet_id; that.model.fetch({ success: function() { that.render(); }, error: function() { App.showPage('NotFound'); } }); } else throw 'wallet_id parameter required'; }); } }); ================================================ FILE: public/scripts/app/views/pages/index.js ================================================ // index.js App.Views.Pages.Index = App.Views.Abstract.Page.extend({ templateName: 'pages/index/index', category: 'home', events: { "click #demo_signup": "demoSignUp", "click #demo_without_mouse_signup": "demoSignUp" }, demoSignUp: function() { App.log.event('registration', 'Demo Sign Up', 'From Homepage'); this.renderLoading(); App.createCookie('show_tour_Wallets', 1); App.createCookie('show_tour_Wallet', 1); App.currentUser.demoRegister(); }, title: function() { return 'Homepage'; }, render: function() { this.renderHTML({}); }, wakeUp: function() { if (typeof(App.currentUser) !== 'undefined' && App.currentUser && App.currentUser.isSignedIn()) App.router.redirect('/wallets/'); else { this.holderReady = false; var that = this; this.on('render', function() { that.resize(); $(window).on('resize', that.resize); }); this.render(); } }, sleep: function() { $(window).off('resize'); }, resize: function() { if (typeof(App.page.__resizeThrottled) === 'undefined') { App.page.__resizeThrottled = _.throttle(function() { var footerOffset = $(window).height() - $('#footer').height() - 20; var rulerOffset = $('#screenshots_header_ruler').offset().top; if ($(window).width() >= 992 && footerOffset > rulerOffset + 190) { var margin = footerOffset - (rulerOffset + 190); $('#screenshots_header').css('margin-top', margin + 'px'); } else { $('#screenshots_header').css('margin-top', '20px'); } }, 100); } App.page.__resizeThrottled(); }, initialize: function() { var that = this; if (typeof(App.currentUser) !== 'undefined' && App.currentUser && App.currentUser.isSignedIn()) return App.router.redirect('/wallets/'); this.renderLoading(); /// initialize models, collections etc. Request fetching from storage this.listenTo(App.currentUser, 'signedInStatusChanged', function() { App.router.redirect('/wallets/'); }); this.on('render', function() { $('#demo_signup').clickonmouseover(); $('.image-link').magnificPopup({ type: 'image', gallery: { enabled: true }, callbacks: { open: function() { App.log.event('homepage', 'Zoom Screenshot'); } }, image: { titleSrc: function(item) { return $('#' + item.el.attr('id') + '-title').text() + '' + $('#' + item.el.attr('id') + '-description').text() + ''; } } }); that.resize(); $(window).on('resize', that.resize); if ('ontouchstart' in window || 'onmsgesturechange' in window) { //// touch device $('.register_without_mouse').fadeIn('slow'); } else { //// pc $('.register_with_mouse').fadeIn('slow'); } }); this.render(); } }); ================================================ FILE: public/scripts/app/views/pages/plan.js ================================================ // plan.js App.Views.Pages.Plan = App.Views.Abstract.Page.extend({ templateName: 'pages/plans/view', category: 'plan', events: { "click #reload_stats_button": 'reloadStats' }, title: function() { return 'Plan report'; }, url: function() { if (typeof(this.model) != 'undefined' && this.model.id) return 'plans/' + this.model.id; }, render: function() { console.log('views/pages/plan.js | rendering'); this.once('render', function() { }); this.renderHTML({ plan: this.model.toJSON(), stats: this.model.stats, currentTimestamp: (new Date().getTime() / 1000), adviceData: this.getAdviceData() }); }, reloadStats: function() { var that = this; this.$('#reload_stats_button').button('loading'); this.listenToOnce(this.model, 'statsready', function() { that.$('#reload_stats_button').button('reset'); }); this.model.reloadStats(); return false; }, getAdviceData: function() { var hasToday = false; var hasTomorrow = false; var hasFuture = false; var currentTimestamp = (new Date().getTime() / 1000); var todayI = null; var todaysPlan = 0; var todaysAlreadyTotal = 0; var todaysDif = 0; var tomorrowPlan = 0; var futureMaxPlan = 0; var futureEndDate = null; for (var i = 0; i < this.model.stats.length; i++) { if (this.model.stats[i].date.unix_from < currentTimestamp && this.model.stats[i].date.unix_to > currentTimestamp) { hasToday = true; todayI = i; if (i < this.model.stats.length - 1) { hasTomorrow = true; } if (i < this.model.stats.length - 2) { hasFuture = true; } } } if (hasToday) { todaysPlan = this.model.stats[todayI].allowedToSpend; todaysAlreadyTotal = this.model.stats[todayI].profitsTotal - this.model.stats[todayI].expensesTotal; if (hasTomorrow) { tomorrowPlan = this.model.stats[todayI+1].allowedToSpend; if (hasFuture) { futureMaxPlan = this.model.stats[this.model.stats.length - 1].allowedToSpend; futureEndDate = this.model.stats[this.model.stats.length - 1].date.unix; } } else { todaysDif = todaysPlan - todaysAlreadyTotal; } } return { hasToday: hasToday, hasTomorrow: hasTomorrow, hasFuture: hasFuture, todaysPlan: todaysPlan, todaysAlreadyTotal: todaysAlreadyTotal, todaysDif: todaysDif, tomorrowPlan: tomorrowPlan, futureMaxPlan: futureMaxPlan, futureEndDate: futureEndDate }; }, wakeUp: function() { console.log('views/pages/plan.js | waking up'); this.holderReady = false; var that = this; this.requireSingedIn(function() { var plan_id = that.model.id; that.model = new App.Models.Plan(); that.model.id = plan_id; that.model.fetch({ error: function() { App.showPage('NotFound'); } }).done(function() { App.exchange.loadRates(function() { that.listenTo(that.model, 'statsready', that.render); that.model.getStats(); }); }); }); }, initialize: function(params) { console.log('views/pages/plan.js | initializing'); this.renderLoading(); var that = this; this.requireSingedIn(function() { /// initialize models, collections etc. Request fetching from storage if (typeof(params.item) !== 'undefined') { that.model = params.item; that.render(); } else if (typeof(params.id) !== 'undefined') { that.model = new App.Models.Plan(); that.model.id = params.id; that.model.fetch({ error: function() { App.showPage('NotFound'); } }).done(function() { App.exchange.loadRates(function() { that.listenTo(that.model, 'statsready', that.render); that.model.getStats(); }); }); } else throw 'id or item parameters required'; }); } }); ================================================ FILE: public/scripts/app/views/pages/plans.js ================================================ // plans.js App.Views.Pages.Plans = App.Views.Abstract.Page.extend({ templateName: 'pages/plans/index', category: 'plans', additionalScripts: [ '/vendors/moment/min/moment.min.js', '/vendors/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js' ], events: { "click #button_create_new": "addNew", "click #button_step1_next": "step1Next", "click #button_step1_back": "step1Back", "click #button_step2_back": "step2Back", "click .step1_wallet_checkbox": "step1WalletChangeChecked", "click .edit_plan_button": "editPlan", "dp.change .datetimepicker": "dateChanged", "change #input_goal_balance": "goalBalanceChanged", "keyup #input_goal_balance": "goalBalanceChanged", "change #input_start_currency": "recalculateStartCurrency", "change #input_goal_currency": "recalculateGoalCurrency", "click #set_goal_to_start": "setGoalCurrencyToStart", "click #button_step2_save": "doSave", "click .remove_plan_button": "removePlan" }, title: function() { return 'Plan your expenses'; }, url: function() { return 'plans'; }, preparedData: {}, isNew: false, removePlan: function(ev) { var target = $(ev.currentTarget); var plan_id = target.data('id'); App.showDialog('RemovePlan', { item: this.plans.get(plan_id) }); return false; }, addNew: function() { this.step = 1; this.preparedData = { start_datetime: (Date.now() / 1000 | 0), goal_datetime: (Date.now() / 1000 | 0) + 24 * 60 * 60, start_balance: 0, goal_balance: 0, start_currency: null, goal_currency: null, name: 'Undefined' }; // this.preparedData['start_datetime'] = (Date.now() / 1000 | 0); // this.preparedData['goal_datetime'] = (Date.now() / 1000 | 0) + 24 * 60 * 60; // this.preparedData['start_balance'] = 0; // this.preparedData['goal_balance'] = 0; // this.preparedData['start_currency'] = null; // this.preparedData['goal_currency'] = null; // this.preparedData['name'] = 'Undefined'; this.isNew = true; this.render(); }, editPlan: function(ev) { var target = $(ev.currentTarget); var plan_id = target.data('id'); var plan = this.plans.get(plan_id); this.preparedData = { start_datetime: plan.get('start_datetime'), goal_datetime: plan.get('goal_datetime'), start_balance: plan.get('start_balance'), goal_balance: plan.get('goal_balance'), start_currency: plan.get('start_currency'), goal_currency: plan.get('goal_currency'), name: plan.get('name'), id: plan.id }; this.preparedData.wallets = []; var planWallets = plan.get('wallets'); for (var k in planWallets) this.preparedData.wallets.push(planWallets[k].id); this.isNew = false; this.step = 1; this.render(); }, doSave: function() { if (this.isNew) { this.preparedData['start_balance'] = App.exchange.convert(this.preparedData['start_balance'], this.preparedData['start_currency'], this.preparedData['goal_currency']); this.preparedData['start_currency'] = this.preparedData['goal_currency']; var plan = new App.Models.Plan(); plan.set('name', this.preparedData['name']); plan.set('start_datetime', this.preparedData['start_datetime']); plan.set('start_currency', this.preparedData['start_currency']); plan.set('start_balance', this.preparedData['start_balance']); plan.set('goal_datetime', this.preparedData['goal_datetime']); plan.set('goal_currency', this.preparedData['goal_currency']); plan.set('goal_balance', this.preparedData['goal_balance']); plan.set('wallets', this.preparedData['wallets']); this.listenToOnce(plan, 'sync', function() { App.router.redirect('plans/' + plan.id); }); plan.save(); this.plans.add(plan); } else { var plan = this.plans.get(this.preparedData['id']); plan.set('name', this.preparedData['name']); // plan.set('start_datetime', this.preparedData['start_datetime']); // plan.set('start_currency', this.preparedData['start_currency']); // plan.set('start_balance', this.preparedData['start_balance']); plan.set('goal_datetime', this.preparedData['goal_datetime']); plan.set('goal_currency', this.preparedData['goal_currency']); plan.set('goal_balance', this.preparedData['goal_balance']); plan.set('wallets', this.preparedData['wallets']); App.localStorage.remove('plan_' + plan.id + '_data'); this.listenToOnce(plan, 'sync', function() { App.router.redirect('plans/' + plan.id); }); plan.save(); } this.step = 0; }, dateChanged: function(ev) { this.preparedData['goal_datetime'] = ev.date.unix(); this.recalculatePreview(); }, goalBalanceChanged: function(ev) { var val = parseFloat($(ev.currentTarget).val(), 10); this.preparedData['goal_balance'] = val; this.recalculatePreview(); }, setGoalCurrencyToStart: function() { this.preparedData['goal_currency'] = this.preparedData['start_currency']; this.$('#input_goal_currency').val(this.preparedData['goal_currency']); this.recalculatePreview(); this.recalculateStartBalance(); }, recalculateGoalCurrency: function() { var newCurrency = this.$('#input_goal_currency').val(); this.preparedData['goal_currency'] = newCurrency; this.recalculatePreview(); this.recalculateStartBalance(); }, recalculateStartBalance: function() { var balance = this.preparedData['start_balance']; var decimal = App.templateManager.modifiers.decimal(balance); var rational = App.templateManager.modifiers.rational(balance); $('#cb_decimal').text(decimal); $('#cb_rational').text(rational); $('#cb_c_other').text(this.preparedData['start_currency']); if (balance < 0) $('#cb_minus').show(); else $('#cb_minus').hide(); if (this.preparedData['start_currency'] == 'USD') { $('#cb_c_other').hide(); $('#cb_c_dollar').show(); } else { $('#cb_c_other').show(); $('#cb_c_dollar').hide(); } if (this.preparedData['start_currency'] != this.preparedData['goal_currency']) { $('#set_goal_to_start').show(); $('#set_goal_to_start_c').text(this.preparedData['start_currency']); // @todo: currency name, not code var o_balance = App.exchange.convert(this.preparedData['start_balance'], this.preparedData['start_currency'], this.preparedData['goal_currency']); var o_decimal = App.templateManager.modifiers.decimal(o_balance); var o_rational = App.templateManager.modifiers.rational(o_balance); $('#cb_o_decimal').text(o_decimal); $('#cb_o_rational').text(o_rational); $('#cb_o_c_other').text(this.preparedData['goal_currency']); if (o_balance < 0) $('#cb_o_minus').show(); else $('#cb_o_minus').hide(); if (this.preparedData['goal_currency'] == 'USD') { $('#cb_o_c_other').hide(); $('#cb_o_c_dollar').show(); } else { $('#cb_o_c_other').show(); $('#cb_o_c_dollar').hide(); } $('#cb_o').show(); } else { $('#cb_o').hide(); $('#set_goal_to_start').hide(); } }, recalculatePreview: function() { var diff = this.preparedData['goal_balance'] - App.exchange.convert(this.preparedData['start_balance'], this.preparedData['start_currency'], this.preparedData['goal_currency']); var decimal = App.templateManager.modifiers.decimal(diff); var rational = App.templateManager.modifiers.rational(diff); $('#preview_diff_decimal').text(decimal); $('#preview_diff_rational').text(rational); if (diff < 0) { $('#preview_spend').show(); $('#preview_get').hide(); } else { $('#preview_spend').hide(); $('#preview_get').show(); } $('#preview_diff_c_other').text(this.preparedData['goal_currency']); if (this.preparedData['goal_currency'] == 'USD') { $('#preview_diff_c_other').hide(); $('#preview_diff_c_dollar').show(); } else { $('#preview_diff_c_other').show(); $('#preview_diff_c_dollar').hide(); } var days_diff = Math.ceil((this.preparedData['goal_datetime'] - this.preparedData['start_datetime']) / (24 * 60 * 60)); $('#preview_days_count').text(days_diff); if (days_diff <= 1) { $('#preview_one_day').show(); $('#preview_few_days').hide(); } else { $('#preview_one_day').hide(); $('#preview_few_days').show(); } var per_day_diff = diff / days_diff; var per_day_decimal = App.templateManager.modifiers.decimal(per_day_diff); var per_day_rational = App.templateManager.modifiers.rational(per_day_diff); $('#preview_d_diff_decimal').text(per_day_decimal); $('#preview_d_diff_rational').text(per_day_rational); if (per_day_diff < 0) $('#preview_d_diff_minus').show(); else $('#preview_d_diff_minus').hide(); $('#preview_d_diff_c_other').text(this.preparedData['goal_currency']); if (this.preparedData['goal_currency'] == 'USD') { $('#preview_d_diff_c_other').hide(); $('#preview_d_diff_c_dollar').show(); } else { $('#preview_d_diff_c_other').show(); $('#preview_d_diff_c_dollar').hide(); } }, recalculateStartCurrency: function() { var newCurrency = this.$('#input_start_currency').val(); this.preparedData['start_balance'] = App.exchange.convert(this.preparedData['start_balance'], this.preparedData['start_currency'], newCurrency); this.preparedData['start_currency'] = newCurrency; this.recalculateStartBalance(); }, step1WalletChangeChecked: function(ev) { var target = $(ev.currentTarget); var wallet_id = target.data('id'); var element = $('.step1_wallet_checkbox[data-id="' + wallet_id + '"]'); var isChecked = element.hasClass('active'); if (isChecked) { element.removeClass('active'); $('span', element).addClass('glyphicon-unchecked').removeClass('glyphicon-check'); if (!this.$('.step1_wallet_checkbox.active').length) $('#button_step1_next').prop('disabled', true); } else { element.addClass('active'); $('span', element).removeClass('glyphicon-unchecked').addClass('glyphicon-check'); $('#button_step1_next').prop('disabled', false); } return false; }, step1Next: function() { var that = this; this.preparedData['name'] = this.$('#input_name').val(); if (this.isNew) { var wallets = []; this.$('.step1_wallet_checkbox').each(function() { var wallet_id = $(this).data('id'); var isChecked = $(this).hasClass('active'); if (isChecked) wallets.push(wallet_id); }); this.preparedData['wallets'] = wallets; if (this.preparedData['start_currency'] == null || this.preparedData['goal_currency'] == null) { /// guess start_currency this.preparedData['start_currency'] = 'USD'; //default this.preparedData['goal_currency'] = 'USD'; //default var possibleCurrencies = {}; _.each(this.preparedData['wallets'], function(wallet_id) { var currency = that.wallets.get(wallet_id).get('currency'); possibleCurrencies[currency] = (possibleCurrencies[currency] || 0) + 1; }); var maxPossibleCurrency = null; var maxvalue = 0; _.each(possibleCurrencies, function(value, key) { if (maxPossibleCurrency == null || value > maxvalue) { maxvalue = value; maxPossibleCurrency = key; } }); if (maxPossibleCurrency) { this.preparedData['start_currency'] = maxPossibleCurrency; this.preparedData['goal_currency'] = maxPossibleCurrency; } } that.preparedData['start_balance'] = 0; _.each(this.preparedData['wallets'], function(wallet_id) { var currency = that.wallets.get(wallet_id).get('currency'); var balance = that.wallets.get(wallet_id).getTotal(); that.preparedData['start_balance'] += App.exchange.convert(balance, currency, that.preparedData['start_currency']); }); } this.step = 2; this.render(); }, step1Back: function() { this.step = 0; this.render(); }, step2Back: function() { this.step = 1; this.render(); }, step: 0, render: function() { var that = this; this.once('render', function() { if (that.step == 2) { var datetime = that.preparedData['goal_datetime']; that.$('.datetimepicker').datetimepicker({ inline: true, minDate: moment(), format: 'MM/dd/YYYY' }) that.$('.datetimepicker').data("DateTimePicker").date(moment(datetime * 1000)); that.recalculatePreview(); that.recalculateStartBalance(); } }); this.renderHTML({ plans: this.plans.toJSON(), wallets: this.wallets.toJSON(), step: this.step, preparedData: this.preparedData }); }, wakeUp: function() { this.holderReady = false; var that = this; this.requireSingedIn(function() { that.step = 0; that.render(); }); }, initialize: function() { console.log('plan.js | initialize'); this.renderLoading(); var that = this; this.requireSingedIn(function() { App.helper.loadAdditionalScripts(that.additionalScripts, function() { that.wallets = App.currentUser.getWallets(); that.plans = App.currentUser.getPlans(); var complete = _.invoke([that.wallets, that.plans], 'fetch'); $.when.apply($, complete).done(function() { App.exchange.loadRates(function() { that.render(); }); }); }); }); } }); ================================================ FILE: public/scripts/app/views/pages/profile.js ================================================ // profile.js App.Views.Pages.Profile = App.Views.Abstract.Page.extend({ templateName: 'pages/profile/index', category: 'user', events: { 'click .select_part': 'selectPart' }, title: function() { return 'User Profile'; }, url: function() { return 'profile'; }, selectPart: function(ev) { var target = $(ev.currentTarget).data('target'); this.$('#profile_' + target + '_container').show(); this.$('.profile_container').not("[id='profile_" + target + "_container']").hide(); $(ev.currentTarget).parents('ul').children('li').removeClass('active'); $(ev.currentTarget).parents('li').addClass('active'); }, initializeParts: function() { console.info('views/pages/profile.js | initializing parts'); this.parts = []; this.parts.push(new App.Views.Parts.ProfileChangePassword({ id: 'profile_change_password_container' })); this.parts.push(new App.Views.Parts.ProfileRemoveAccount({ id: 'profile_remove_account_container' })); this.partsInitialized = true; }, render: function() { console.log('views/pages/profile.js | Renedring user profile'); if (!this.partsInitialized) this.initializeParts(); this.once('render', function() { for (var k in this.parts) this.parts[k].render(); }); this.renderHTML({ user: App.currentUser }); }, wakeUp: function() { console.log('views/pages/profile.js | waking up'); this.holderReady = false; var that = this; this.requireSingedIn(function() { that.render(); }); }, initialize: function(params) { console.log('views/pages/profile.js | initializing'); this.renderLoading(); var that = this; this.requireSingedIn(function() { that.render(); }); } }); ================================================ FILE: public/scripts/app/views/pages/update_password.js ================================================ // update_password.js App.Views.Pages.UpdatePassword = App.Views.Abstract.Page.extend({ events: { "submit #update_password_form": "proccess", }, templateName: 'pages/user/update_password', category: 'user', title: function() { return 'Update Password'; }, proccess: function() { var password_restore_code = this.$('#password_restore_code').val(); var password_restore_hash = this.$('#password_restore_hash').val(); var newPassword = this.$('#new_password_input').val(); var repeatPassword = this.$('#new_password_repeat_input').val(); if (repeatPassword != newPassword) { this.showError(2); return false; } if (newPassword.length < 6) { this.showError(3); return false; } this.$('.btn-primary').button('loading'); this.listenTo(App.currentUser, 'newpassword:error', function() { this.showError(1); }); this.listenTo(App.currentUser, 'newpassword:success', function() { this.$('.alert-danger').hide(); this.$('form').hide(); this.$('.alert-info').show(); }); App.currentUser.newPassword(password_restore_code, password_restore_hash, newPassword); return false; }, showError: function(errorNo) { this.$('.btn-primary').button('reset'); this.$('span', '.alert-danger').hide(); this.$('.errorNo' + errorNo, '.alert-danger').show(); if (this.$('.errorNo' + errorNo, '.alert-danger') && typeof(this.$('.errorNo' + errorNo, '.alert-danger').data('input')) !== 'undefined') { /// highlight input described as data-input="new_password_repeat_input" in span var formGroup = this.$('#' + this.$('.errorNo' + errorNo, '.alert-danger').data('input')).closest('.form-group'); if (formGroup) { formGroup.addClass('has-error'); setTimeout(function() { formGroup.removeClass('has-error'); }, 3000); this.$('#' + this.$('.errorNo' + errorNo, '.alert-danger').data('input')).focus(); } } this.$('.alert-danger').stop(true, true).slideDown('fast'); var that = this; setTimeout(function() { that.$('.alert-danger').slideUp('slow'); }, 3000); }, render: function() { var that = this; this.once('render', function() { that.$('#new_password_input').focus(); }); this.renderHTML({ password_restore_code: this.password_restore_code, password_restore_hash: this.password_restore_hash }); }, initialize: function(params) { if (typeof(params.password_restore_code) !== 'undefined') { this.password_restore_code = '' + params.password_restore_code; this.password_restore_hash = '' + params.password_restore_hash; } else throw 'password_restore_code and password_restore_hash parameters required'; this.render(); } }); ================================================ FILE: public/scripts/app/views/pages/wallet.js ================================================ // wallet.js App.Views.Pages.Wallet = App.Views.Abstract.Page.extend({ templateName: 'pages/wallets/view', category: 'wallets', events: { "submit #add_transaction_form": "addExpense", "click #add_profit_button": "addProfit", "click #set_total_to_button": "setTotalTo" }, title: function() { if (typeof(this.model) != 'undefined' && this.model.get('name')) return this.model.get('name'); else return 'Wallet'; }, url: function() { if (typeof(this.model) != 'undefined' && this.model.id) return 'wallets/' + this.model.id; }, setTotalTo: function() { App.showDialog('SetTotalTo', { wallet: this.model }); return false; }, addProfit: function() { App.showDialog('AddProfit', { wallet: this.model }); return false; }, addExpense: function() { var description = $("#add_transaction_text").val(); var amount = $("#add_transaction_amount").val(); // could be empty if we are getting amount from description (1st try). console.log('Add transaction with description: ' + description); var numbers = description.split(",").join(".").match(/[0-9.]+/g); var fromDescriptionAmount = false; if (typeof(numbers) !== 'undefined' && numbers && typeof(numbers[0]) !== 'undefined' && numbers[0]) { fromDescriptionAmount = +numbers[0]; } if (fromDescriptionAmount) { this.model.addExpense(fromDescriptionAmount, description); this.$('#add_transaction_amount').hide(); $("#add_transaction_text").val('').blur(); } else { amount = amount.split(',').join('.'); amount = +amount; if (amount > 0) { this.model.addExpense(amount, description); this.$('#add_transaction_amount').hide(); this.$("#add_transaction_text").val('').blur(); } else { this.$('#add_transaction_amount').show(); this.$('#add_transaction_amount').focus(); } } return false; }, render: function() { console.log('views/pages/wallet.js | rendering'); if (!this.partsInitialized) this.initializeParts(); //// slide down invitation box if total is changed. if (App.currentUser.isDemo()) { if (typeof(this.initialWalletTotal) !== 'undefined') { if (!$('#fill_profile_invitation').is(":visible")) if (this.model.get('total') != this.initialWalletTotal) $('#fill_profile_invitation').slideDown('slow'); } else { this.initialWalletTotal = this.model.get('total'); } } this.once('render', function() { for (var k in this.parts) this.parts[k].render(); for (var k in this.charts) this.charts[k].render(); // Instance the tour if (typeof(App.Tours.Wallet) !== 'undefined') App.Tours.Wallet.init(this); }); this.renderHTML({ item: this.model.toJSON() }); }, initializeParts: function() { console.info('views/pages/wallet.js | initializing parts'); this.parts = []; this.parts.push(new App.Views.Parts.Transactions({ id: 'transactions_container', model: this.model, collection: this.model.getTransactions() })); this.parts.push(new App.Views.Parts.WalletPlans({ id: 'plans_container', model: this.model })); this.partsInitialized = true; this.charts = []; this.charts.push(new App.Views.Charts.Balance({ id: 'balance_canvas', model: this.model })); }, wakeUp: function() { console.log('views/pages/wallet.js | waking up'); this.holderReady = false; var that = this; this.requireSingedIn(function() { that.render(); that.listenTo(that.model, 'change sync destroy', that.render); for (var k in that.parts) if (typeof(that.parts[k].wakeUp) === 'function') that.parts[k].wakeUp(); }); }, reloadWallet: function() { var wallet_id = this.model.id; var that = this; this.requireSingedIn(function() { var transactions = that.model.getTransactions(); that.model = new App.Models.Wallet(); that.model.id = wallet_id; that.model.transactions = transactions; that.model.transactions.fetch(); that.listenTo(that.model, 'change sync destroy', that.render); that.model.fetch({ error: function() { App.showPage('NotFound'); } }); }); }, initialize: function(params) { console.log('views/pages/wallet.js | initializing'); this.renderLoading(); var that = this; this.requireSingedIn(function() { /// initialize models, collections etc. Request fetching from storage if (typeof(params.item) !== 'undefined') { that.model = params.item; that.render(); that.listenTo(that.model, 'change sync destroy', that.render); } else if (typeof(params.id) !== 'undefined') { that.model = new App.Models.Wallet(); that.model.id = params.id; that.listenTo(that.model, 'change sync destroy', that.render); that.model.fetch({ error: function() { App.showPage('NotFound'); } }); } else throw 'id or item parameters required'; }); } }); ================================================ FILE: public/scripts/app/views/pages/wallets.js ================================================ // wallets.js App.Views.Pages.Wallets = App.Views.Abstract.Page.extend({ templateName: 'pages/wallets/index', category: 'wallets', status: 'active', origin: 'both', events: { "mouseenter .item": "moreWalletDetails", "mouseleave .item": "lessWalletDetails", "click .item_button_remove": "removeItem", "click .item": "toItem", "click .item_button_edit": "editItem", "click .item_button_restore": "restoreItem", "click .item_button_accesses": "showAccesses", "click .filter_menu": "filter", "click .origin_menu": "filterOrigin" }, title: function() { return 'Wallets'; }, url: function() { return 'wallets'; }, filter: function(ev) { var status = $(ev.currentTarget).data('status'); if ((status == 'active' || status == 'hidden') && status != this.status) { this.status = status; this.render(); } return false; }, filterOrigin: function(ev) { var origin = $(ev.currentTarget).data('origin'); if ((origin == 'both' || origin == 'mine' || origin == 'shared') && origin != this.origin) { this.origin = origin; this.render(); } return false; }, toItem: function(ev) { var data = $(ev.currentTarget).data(); if (typeof(data.id) === 'undefined') return true; var id = parseInt(data.id, 10); var item = this.items.get(id); if (!item) return true; App.showPage('Wallet', { item: item }); return false; }, moreWalletDetails: function(ev) { $(ev.currentTarget).find(".item_buttons").show(); //$(ev.currentTarget).find(".item_information").hide(); }, lessWalletDetails: function(ev) { $(ev.currentTarget).find(".item_buttons").hide(); //$(ev.currentTarget).find(".item_information").show(); }, removeItem: function(ev) { var id = $(ev.currentTarget).parents('.item').data('id'); App.showDialog('HideWallet', { item: this.items.get(id) }); return false; }, restoreItem: function(ev) { var id = $(ev.currentTarget).parents('.item').data('id'); var item = this.items.get(id); if (item && item.get('status') == 'hidden') { item.set('status', 'active'); item.save(); } return false; }, showAccesses: function(ev) { var id = $(ev.currentTarget).parents('.item').data('id'); App.showDialog('WalletAccesses', { item: this.items.get(id) }); return false; }, editItem: function(ev) { var id = $(ev.currentTarget).parents('.item').data('id'); App.showDialog('EditWallet', { item: this.items.get(id) }); return false; }, render: function() { if (this.origin == 'both') var filtered = this.items.search({ status: this.status }); else var filtered = this.items.search({ status: this.status, origin: this.origin }); this.once('render', function() { // Instance the tour if (typeof(App.Tours.Wallets) !== 'undefined') App.Tours.Wallets.init(this); }); this.renderHTML({ items: filtered.toJSON(), status: this.status, origin: this.origin }); }, wakeUp: function() { this.holderReady = false; var that = this; this.requireSingedIn(function() { that.render(); that.listenTo(that.items, 'sync add change reset remove', that.render); }); }, initialize: function() { console.log('wallets.js | initialize'); this.renderLoading(); var that = this; this.requireSingedIn(function() { that.items = App.currentUser.getWallets(); /// initialize models, collections etc. Request fetching from storage that.listenTo(that.items, 'sync', that.render); that.items.fetch().done(function() { that.listenTo(that.items, 'add change reset remove', that.render); }).error(function() { that.render(); }); }); } }); ================================================ FILE: public/scripts/app/views/parts/profile_change_password.js ================================================ // profile_change_password.js App.Views.Parts.ProfileChangePassword = Backbone.View.extend({ events: { "submit #change_password_form": "proccess", }, proccess: function() { var currentPassword = this.$('#current_password_input').val(); var newPassword = this.$('#new_password_input').val(); var repeatPassword = this.$('#new_password_repeat_input').val(); if (repeatPassword != newPassword) { this.showError(2); return false; } if (newPassword.length < 6) { this.showError(3); return false; } this.$('.btn-primary').button('loading'); this.listenTo(App.currentUser, 'invalid', function() { this.showError(1); }); this.listenTo(App.currentUser, 'changed', function() { this.$('.alert-danger').hide(); this.$('form').hide(); this.$('.alert-info').show(); }); App.currentUser.changePassword(currentPassword, newPassword); return false; }, showError: function(errorNo) { this.$('.btn-primary').button('reset'); this.$('span', '.alert-danger').hide(); this.$('.errorNo' + errorNo, '.alert-danger').show(); if (this.$('.errorNo' + errorNo, '.alert-danger') && typeof(this.$('.errorNo' + errorNo, '.alert-danger').data('input')) !== 'undefined') { /// highlight input described as data-input="new_password_repeat_input" in span var formGroup = this.$('#' + this.$('.errorNo' + errorNo, '.alert-danger').data('input')).closest('.form-group'); if (formGroup) { formGroup.addClass('has-error'); setTimeout(function() { formGroup.removeClass('has-error'); }, 3000); this.$('#' + this.$('.errorNo' + errorNo, '.alert-danger').data('input')).focus(); } } this.$('.alert-danger').stop(true, true).slideDown('fast'); var that = this; setTimeout(function() { that.$('.alert-danger').slideUp('slow'); }, 3000); }, initialize: function() { console.log('views/parts/profile_change_password.js | Initializing view'); }, wakeUp: function() { console.error('views/parts/profile_change_password.js | Waking up'); }, render: function() { console.log('views/parts/profile_change_password.js | Rendering'); this.setElement($('#' + this.id)); } }); ================================================ FILE: public/scripts/app/views/parts/profile_remove_account.js ================================================ // profile_remove_account.js App.Views.Parts.ProfileRemoveAccount = Backbone.View.extend({ events: { "submit #remove_account_step_1_form": "proccess1", "submit #remove_account_step_2_form": "proccess2" }, proccess1: function() { this.$('#remove_account_step_1_submit').button('loading'); this.listenTo(App.currentUser, 'removeaccountstart', function() { this.$('#profile_remove_account_step_1').hide(); this.$('#profile_remove_account_step_2').show(); }); App.currentUser.removeAccount(); return false; }, showWrongCodeMessage: function() { var that = this; that.$('#invalid_remove_account_code').slideDown('fast'); setTimeout(function() { that.$('#invalid_remove_account_code').slideUp(); }, 2000); }, proccess2: function() { var code = this.$('#remove_account_code').val(); if (!code) { this.showWrongCodeMessage(); return; } this.$('#remove_account_step_2_submit').button('loading'); this.listenTo(App.currentUser, 'removeaccountdone', function() { this.$('#profile_remove_account_done').show(); setTimeout(function() { App.currentUser.signOut(); }, 1000); }); this.listenTo(App.currentUser, 'removeaccountwrongcode', function() { this.showWrongCodeMessage(); this.$('#remove_account_step_2_submit').button('reset'); }); App.currentUser.removeAccountConfirm(code); return false; }, initialize: function() { console.log('views/parts/profile_remove_account.js | Initializing view'); }, wakeUp: function() { console.error('views/parts/profile_remove_account.js | Waking up'); }, render: function() { console.log('views/parts/profile_remove_account.js | Rendering'); this.setElement($('#' + this.id)); } }); ================================================ FILE: public/scripts/app/views/parts/transactions.js ================================================ // transactions.js App.Views.Parts.Transactions = Backbone.View.extend({ templateName: 'parts/transactions', el: $("#comments_container"), events: { "click .item": "transactionDetails", "click #goto_next": "gotoNext", "click #goto_prev": "gotoPrev", "click #goto_current": "gotoCurrent" }, gotoNext: function() { this.collection.gotoNext(); }, gotoPrev: function() { this.collection.gotoPrev(); }, gotoCurrent: function() { this.collection.gotoCurrent(); }, transactionDetails: function(ev) { console.log('views/parts/transactions.js | Show transactions details'); var data = $(ev.currentTarget).data(); if (typeof(data.id) === 'undefined') return true; var id = parseInt(data.id, 10); var item = this.collection.get(id); if (!item) return true; App.showDialog('TransactionDetails', { item: item, wallet: this.model }); return false; }, initialize: function() { console.log('views/parts/transactions.js | Initializing Transactions view'); if (!this.model || !this.collection) console.error('views/parts/transactions.js | model && collection && id should be provided for this view'); this.listenTo(this.collection, 'sync', this.render); this.listenTo(this.collection, 'changedperiod', this.fadeOut); }, wakeUp: function() { console.error('views/parts/transactions.js | Waking up'); this.listenTo(this.collection, 'sync', this.render); this.listenTo(this.collection, 'changedperiod', this.fadeOut); }, fadeOut: function() { this.$('#transactions_container').fadeTo(1, 0.5); }, render: function() { console.log('views/parts/transactions.js | Rendering, state = ' + this.collection.state); this.setElement($('#' + this.id)); this.$('#transactions_container').fadeTo(1, 1); var data = { state: this.collection.state, collection: this.collection, transactions: this.collection.sort().toJSON(), item: this.model.toJSON() }; var that = this; App.templateManager.fetch(this.templateName, data, function(html) { that.$el.html(html); that.trigger('render'); that.trigger('loaded'); }); } }); ================================================ FILE: public/scripts/app/views/parts/wallet_plans.js ================================================ // wallet_plans.js App.Views.Parts.WalletPlans = Backbone.View.extend({ templateName: 'parts/wallet_plans', events: {}, areStatsReady: false, initialize: function() { console.log('views/parts/wallet_plans.js | Initializing Wallet Plans view'); if (!this.model || !this.id) console.error('views/parts/wallet_plans.js | model and dom id should be provided for this view'); this.areStatsReady = false; var that = this; App.exchange.loadRates(function() { that.listenToOnce(that.model, 'plansloaded', function() { that.invokeStatsLoading(); }); that.listenTo(that.model, 'plansloaded', that.render); that.model.getPlans(); }); }, wakeUp: function() { console.error('views/parts/wallet_plans.js | Waking up'); }, invokeStatsLoading: function() { var that = this; var complete = _.invoke(this.model.plans.models, 'getStats'); $.when.apply($, complete).done(function() { that.areStatsReady = true; that.render(); }); }, render: function() { console.log('views/parts/wallet_plans.js | Rendering'); this.setElement($('#' + this.id)); var plans = []; if (this.model.plans) for (var i = 0; i < this.model.plans.length; i++) { var allowedToSpend = null; var allowedToSpendInWalletCurrency = null; if (this.areStatsReady) { allowedToSpend = this.model.plans.at(i).getPlanForToday(); allowedToSpendInWalletCurrency = App.exchange.convert(allowedToSpend, this.model.plans.at(i).get('goal_currency'), this.model.get('currency')); console.log(allowedToSpendInWalletCurrency); } plans.push({ plan: this.model.plans.at(i).toJSON(), allowedToSpend: allowedToSpend, allowedToSpendInWalletCurrency: allowedToSpendInWalletCurrency }); } var data = { wallet: this.model.toJSON(), plans: plans, areStatsReady: this.areStatsReady }; var that = this; App.templateManager.fetch(this.templateName, data, function(html) { that.$el.html(html); that.$('[data-toggle="tooltip"]').tooltip(); that.trigger('render'); that.trigger('loaded'); }); } }); ================================================ FILE: public/scripts/app/views/tours/wallet.js ================================================ // wallet.js App.Tours.Wallet = { tour: null, page: null, finish: function() { App.eraseCookie('show_tour_Wallet'); this.tour.end(); }, init: function(page) { if (!App.readCookie('show_tour_Wallet')) return false; var that = this; App.currentTour = this; var nextFunction = function() { var step = that.tour.getCurrentStep() + 1; that.tour.restart(); that.tour.goTo(step); } this.page = page; this.tour = new Tour({ onEnd: function(tour) { App.eraseCookie('show_tour_Wallet'); }, steps: [{ element: "#add_profit_button", title: "Step 1 of 6", content: $('#tour_step_0').html(), reflex: true, placement: 'auto', onNext: function(tour) { that.tour.end(); setTimeout(function() { if (App.dialog && App.dialog.isVisible) that.page.listenToOnce(App.dialog, 'hidden', nextFunction); else nextFunction(); }, 50); } /// onNext }, { element: "#set_total_to_button", placement: 'auto', reflex: true, title: "Step 2 of 6", content: $('#tour_step_1').html(), onNext: function(tour) { that.tour.end(); setTimeout(function() { if (App.dialog && App.dialog.isVisible) that.page.listenToOnce(App.dialog, 'hidden', nextFunction); else nextFunction(); }, 50); } //// onNext }, { element: "#add_transaction_form", placement: 'auto', reflex: false, title: "Step 3 of 6", content: $('#tour_step_2').html(), onShown: function(tour) { var nextStep = tour.getCurrentStep() + 1; that.page.listenToOnce(that.page.model, 'addExpense', function() { that.tour.goTo(nextStep); }); } //// onShown }, { element: "#transactions_container", placement: 'auto', reflex: true, title: "Step 4 of 6", content: $('#tour_step_3').html(), onShown: function() { }, onNext: function(tour) { that.tour.end(); setTimeout(function() { if (App.dialog && App.dialog.isVisible) that.page.listenToOnce(App.dialog, 'hidden', nextFunction); else nextFunction(); }, 50); } //// onNext }, { element: "#balance_canvas", placement: 'auto', reflex: true, title: "Step 5 of 6", content: $('#tour_step_4').html(), onNext: function() { $("#fill_profile_invitation").show(); } }, { element: "#fill_profile_invitation", placement: 'auto', reflex: true, title: "Step 6 of 6", content: $('#tour_step_5').html(), onNext: function() { App.currentTour.finish(); } }] }); // Initialize the tour that.tour.init(); // Start the tour that.tour.start(true); that.tour.goTo(0); } } ================================================ FILE: public/scripts/app/views/tours/wallets.js ================================================ // wallets.js App.Tours.Wallets = { tour: null, page: null, finish: function() { App.eraseCookie('show_tour_Wallets'); this.tour.end(); }, init: function(page) { if (!App.readCookie('show_tour_Wallets')) return false; var that = this; App.currentTour = this; var nextFunction = function() { var step = that.tour.getCurrentStep() + 1; that.tour.restart(); that.tour.goTo(step); } this.page = page; this.tour = new Tour({ onEnd: function(tour) { App.eraseCookie('show_tour_Wallets'); }, steps: [{ element: "#wallet_items", title: "Step 1 of 3", content: $('#tour_step_0').html(), reflex: false, placement: 'auto' }, { element: "#add_wallet_button", placement: 'auto', reflex: true, title: "Step 2 of 3", content: $('#tour_step_1').html(), onNext: function(tour) { that.tour.end(); setTimeout(function() { if (App.dialog && App.dialog.isVisible) that.page.listenToOnce(App.dialog, 'hidden', nextFunction); else nextFunction(); }, 50); } //// onNext }, { element: "#wallet_items", placement: 'auto', reflex: false, title: "Step 3 of 3", content: $('#tour_step_2').html(), onNext: function(tour) { that.tour.end(); setTimeout(function() { if (App.dialog && App.dialog.isVisible) that.page.listenToOnce(App.dialog, 'hidden', nextFunction); else nextFunction(); }, 50); } //// onNext }] }); // Initialize the tour that.tour.init(); // Start the tour that.tour.start(true); that.tour.goTo(0); } } ================================================ FILE: public/scripts/app/views/widgets/index.js ================================================ ================================================ FILE: public/scripts/app.js ================================================ // app.js window.App = { Models: {}, Collections: {}, Views: { Abstract: {}, Dialogs: {}, Pages: {}, Widgets: {}, Parts: {}, Charts: {} }, Tours: {}, currentTour: null, router: null, dialog: null, page: null, header: null, footer: null, settings: null, currentUser: null, init: function() { var that = this; $.ajaxSetup({ cache: false }); var doneCallback = function() { that.localStorage.invalidate(that.settings.version); that.i18n.setLanguage(that.settings.detectLanguage()); that.router.init(); that.loadingStatus(false); }; if (document.cookie.indexOf("is_logged_in_user") >= 0) { $.get(this.settings.apiEntryPoint + 'users', function(user) { if (user) that.setUser(user); else that.setUser(); }, 'json') .fail(function() { that.setUser(); }).always(function() { doneCallback(); }); } else { that.setUser(); doneCallback(); } }, showDialog: function(dialogName, params) { if (typeof(App.Views.Dialogs[dialogName]) === 'undefined') /// this page is already current return false; if (App.dialog && App.dialog.isVisible) { App.dialog.once('hidden', function() { console.log('Ready to show another dialog'); App.dialog = new App.Views.Dialogs[dialogName](params); }, this); App.dialog.hide(); } else { App.dialog = new App.Views.Dialogs[dialogName](params); App.log.event('dialog', 'Show Dialog ' + dialogName); } return true; }, showPage: function(pageName, params) { console.log('Showing page: ' + pageName); if (App.currentTour) App.currentTour.finish(); if (typeof(params) === 'undefined') params = {}; if (typeof(App.Views.Pages[pageName]) === 'undefined') { console.error("There is no view class defined"); return false; } if (typeof(this.page) !== 'undefined' && this.page) /// undelegate events from previous page { this.page.sleep(); } /// Trying to get view from stack var fromStack = this.viewStack.getView(pageName, params); if (fromStack !== false) { /// Console log wake up page from stack console.log('Showing page from stack'); this.page = fromStack; this.page.wakeUp(); this.loadingStatus(false); } else { /// or create new one this.loadingStatus(true); this.page = new App.Views.Pages[pageName](params); this.page.on('loaded', function() { this.loadingStatus(false); }, this); if (this.page.isReady) this.loadingStatus(false); // this.listenTo(this.page, 'loaded', function(){ this.loadingStatus(false); }); // this.listenTo(this.page, 'loading', function(){ this.loadingStatus(true); }); this.viewStack.addView(pageName, params, this.page); } this.renderLayoutBlocks(); return true; }, setProgress: function(value) { if (!this.progress) this.progress = new Mprogress(); if (typeof(value) === 'undefined') { if (this.progress.status === null) return this.progress.start(); else return this.progress.inc(); } if (value >= 1 || value === true) return this.progress.end(); this.progress.set(value); }, loadingStatus: function(status) { if (status) { console.log('app.js | Loading status = true'); this.isLoading = true; $('#preloader').stop().show(); } else { console.log('app.js | Loading status = false'); this.isLoading = false; $('#preloader').stop().fadeOut('slow'); } }, setUser: function(data) { this.currentUser = new App.Models.User(); this.currentUser.on('signedInStatusChanged', this.userChanged, this); if (typeof(data) !== 'undefined') this.currentUser.signInWithData(data); }, userChanged: function() { console.log('User info changed'); // You can also refresh the page here if you want to. this.renderLayoutBlocks(); }, renderLayoutBlocks: function() { var that = this; if (!this.header) { this.header = new App.Views.Header(); } var renderFunc = function() { that.header.render(); }; if ($.isReady) { renderFunc(); } else { $(function() { renderFunc(); }); } }, createCookie: function(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/"; }, readCookie: function(name) { var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); } return null; }, eraseCookie: function(name) { App.createCookie(name, "", -1); } }; ================================================ FILE: public/scripts/functions.js ================================================ function isEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function md5cycle(x, k) { var a = x[0], b = x[1], c = x[2], d = x[3]; a = ff(a, b, c, d, k[0], 7, -680876936); d = ff(d, a, b, c, k[1], 12, -389564586); c = ff(c, d, a, b, k[2], 17, 606105819); b = ff(b, c, d, a, k[3], 22, -1044525330); a = ff(a, b, c, d, k[4], 7, -176418897); d = ff(d, a, b, c, k[5], 12, 1200080426); c = ff(c, d, a, b, k[6], 17, -1473231341); b = ff(b, c, d, a, k[7], 22, -45705983); a = ff(a, b, c, d, k[8], 7, 1770035416); d = ff(d, a, b, c, k[9], 12, -1958414417); c = ff(c, d, a, b, k[10], 17, -42063); b = ff(b, c, d, a, k[11], 22, -1990404162); a = ff(a, b, c, d, k[12], 7, 1804603682); d = ff(d, a, b, c, k[13], 12, -40341101); c = ff(c, d, a, b, k[14], 17, -1502002290); b = ff(b, c, d, a, k[15], 22, 1236535329); a = gg(a, b, c, d, k[1], 5, -165796510); d = gg(d, a, b, c, k[6], 9, -1069501632); c = gg(c, d, a, b, k[11], 14, 643717713); b = gg(b, c, d, a, k[0], 20, -373897302); a = gg(a, b, c, d, k[5], 5, -701558691); d = gg(d, a, b, c, k[10], 9, 38016083); c = gg(c, d, a, b, k[15], 14, -660478335); b = gg(b, c, d, a, k[4], 20, -405537848); a = gg(a, b, c, d, k[9], 5, 568446438); d = gg(d, a, b, c, k[14], 9, -1019803690); c = gg(c, d, a, b, k[3], 14, -187363961); b = gg(b, c, d, a, k[8], 20, 1163531501); a = gg(a, b, c, d, k[13], 5, -1444681467); d = gg(d, a, b, c, k[2], 9, -51403784); c = gg(c, d, a, b, k[7], 14, 1735328473); b = gg(b, c, d, a, k[12], 20, -1926607734); a = hh(a, b, c, d, k[5], 4, -378558); d = hh(d, a, b, c, k[8], 11, -2022574463); c = hh(c, d, a, b, k[11], 16, 1839030562); b = hh(b, c, d, a, k[14], 23, -35309556); a = hh(a, b, c, d, k[1], 4, -1530992060); d = hh(d, a, b, c, k[4], 11, 1272893353); c = hh(c, d, a, b, k[7], 16, -155497632); b = hh(b, c, d, a, k[10], 23, -1094730640); a = hh(a, b, c, d, k[13], 4, 681279174); d = hh(d, a, b, c, k[0], 11, -358537222); c = hh(c, d, a, b, k[3], 16, -722521979); b = hh(b, c, d, a, k[6], 23, 76029189); a = hh(a, b, c, d, k[9], 4, -640364487); d = hh(d, a, b, c, k[12], 11, -421815835); c = hh(c, d, a, b, k[15], 16, 530742520); b = hh(b, c, d, a, k[2], 23, -995338651); a = ii(a, b, c, d, k[0], 6, -198630844); d = ii(d, a, b, c, k[7], 10, 1126891415); c = ii(c, d, a, b, k[14], 15, -1416354905); b = ii(b, c, d, a, k[5], 21, -57434055); a = ii(a, b, c, d, k[12], 6, 1700485571); d = ii(d, a, b, c, k[3], 10, -1894986606); c = ii(c, d, a, b, k[10], 15, -1051523); b = ii(b, c, d, a, k[1], 21, -2054922799); a = ii(a, b, c, d, k[8], 6, 1873313359); d = ii(d, a, b, c, k[15], 10, -30611744); c = ii(c, d, a, b, k[6], 15, -1560198380); b = ii(b, c, d, a, k[13], 21, 1309151649); a = ii(a, b, c, d, k[4], 6, -145523070); d = ii(d, a, b, c, k[11], 10, -1120210379); c = ii(c, d, a, b, k[2], 15, 718787259); b = ii(b, c, d, a, k[9], 21, -343485551); x[0] = add32(a, x[0]); x[1] = add32(b, x[1]); x[2] = add32(c, x[2]); x[3] = add32(d, x[3]); } function cmn(q, a, b, x, s, t) { a = add32(add32(a, q), add32(x, t)); return add32((a << s) | (a >>> (32 - s)), b); } function ff(a, b, c, d, x, s, t) { return cmn((b & c) | ((~b) & d), a, b, x, s, t); } function gg(a, b, c, d, x, s, t) { return cmn((b & d) | (c & (~d)), a, b, x, s, t); } function hh(a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t); } function ii(a, b, c, d, x, s, t) { return cmn(c ^ (b | (~d)), a, b, x, s, t); } function md51(s) { var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i; for (i = 64; i <= s.length; i += 64) { md5cycle(state, md5blk(s.substring(i - 64, i))); } s = s.substring(i - 64); var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (i = 0; i < s.length; i++) tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3); tail[i >> 2] |= 0x80 << ((i % 4) << 3); if (i > 55) { md5cycle(state, tail); for (i = 0; i < 16; i++) tail[i] = 0; } tail[14] = n * 8; md5cycle(state, tail); return state; } /* there needs to be support for Unicode here, * unless we pretend that we can redefine the MD-5 * algorithm for multi-byte characters (perhaps * by adding every four 16-bit characters and * shortening the sum to 32 bits). Otherwise * I suggest performing MD-5 as if every character * was two bytes--e.g., 0040 0025 = @%--but then * how will an ordinary MD-5 sum be matched? * There is no way to standardize text to something * like UTF-8 before transformation; speed cost is * utterly prohibitive. The JavaScript standard * itself needs to look at this: it should start * providing access to strings as preformed UTF-8 * 8-bit unsigned value arrays. */ function md5blk(s) { /* I figured global was faster. */ var md5blks = [], i; /* Andy King said do it this way. */ for (i = 0; i < 64; i += 4) { md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24); } return md5blks; } var hex_chr = '0123456789abcdef'.split(''); function rhex(n) { var s = '', j = 0; for (; j < 4; j++) s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; return s; } function hex(x) { for (var i = 0; i < x.length; i++) x[i] = rhex(x[i]); return x.join(''); } function md5(s) { return hex(md51(s)); } /* this function is much faster, so if possible we use it. Some IEs are the only ones I know of that need the idiotic second function, generated by an if clause. */ function add32(a, b) { return (a + b) & 0xFFFFFFFF; } if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') { function add32(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } } ================================================ FILE: public/scripts/setup.js ================================================ // setup.js $(function() { App.init(); }); ================================================ FILE: public/scripts/table_helper.js ================================================ $(function() { $('body').append("
"); $('body').append("
"); }); function sort(column) { $("#table_helper_sort_column").val(column); $("#table_helper_sort_form").submit(); } function show_search() { $("#show_filter").hide(); $("#search_area").show(); } function do_search() { $("#table_helper_search").val($("#search_q").val()); $("#table_helper_search_form").submit(); } function remove_search() { $("#search_q").val(""); do_search(); } function remove_item(item_id) { $('#delete_item_modal_item_id').val(item_id); $('#delete_item_modal').modal({}); } ================================================ FILE: tools/check_i18n_files.js ================================================ var fs = require('fs'); var path = require('path'); var i18n_dirname = path.join(__dirname, '..', 'data/i18n'); fs.readdir(i18n_dirname, function(err, list) { list.forEach(function(filename) { console.log('\x1b[36m', 'i18n file:', '\x1b[0m', filename); var content = null; try { content = "" + fs.readFileSync(path.join(i18n_dirname, filename), 'utf8'); } catch (e) { console.log('\x1b[31m', 'Error:', '\x1b[0m', 'Can not open file. Permission denied'); } if (content !== null) { try { var items = JSON.parse(content); var items_count = 0; for (var k in items) { if (items.hasOwnProperty(k)) { items_count++; } } var strings_count = 'no strings'; if (items_count == 1) strings_count = '1 string'; else if (items_count > 1) strings_count = items_count + ' strings'; console.log('\x1b[36m', 'Valid:', '\x1b[0m', strings_count); } catch (e) { console.log('\x1b[31m', 'Error:', '\x1b[0m', 'Invalid JSON format'); console.log('NOT VALID'); } } }); }); ================================================ FILE: tools/harvest_i18n_strings.js ================================================ var fs = require('fs'); var path = require('path'); var harvester = function(dirname, callback) { var walk = function(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var i = 0; (function next() { var file = list[i++]; if (!file) return done(null, results); file = dir + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { walk(file, function(err, res) { results = results.concat(res); next(); }); } else { results.push(file); next(); } }); })(); }); }; var foundItems = {}; var foundItemsCount = 0; var parseFile = function(filename, transalateTag) { transalateTag = transalateTag || 't'; var regex = new RegExp("\{" + transalateTag + "\}([^\{]+)\{\/" + transalateTag + "\}", 'g'); var data = "" + fs.readFileSync(filename, 'utf8'); var matches = data.match(regex); var openingTagLength = ('{' + transalateTag + '}').length; var closingTag = '{/' + transalateTag + '}'; var closingTagLength = closingTag.length; if (matches !== null) matches.forEach(function(match) { var string = ''; if (match.length > 7) string = match.substr(openingTagLength, match.indexOf(closingTag) - openingTagLength); else return false; if (typeof(foundItems[string]) == 'undefined') { foundItems[string] = ''; foundItemsCount++; } }); }; var parseHTMLFile = function(filename) { var regex = /data-i18n="([^"]+)"/g; var data = "" + fs.readFileSync(filename, 'utf8'); var matches = data.match(regex); if (matches !== null) matches.forEach(function(match) { var string = ''; if (match.length > 7) string = match.substr(("data-i18n=\"").length, match.length - ("data-i18n=\"").length - 1); else return false; if (typeof(foundItems[string]) == 'undefined') { foundItems[string] = ''; foundItemsCount++; } }); }; walk(dirname, function(err, results) { console.log('Found ' + results.length + ' files'); if (err) throw err; var foundTplCount = 0; var foundHtmlCount = 0; results.forEach(function(file) { if (file.slice(-4) === '.tpl') { parseFile(file); parseFile(file, 'ts'); parseFile(file, 'tp'); foundTplCount++; } if (file.slice(-5) === '.html' || file.slice(-4) === '.htm') { parseHTMLFile(file); foundHtmlCount++; } }); console.log('Found ' + foundTplCount + ' tpl files'); console.log('Found ' + foundHtmlCount + ' html files'); console.log('Found ' + foundItemsCount + ' i18n strings'); callback(Object.keys(foundItems)); }); }; var dirname = path.join(__dirname, '..', 'public'); var i18n_dirname = path.join(__dirname, '..', 'data/i18n'); harvester(dirname, function(strings) { // console.log(strings); var i18n_files = fs.readdirSync(i18n_dirname); i18n_files.filter(function(file) { if (file.slice(-5) !== '.json') return false; else return true; }); var updatei18n = function(i18n_file, strings) { var data = {}; try { data = JSON.parse("" + fs.readFileSync(path.join(i18n_dirname, i18n_file), 'utf8')); } catch (e) { } var newStringsCount = 0; strings.forEach(function(string) { if (typeof(data[string]) == 'undefined') { data[string] = ''; newStringsCount++; } }); fs.writeFileSync(path.join(i18n_dirname, i18n_file), JSON.stringify(data, null, 2)); console.log('Updated. Added ' + newStringsCount + ' new strings.'); }; console.log("There're " + i18n_files.length + ' i18n files'); // console.log(i18n_files); // console.log(strings); i18n_files.forEach(function(i18n_file) { console.log('Updating ' + i18n_file); updatei18n(i18n_file, strings); }); console.log('Done'); });