on design and development of cash remittance functionality ... p.pdf · “design and development...
TRANSCRIPT
A Summer Internship Project Report
On
“Design and Development of Cash
Remittance functionality in MIFOS X
Open Source Micro-Finance platform” Carried out at the
Institute of Development and Research in Banking Technology,
Hyderabad
Established by ‘Reserve Bank of India’
Submitted by
NITISH POIGAL
Roll No. – 11MA20033
Int.M.Sc. Mathematics and Computing [2011-16]
Under the Guidance of
Mr. Lalit Mohan S.,
Senior Technology Manager
IDRBT, Hyderabad
July 8, 2015
Table of Contents
Certificate ....................................................................................................................................................... 2
Acknowledgements ....................................................................................................................................... 3
Objective ........................................................................................................................................................ 3
Introduction ................................................................................................................................................... 3
The Mifos Initiative ................................................................................................................................ 3
Mifos Overview ...................................................................................................................................... 4
Mifos X Overview .................................................................................................................................. 4
Key Design Principles .............................................................................................................................. 4
Introduction .......................................................................................................................................... 4
Mifos X Financial Service Engine ......................................................................................................... 4
Layer Diagram........................................................................................................................................ 5
API Layer ................................................................................................................................................ 5
Service Layer .......................................................................................................................................... 6
Data Layer ............................................................................................................................................. 6
Architecture ............................................................................................................................................ 7
Source Code Directory Structure ............................................................................................................ 8
Mifos X Financial Service Engine ......................................................................................................... 8
Package Structure ................................................................................................................................. 9
Project Overview ......................................................................................................................................... 10
Prerequisite .............................................................................................................................................. 10
Build Instructions ..................................................................................................................................... 11
Get the Source ....................................................................................................................................... 11
Initial setup............................................................................................................................................ 11
Clone the repository .............................................................................................................................. 11
Configure remotes ................................................................................................................................. 11
Keep up to date ..................................................................................................................................... 12
Build .......................................................................................................................................................... 12
Import project into IntelliJ IDEA ........................................................................................................ 12
Run Configuration ................................................................................................................................... 13
Preparation ........................................................................................................................................... 14
Creating a Branch ................................................................................................................................ 14
PAGE 1
Pull in changes ..................................................................................................................................... 14
Mifos Usage .............................................................................................................................................. 15
Configuring an Organization .............................................................................................................. 15
Clients / Groups / Centers ................................................................................................................... 15
Lending ................................................................................................................................................. 15
Accounting ........................................................................................................................................... 15
Standard Financial Account Principles ................................................................................................. 16
Real Accounts – related to Assets and Liabilities .............................................................................. 16
Personal Accounts – related to people (or legal entities) .................................................................. 16
Nominal Accounts – related to profits, losses, incomes and expenses............................................. 16
Liabilities .............................................................................................................................................. 16
Assets .................................................................................................................................................... 16
Income .................................................................................................................................................. 16
Expenses ............................................................................................................................................... 16
Coding Mifos X ............................................................................................................................................ 17
How I made the changes ...................................................................................................................... 17
Diagrams .................................................................................................................................................. 17
Use Case Diagram ................................................................................................................................ 17
Class diagram ....................................................................................................................................... 17
Sequence diagram ................................................................................................................................ 18
New Packages and Classes created ........................................................................................................ 18
Classes and their purpose .................................................................................................................... 19
Development Process ................................................................................................................................. 20
Testing and Results .................................................................................................................................... 28
Conclusion ................................................................................................................................................... 33
Future Work ................................................................................................................................................ 34
References .................................................................................................................................................... 34
PAGE 2
Certificate
This is to certify that Mr. Nitish Poigal, pursuing Int.M.Sc. Degree in Mathematics and Computing
at Indian Institute of Technology, Kharagpur has undertaken a project as an intern at IDRBT,
Hyderabad from April 30, 2015 to July 8, 2015.
He was assigned the project “Design and Development of Cash Remittance functionality in
MIFOS X Open Source Micro-Finance platform” under my guidance. During the course of the
project he has undertaken the task of developing cash remittance feature for Mifos and has done
excellent work.
I wish him all the best for all his endeavors.
Mr. Lalit Mohan S.
(Project Guide)
Senior Technology Manager
IDRBT, Hyderabad
PAGE 3
Acknowledgements
This project was quiet learning for me at each and every step, at the same time it has given me the
confidence to work in the real life and professional setup. I feel the experience gained during the
project would lead me to bright prospects in the future.
I wish to express my profound gratitude to my Guide Mr. Lalit Mohan S. for giving me
opportunity to do this project in the Institute for Development and Research in Banking
Technology (IDRBT).
I am also thankful to Mr. B. Shandilya for giving me valuable suggestions during the work. I would
like to thank Sangamesh and Markus Geiß for providing excellent functional and technical
sessions.
At the end, I would like to thank the faculty of Indian Institute of Technology Kharagpur for
allowing me to do this Summer Internship Program.
Objective
The objective was to implement cash remittance functionality that currently does not exist, onto
the Mifos core banking platform.
Introduction
The Mifos Initiative
The Mifos Initiative is a 501(c)3 non-profit incorporated in Washington State. Its sole mission is to
speed the elimination of poverty by enabling financial service providers to more effectively and
efficiently deliver responsible financial services to the world’s 2.5 billion poor and unbanked. We
guide the development of the Mifos X platform, an open platform for financial inclusion with a
suite of simple configurable apps hosted in the cloud. We are a community of financial service
providers, technology specialists, financial services experts and open source developers working
together to grow this platform. The Mifos X project spun out of the Grameen Foundation in 2011
and, thanks to generous support from Silicon Valley, The Mifos Initiative was revitalized as a U.S.
based 503(c)3. Redesigned and built around an API-centric, cloud-based software architecture, the
Mifos X Platform is a modern, connected core banking system for responsible financial services
organizations bringing basic financial services to the poor globally.
PAGE 4
Mifos Overview
Mifos is an open source information management platform developed by the Grameen
Foundation's Technology Center. Mifos is a centralized web-based MIS purpose-built for the
microfinance industry. Utilizing thin-client technology gives the entire organization real-time
access to vital work processes and information. Management is delivered deep client insight
through business analytics and social reporting, therefore increasing operational efficiencies and
driving revenue generation through expanded products and reach.
Mifos X Overview
Mifos X is the next generation of Mifos, which is led by Mifos Initative. Redesigned and built
around anAPI-centric, cloud-based software architecture, the Mifos X Platform is a modern, solving
the challenges of core banking systems that are too expensive, too complicated or that have no
local support. Mifos X can be deployed in any environment: cloud or on-premise, on or offline,
mobile or PC; it’s extensible enough to support any organizational type or delivery channel, and
flexible enough to support any product, service, or methodology. For any organization, big or small,
it will provide client data management, loan and savings portfolio management, integrated real
time accounting and social and financial reporting needed to bring digital financial services in a
modern connected world. The platform is completely open via the Mozilla Public License 2.0.
KEY DESIGN PRINCIPLES
Introduction
Mifos X Software Platform (simply “the Platform”) is built around a multitenant, service oriented,
and tiered architecture, and can be deployed in a SaaS (Software as a Service) model or on-
premises.
The foundation forms a robust but flexible data model which is ready-made for extensions and
customizations. An API provides access to all basic functions grouped in modules.
Because the Platform needs to be accessible to users at remote locations, a browser-based solution
was essential.
Java was selected as a suitable high level language allowing the rapid customization of code
required for each individual circumstance yet has a large number of powerful libraries available.
Mifos X Financial Service Engine
The Mifos X Financial Service Engine (simply “the Engine”) is a scalable and extensible framework
written in Java, and licensed under the Mozilla Public License 2.0.
PAGE 5
The main design principle of the Engine is CQRS (Command Query Responsibility Segregation), a
pattern that separates commands and queries into different models and services. This approach has
multiple benefits: 1) State changes (commands) are persisted, providing an audit of all changes, 2)
fine grained control and extension of state changes, and 3) scalability based on consumer behavior
and real system load.
Based on a tiered architecture the Engine provides multiple layers to separate concerns and allow
reusability.
Layer Diagram
API Layer
The API Layer is built entirely as a RESTful Webservice, using JSON to transmit data, and utilizes
standard HTTP Methods for interactions.
The main components of this layer are:
Resources
Every module is exposed via an URI (Unique Resource Identifier).
Access Control
PAGE 6
Early exit if a consumer lacks authorization for a queried Resource.
Data marshalling
Any data transmitted to and from the API is de-/serialized using JSON.
The API is exposed via HTTPS to encrypt all data and secure the communication. OAuth2 is used
for authorization.
Stateless by nature the API Layer can be scaled based on the actual load and even used in high
availability scenarios.
Service Layer
The Service Layer provides module specific business logic and rules, role based access control and a
xBRL compliant reporting engine. Transaction awareness and data validity is encapsulated, and
extension points are available to enhance built-in workflows.
Cross concerns like Security or Transactions are part of the core framework and provided via AOP
(Aspect Oriented Programming).
The Service Layer has horizontal and vertical layers.
Services, command, and event handlers form horizontal layers; functional modules form vertical
layers.
Data Layer
The Data Layer provides module specific access to data stores. Data integrity is reached by using
the ACID principal and well defined data relations. Write and read operations are encapsulated in
different repositories to define a clean responsibility separation.
The Data Layer uses two cache strategies to cache data efficiently; database and 2nd level caching.
Database caching stores records on the database level and is useful for reporting, batch jobs, and
low level SQL queries.
2nd Level caching stores data objects on the application level and keeps database turnarounds on a
very low level allowing fast in-memory access of frequent data.
PAGE 7
Architecture
The Engine’s architecture was designed with a focus on modern, scalable and extensible
technologies ready to run in the cloud. All components where selected based on their maturity,
proven reliability and cost efficiency.
It is our goal to provide a software that is deployable with effectively no cost that can grow with the
customer need over time using well known best practices and support from a wide range of
communities.
The basic Mifos X Financial Service Engine architecture is as follows:
Resource Component Comment
Operating System Linux , Windows, Mac
OS
Amazon AWS image and Debian package
available
Runtime Java 7.x
Application Server Tomcat 7.x Embedded Tomcat for development
environments
PAGE 8
Resource Component Comment
Database MySQL 5.x Embedded MariaDB for development
environments
Application
Framework
Spring Framework 4.x
Persistence
Framework
Hibernate 4.x
Reporting Engine Pentaho Reporting
Engine 3.x
Test Framework JUnit 4.x
Mockito 1.x
REST-assured 2.x
SOURCE CODE DIRECTORY STRUCTURE
Mifos X Financial Service Engine
Only main folders are covered here. All other folders are obsolete or containing out-dated
information.
mifosx
Project root containing license, readme, and changlog files. In addition some build scripts to run
the build on Jenkins are included.
api-docs
Source file and styles for the online API documentation.
mifosng-provider
The main folder for the Mifos X Financial Service Engine. Gradle build scripts and project files are
located here.
PAGE 9
All sources can be found below src and the sub-folder structure follows the recommended
gradle/maven approach:
main/java
contains all Java source files
main/resources
contains the log configuration
main/resources/META-INF
contains all configuration files for Hibernate and Spring
main/resources/sql/migrations
contains all SQL scripts used by Flyway and some additional scripts to populate sample data
test/java
contains all JUnit source files
test/resource/META-INF
contains unit test specific Spring configurations
integrationTest/java
contains all Java source files for automated test scenarios
Package Structure
The package structure follows the domain.module.layer approach. Where domain is
org.mifosplatform, module is a functional area of the software and can contain sub-modules, and
layer is the technical function of this module.
All sections of a package name are in singular.
A layer can be:
annotation
All annotations for this module
api
All RESTful resources for this module
data
POJOs that are transmitted to the API consumer
PAGE 10
domain
Entities and data access classes
exception
All module specific exceptions
handler
All module specific command handlers
provider
Factory classes
service
All service classes enclosing the business logic for this module
util
Helper and utility classes
Some examples
org.mifosplatform.command.api // valid
org.mifosplatform.organisation.office.domain // valid using a sub-module
org.mifosplatform.service.batch // invalid; module must be before the layer
Project Overview
Setting up Mifos X development environment
PREREQUISITE
Java SDK 7
To compile the source code, and as a run time environment, Java SDK 7 is needed.
Download and install Java from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-
downloads-1880260.html.
PAGE 11
Git
Git serves as our distributed revision control system.
You can find detailed information on how to install git on your system at http://git-
scm.com/book/en/v2/Getting-Started-Installing-Git.
MySQL
MySQL is the database used by the Mifos X Financial Service Engine.
Download and installation instructions can be found here:
http://dev.mysql.com/downloads/mysql/.
BUILD INSTRUCTIONS
Get the Source
Initial setup
If you dont have a github account already then you need to sign up and create one on on
github.com (free accounts are fine).
Once you have a github account, the next step is to fork https://github.com/openMF/mifosx or
https://github.com/openMF/community-app.git.
See https://help.github.com/articles/fork-a-repo for help on forking in github.
Clone the repository
Create a directory in which you want the cloned project to exist within: e.g. in directory ~/repo
git clone [fork repository url]
See https://help.github.com/articles/which-remote-url-should-i-use.
Configure remotes
When a repository is cloned, it has a default remote called origin that points to your fork on
GitHub, not the original repository it was forked from. To keep track of the original repository, you
should add another remote named upstream:
The easiest way is to use the https url:
git remote add upstream https://github.com/openMF/[mifosx | community-app].git
PAGE 12
or if you have ssh set up you can use that url instead:
git remote add upstream [email protected]:openMF/[mifosx | community-app].git
Keep up to date
There will be development changes to both repositories almost every day for the foreseeable future
so its important to keep your fork of the software up to date with the latest changes.
To pull in upstream changes from repository you forked:
git checkout develop
git fetch upstream
git merge upstream/develop
You should not have any local changes on your master branch, if you do, use rebase!
Once you have pulled all latest changes and your build was successful, push the just merged
changes to the develop branch on your fork.
git push origin develop
BUILD
After setting up your environment, and downloading the source, Setup to configure your IntelliJ
IDEA:
Import project into IntelliJ IDEA
1. Open command prompt / terminal.
2. Go to folder mifosng-provider.
3. Fire the command ./gradlew -Penv=dev idea
4. Once the command is done, IDEA project files will be created in the same folder.
5. From Explorer/Finder open the file mifosng-provider.ipr
PAGE 13
RUN CONFIGURATION
Remove 'Make' form 'Before Launch' by selecting the value and push '-'
Add a new 'Before Launch' entry '+' and select 'Gradle task'.
'-Penv=dev' is doing the trick by setting a Gradle project property that will include all needed
classes and libraries to run in a development environment.
PAGE 14
Preparation
Every change to the code is tracked by an issue in JIRA; without an issue, code will not be reviewed,
and without review, code will not be accepted. To avoid duplication, search for an existing issue
about the change, and if none exists, file a new one. Most of the communication about code
changes takes place in the issue, so be sure that the issue describes the exact problem being solved.
The issue workflow is part of the Development Process.
The person who is working on an issue should be the "assignee" of that issue in JIRA.
Creating a Branch
Each pull request should represent a single complete change, so you should separate distinct
changes into multiple pull requests.
Its probably easiest if you create a new 'topic' branch on your forked repository for each unique
piece of work rather than commit changes directly into master or our special develop branch. Why?
It means you can work on something very specific, get it up to date and send a 'pull request', To
move on to a seperate piece of work, you simply create a different branch. It might also make it
easier to keep up to date with the openMF/mifosx repository as explained in next section.
git checkout -b [topic]
Pull in changes
There will be development changes to the openMF/mifosx almost every day for the foreseeable
future so its important to keep your fork of the software up to date with the latest changes.
To pull in upstream changes from repository you forked revisit the section "Keep up to date" form
the build instructions.
After you pulled all changes from upstream you need to rebase your topic branch with the latest
code.
git checkout [topic]
git rebase develop
If you are ready push your topic branch to your GitHub account.:
git push origin [topic]
PAGE 15
MIFOS USAGE
I have undergone functional training session on how to use Mifos X so that the code base will start
to make more sense and I will be able to understand it and able to make changes to it. Below are
the some of the things I have learnt in that session.
Configuring an Organization
Branches / Officers
Staff
Dropdown values
Data tables
Global Configurations
Roles and Permissions
Clients / Groups / Centers
Client Statuses
Lending
Loan Products
Loan Accounts - creation
Loan Account Approval and Loan Disbursal
Interest Calculation for Loans
Repayment Strategies for Loans
Deposits
Savings products
Savings Account Creation, Approval and Activation
Interest Calculation and posting for Savings Accounts
Accounting
Chart of Accounts
Accounting Principles
Journal Entries
Accounting for Loans
Accounting for Deposits
Accounting Closures
Reports
PAGE 16
STANDARD FINANCIAL ACCOUNT PRINCIPLES
Real Accounts – related to Assets and Liabilities
• Debit – what comes in
• Credit – what goes out
Personal Accounts – related to people (or legal entities)
• Debit – the receiver
• Credit – the giver
Nominal Accounts – related to profits, losses, incomes and expenses
• Debit – all expenses and losses
• Credit – the giver
Liabilities
Capital
Savings Portfolio
Assets
cash
Bank
Fixtures and Fittings
Loan Portfolio
Allowance for Bad and Doubtful Debts
Income
Fees and Charges Received
Interest Received
Expenses
Electricity Charges
Salaries and Wages
Bad Debts
Interest on Deposits
Loan Write Offs
PAGE 17
Coding Mifos X
How I made the changes
I started out with use case diagram then moved on to class diagram and sequence diagram. Once
that is done I started to make necessary changes.
DIAGRAMS
Use Case Diagram
Class diagram
PAGE 19
AccountApiResource
o data
AccountData
o domain
MockedAccountStorage
o exceptions
AccountNotFoundException
o service
AccountReadService
AccountWriteService
Screenshot
Classes and their purpose
AccountApiResource
This class exposes the Restful api to the external world. Using appropriate http service we can send
a GET or a POST request to activate any service and this class defines the services that are exposed
and the interception url is defined here. We heavily make use of Spring frame by using annotations
such as Component , Autowired, Scope , Path, Consumes, Produces etc.
AccountData
This call defines how the account data is represented i.e. the class variables and methods. We also
define getters and setters to make changes to this information.
MockedAccountStorage
For the sake of simplicity we have used a LinkedHashMap datastructure to hold the accounts data
for our use. We could improve our implementation by using AbstractPersistableClass i.e. using
persistence with the help of JPA and hibernate.
PAGE 20
AccountNotFoundException
We include all our expentions exception package. AccountNotFoundException is triggered when
we try to fetch and account by providing account number but the account object is not present.
AccountReadService
We use Command Query Responsibility Segregation i.e. we separate Read and Write services and
the classes that get invoked from AccountApiResource will be either in AccountReadService or
AccountWriteService. Usually all the methods that are related to reading fall under this class.
AccountWriteService
All the services related to writing are actually implemented here.
Development Process
We create a new module by providing some cash remittance use case. We start by creating new
package structure and we put this beside org.mifosplatform. I simply call it nitish.account . All the
changes we are doing are usually happenning in the org mifos platform. So, if you start doing things
here or extending it or changing stuff or something else and may be you can get in trouble once
they are also working on the same classes or structure and may be then you get merge conflicts
when you pull back changes they have made.
If you want to start doing something specifically for your need and also you are doing something
beside the current implementation it is recommended using separate package beside the real
package.
We add another package we call it data, api for the REST portion of it. Representational State
Transfer (REST) is a software architecture style consisting of guidelines and best practices for
creating scalable web services REST is a coordinated set of constraints applied to the design of
components in a distributed hypermedia system that can lead to a more performant and
maintainable architecture.
Under data we create new class called account data. We use the same name scheme that we use in
mifos. An important thing that you need to remember is that if we put it into their schema we
should put the liscence header
PAGE 21
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
We need accountNumber, account Name , Type , Amount. I want a constructor Also add getters
and setters. Nothing really sophisticated here.
public class AccountData {
private String accountNumber;
private String accountName;
private String type;
private Long amount;
public AccountData() {
super();
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
}
Add a new class in api package lets call it AccountApiResource it still fits the name scheme. Lets
add license header.Add constructor .We need to put annotations on top of it.
Add @Component spring annotation. Component is mocker annotation that lets spring know that
this class needs to be picked up during bootstrapping and then spring is doing the magic of offering
it in his discovery tree add @Path annotation so that I can tell spring where it is located and in my
PAGE 22
case it will be “/accounts” and also add the @Scope(“singleton”) we use it for our resources for all
api resources or rest services we usually use scope singleton we tell spring that only should provide
only one version of this class and use this class when one is entering https/something/clients then
you will always get the same class@Component
@Scope("singleton")
@Path("/accounts")
public class AccountApiResource {
We use different package scheme so we must tweak application context which we can do in
multiple ways. One would be to add it to add package in component scan but that will lead to
conflicts because when they adding new stuff then it will overlay my stuff. What is recommended
it to create a new xml file In my case I use nitishModules.xml
I added my own xml file and to it I added component scan base package for my main account
package here.Now I need to let the current context know that there is something new. I simply say
import resource and I use my new resource here and that’s it.<import resource="nitishModules.xml"/>
This is the only line of code I need to take care of in the current implementation because this the
only real thing I have changed in existing code and everything else is totally new. So this makes it
easy to track the changes I am doing because it is the only line of code I have to take care about
when I pull in changes from the real codebase and same for my modules . I will have all my
configurations I will ever need in the future in this specific xml file
PAGE 23
<?xml version="1.0" encoding="UTF-8"?>
<!--
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this file,
You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan
base-package="nitish.account"/>
</beans>
In metain-inf spring appcontext.xml is main configuration file for spring as you can see we use
context component scan which tells spring that it should look into some specific packages during
the starting of the container because we do not want to scan all the class path because we know
where our stuff is we define some packages here so he simply skip into it and find classes that we
think are important for him (spring) we got some exclude filter in this case we tell him that
everything that is annotated with controller is simply not picked up and used for this configuration
I usually work from to bottom I prepare my accounts API and I want to offer the UI developer to
start working with it also some dummy implementation.
I create service package and new java class AccoutReadService and AccountWriteService
and use the same header license information.
Add domain package and create new class MockedAccountStorage class and add header.I treat it as
a repository so I call it @Repository now also @Scope(“singleton”). Repository is a child of
component.
@Repository
@Scope("singleton")
public class MockedAccountStorage {
I use Linkedhashmap in memory store for account data. Create constructor. Add methods
save ,find , fetchAll()
PAGE 24
public MockedAccountStorage() {
super();
}
public void save(final AccountData accountData) {
this.accountCache.put(accountData.getAccountNumber(), accountData);
}
public AccountData find(final String accountNumber){
if(!this.accountCache.containsKey(accountNumber)) {
throw new AccountNotFoundException(accountNumber);
}
return this.accountCache.get(accountNumber);
}
public List<AccountData> fetchAll(){
return new ArrayList<>(this.accountCache.values());
}
Under service package add ConsumerReadService and add @Service annotation.@Service
public class AccountReadService {
We add @Service for services which are in service package we use more specific annotation called
service and it’s a child from component. Component is generic version of something that spring
could auto detect. Then you got service and you also got repository and Controller. Repository used
if using class that access that data store interacting with database.
@Controller - we do not support - we usually use it in model view controller system which wouldn't
make sense on our side as we do not support controller and model and view on the rest service
because there are no models and views. In our case usually there are simply services and repository.
Add MockedAccountStorage in AccountReadServiceprivate final MockedAccountStorage accountStorage;
accountStorage is declared final so it must be initialized otherwise we get errors.@Autowired
public AccountReadService(final MockedAccountStorage accountStorage) {
super();
this.accountStorage = accountStorage;
}
We will use @Autowired so that spring will know I will use mocked consumer storage. We add
methods validateAccount and fetchAllAccounts to it.
PAGE 25
public AccountData validateAccount(final String accountNumber) {
return this.accountStorage.find(accountNumber);
}
public List<AccountData> fetchAllAccounts() {
return this.accountStorage.fetchAll();
}
Similarly I will create class AccountWriteService under service and do the same thing. I add
methods createAccount
public void createAccount(final AccountData accountData){
this.accountStorage.save(accountData);
}
and creditAccount public void createAccount(final AccountData accountData){
this.accountStorage.save(accountData);
}
public void creditAccount(final String accountNumber, final Long amountToCredit) {
final String accountType = this.accountStorage.find(accountNumber).getType();
final Long currentAmount =
this.accountStorage.find(accountNumber).getAmount();
long finalAmount;
switch(accountType) {
case "savings":
finalAmount = currentAmount + amountToCredit;
break;
case "bank":
case "loan": finalAmount = currentAmount - amountToCredit;
break;
default:
finalAmount = currentAmount;
}
this.accountStorage.find(accountNumber).setAmount(finalAmount);
}
And debitAccount method.
PAGE 26
public void debitAccount(final String accountNumber, final Long amountToDebit) {
final String accountType = this.accountStorage.find(accountNumber).getType();
final Long currentAmount =
this.accountStorage.find(accountNumber).getAmount();
long finalAmount;
switch(accountType) {
case "savings":
finalAmount = currentAmount - amountToDebit;
break;
case "bank":
case "loan": finalAmount = currentAmount + amountToDebit;
break;
default:
finalAmount = currentAmount;
}
this.accountStorage.find(accountNumber).setAmount(finalAmount);
}
}
Now I will go to my AccountApiResource and add accountReadService and accountWriteService
and since it is final we need to initialize it in constructorprivate final AccountReadService accountReadService;
private final AccountWriteService accountWriteService;
Add methods fetchAll() which returns a list of account data. We use @get as it will be our get
request. @Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_HTML,
MediaType.APPLICATION_JSON}) and @Produces({MediaType.APPLICATION_JSON}) are
straightforward.
@GET
@Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public List<AccountData> fetchall() {
return this.accountReadService.fetchAllAccounts();
}
I would like to have decent exception handling. In my MockedAccountStorage if somebody tries to
find accout by accountNumber and I would do something like this
if(!this.accountCache.containsKey(accountNumber)) {
throw new AccountNotFoundException(accountNumber);
}
I am doing a check if my accountCache contains my accountNumber and then will throw an
exception in this case it is AccountNotFoundException. Create package exception new class
account not found exception
PAGE 27
It extends PlatformResourceNotFoundException
public class AccountNotFoundException extends
AbstractPlatformResourceNotFoundException{
public AccountNotFoundException(String accountNumber) {
super("error.msg.account.notfound", "Account '"+ accountNumber +"' not
found",accountNumber);
}
}
In AccountApiResource we crate validate account method
@GET and special path call it “accNo” add Path Parameter to use this path “accNo”
@GET
@Path("{accNo}")
@Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public AccountData validateAccount(@PathParam("accNo") final String accountNumber) {
return this.accountReadService.validateAccount(accountNumber);
}
We either get an account that we request for or it throws an exception.
Similarly we do it for createAccount and here we use @POST instead of @GET and the body of the
post must be of the type application/json or else we might get errors.
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public void createAccount(final AccountData accountData) {
this.accountWriteService.createAccount(accountData);
}
In the same way the API for remitCash is defined as follows. Where path parameters giver, receiver
and amount are passed to giverAccountNumber, receiverAccountNumber and amount variables.
PAGE 28
@POST
@Path("{giver}/{receiver}/{amount}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public void remitCash(@PathParam("giver") final String giverAccountNum,
@PathParam("receiver") final String receiverAccountNum,
@PathParam("amount") final Long amount) {
this.accountWriteService.creditAccount(giverAccountNum,amount);
this.accountWriteService.debitAccount(receiverAccountNum,amount);
}
At this point we will have all our API fully functional and we can start testing it out by running our
embedded server and using REST client.
Testing and Results
For the sake of simplicity I have tested it using Advanced Rest Client application. Using this
application we can send http GET or POST request to our server.
We start by running our embedded server
When we see Hit Enter to quit… in the log window it means our code has compiled successfully
and our embedded server is running.
Before we start testing our code we need to make sure we accept the certificate to proceed to local
host.
The above figure shows what would happen if we do not accept the certificates and click proceed to
local host (unsafe). Here is how you do it.
PAGE 29
We then create some dummy accounts for the purpose of testing. We send POST request to
“/accounts” url and the type of the message must be application/json or else we might get errors.
We include the appropriate headers and authentication key so that we do not have to enter it
manually everytime. We change the resource to accounts.
PAGE 30
After post request is being sent the account gets created and we can then make a get request to
view all the accounts that are present.
Which will give the following output.We see that we have four accounts. One bank account , and
three customer accoutns the first two accouts are savings type and the last one is loan account type.
The bank account has account type as bank. Depending on the type of the account we use differet
logic when we debit or credit the accounts.
PAGE 31
Now we remit cash by POST request and specifying the accounts and amount in the url in the
format “giver/receiver/amount” so that the code will credit the giver , debit the receiver by that
amount. The logic of increasing and decreasing the amount in an account by some number
depends both on whether it is being credited or debited and also the type of the account.
To demonstrate this we make two different requests in which the customer account types are
different.
The first one involves a savings account type and bank account type.
PAGE 32
Here we notice that that customer account is getting credit and bank account is getting debited.
Although we see that the numbers increase we must keep in mind that bank account is an asset
and savings account is liability therefore they are on the opposite of the accounting equation and if
one increases then the other must increase. Hence, we get correct result.
On the other hand we look at a situation when a bank account and loan account are involved.
PAGE 33
We notice that the amount in the loan account is getting reduced and the amount in the bank
account is getting increased. Both bank and loan account comes under assets hence they are on
same side of accounting equation. If one of them increase the other must decrease. Since bank is
getting debited and loan account is getting credited the amount in the bank account is getting
increased and amount in customer account decreases. Which is what we actually expected.
Conclusion
I would like to conclude the report by stating the following points
Successfully added remittance feature to Mifos X platform.
Provided Class diagram and Sequence diagram so that it becomes easy to understand the
classes and relationship between them and how and why the changes have been made in
such a way.
Tested using the Advanced Rest Client application to test the validity of the code and the
accounting principles it uses.
The work done so far will help the frontend developers to develop the community-app i.e.
the GUI of the application. All the ground work has been done successfully.
PAGE 34
Future Work
The code currently uses mocked data instead of using actual data. Therefore the code can be
further improved to use actual data. Also it can be extended to compute bank charges and produce
invoice or receipt after remitting successfully if necessary. The front end i.e, the community-app
can be developed independently of the Mifos X platform but by making use of the work I have done
so far the front end developers will find developing community-app much easier.
References
1. Mifos x wiki - https://github.com/openMF/mifosx/wiki
2. Developers page - https://mifosforge.jira.com/wiki/display/MDZ/Welcome+in+the+Zone
3. Mifos x API documentation - https://demo.openmf.org/api-docs/apiLive.htm
4. GitHub – My Fork- https://github.com/poigalnitish/mifosx/tree/consumerdata
5. GitHub- Code Changes-https://github.com/poigalnitish/CodeChangesMifos