Newspaper Automation Agency Sowftware Report
Newspaper Automation Agency Sowftware Report
1. Introduction
1.1Purpose
This Public Photography Contest with Live Voting System Software Requirement
Specification (SRS) main object is to provide a base for the foundation of the project.
It gives comprehensive view of how the system is supposed to work and requirements
for implementing the system.
This SRS can also be used for future as basis for detailed understanding on how
project was started. It provides a blueprint to upcoming new developers and
maintenance teams to assist in maintaining and modifying this project as per required
changeability.
1.2 Scope
The system will be used to properly portray the skills of photographers. It maintains
three levels of users: Admin, Photographers and Voters (or users).
Admins will be able to conduct contest based on specific themes, notify the registered
users, check if uploaded photograph is not taken from any other source and declare
the winners of a contest. Photographers can register to a contest and upload
photographs to show his skills. Voters can vote for three best photographs in a
contest.
1.4References
[1] Fundamentals of Software Engineering, Rajiv Mall
1.5 Document overview: The remaining part of this document contains other
information about the system such as general description of the system, functional
requirements, external interface requirements, performance requirements, design
constraints and other requirements.
1
2 General Description
This is a web based system implementing client-server model. The system provides a
platform for photographers where they can show their skills and win some awards.
Users registration
Users login
Create contest
Contest registration
Originality check
Limitation check
Users voting
Winner declaration
Admin
Admin can conduct contest based on a theme. The admin must check whether images
belong to corresponding photographer only, and not taken from other sources. If
entries exceed the required participation limit, admin will select top images and users
will vote for the best one. Admin can choose the winner either by the number of likes
on a photograph or directly select the winner. Admin must have good knowledge of
application server.
Photographer
Photographer can register to contests and upload a photo. Photographer must have
basic IT knowledge to register and upload photo.
Voters
They can view all the ongoing contests and vote for photograph they like (maximum
3 votes for each contest). Voters must be capable of using the web UI interface.
2
2.4 General Constraints
3 Functional Requirements
3
Function 4 Contest Registration
Input Contest_id , Email_id, photograph
A new record with the above details should be
Processing inserted into the contest_image table of the database.
4
Function 8 Winner declaration
Input Contest_id
Processing Check in votes table for the entry which has secured
maximum votes or select the photographer chosen by
the admin.
Output Declare the winner.
The user interface for the system must be compatible to any type of web browser such
as Mozilla Firefox, Google Chrome and Internet Explorer.
OS(Windows)
Google Images
Java, HTML, CSS
MySQL
Apache server
5
5 Performance Requirements
Data in database should be updated within 2 seconds
Query results must return results within 5 seconds
Load time of UI should not take more than 2 seconds
Login validation should be done within 3 seconds
6
SRS FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
1. Introduction
1.1 Purpose
This Newspaper Agency Automation Software Requirement Specification (SRS) main
objective is to provide a base foundation of the project. It gives comprehensive view of
how the system is supposed to work and requirements for implementing the system.
This SRS can also be used for future as basis for detailed understanding on how project
was started. It provides a blueprint to upcoming new developers and maintenance teams
to assist in maintaining and modifying this project as per required changeability.
1.2 Scope
The software will be used to manage the delivery of newspapers and magazines, print
delivery details and bills. It maintains two levels of users: Manager and Delivery persons.
Manager can add details of newspapers / magazines, add new subscription or modify or
stop subscriptions of customers and also stop delivery for certain period for a customer.
The delivery persons can check the addresses to which he must deliver the publications.
1.3 Definitions, Acronyms and abbreviations
SRS Software Requirement Specification
HTML Hyper-Text Markup Language
UI User Interface
OS Operating System
IT Information Technology
AMD Advanced Micro Devices
1.4 References
[1] Fundamentals of Software Engineering, Rajiv Mall
1.5 Document overview:
The remaining part of this document contains other information about the system such as
general description of the software, functional requirements, external interface
requirements, performance requirements, design requirements and other requirements.
7
2. General Description
2.1 Product Perspective
This software is developed to automate various clerical activities associated with the local
newspaper and magazine delivery agency.
2.2 Product Functions Overview:
Manager/ Deliverer login
Add Publication
Edit publication details
Add customer
Edit customer details
Publications to be delivered
Delivery summary
Customer bills
With-Hold subscription
Payment receipt
Deliverer payment
2.3 User Characteristics:
There are 2 user levels in this system:
A. Manager
B. Deliverer
Manager
Manager can add new newspaper/ magazine details, add new customers and can edit
those details. Manager can view summary of the deliveries and print bills of
customers. He can also add, modify, stop and hold subscriptions for a while if
customers go out of station. Manager must have basic IT knowledge to operate the
software.
Deliverer
Deliverer can view the addresses to which he must deliver the publications every day.
He can also view his monthly payment details. Deliverers must be capable of using
UI interface of the software.
8
2.4 General Constrains:
I. Memory: Software will require 2GB space.
II. Language Requirement: Software must be only in English.
III. Budget Constraint: Due to limited budget, this software is intended to very
simple and just for basic functionalities. UI is going to be very simple.
IV. Implementation Constraint: Application should be based on Java.
3. Functional Requirements
9
Function 4 Add customer
Input Customer name, address, phone, subscription
Processing A new record with the above details is inserted into the
database.
Output Notify the user whether the data is successfully inserted
or not.
10
Function 8 Customer bills
Input Customers, subscriptions, publications
Processing Calculate the total amount to be paid by the customer for
a month based on the type of publication and number of
publications received by a customer.
Output Print the bill for each customer which includes
publication type, the number of copies delivered in a
month and cost for these.
11
4. External Interface Requirements
4.1 User Interfaces
The user interface for the system must be compatible to windows OS.
4.2 Software Interfaces
OS (Windows)
Java, HTML
MySQL
4.3 Hardware interfaces
5. Performance Requirements
Data in database should be updated within 2 seconds
Query results must return results within 5 seconds
Load time of UI should not take more than 2 seconds
Login validation should be done within 3 seconds
12
Entity Relationship Diagram (ERD)
An entity relationship diagram (ERD) shows the relationships of entity sets stored in a database.
An entity in this context is a component of data. In other words, ER diagrams illustrate the
logical structure of databases.
At first glance an entity relationship diagram looks very much like a flowchart. It is the
specialized symbols, and the meanings of those symbols, that make it unique.
A weak entity is an entity that must defined by a foreign key relationship with another
entity as it cannot be uniquely identified by its own attributes alone.
Actions, which are represented by diamond shapes, show how two entities share
information in the database.
13
Attributes, which are represented by ovals. A key attribute is the unique, distinguishing
characteristic of the entity. For example, an employee's social security number might be
the employee's key attribute.
A multivalued attribute can have more than one value. For example, an employee entity
can have multiple skill values.
Connecting lines, solid lines that connect attributes to show the relationships of entities
in the diagram.
Cardinality specifies how many instances of an entity relate to one instance of another
entity
14
ER DIAGRAM FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
id
phone_no
name
Distributor
customer_id
address
1
Delivers
address
id
M
phone_no
name
Customers
amount
status due
M 1
Subscribe Withhold
M 1
Newspaper/ Subscriptions
id
Magazine
name
id duration
price description
customer_id
language
15
DATA FLOW DIAGRAMS (DFDs)
A data flow diagram (DFD) maps out the flow of information for any process or system. It
uses defined symbols like rectangles, circles and arrows, plus short text labels, to show data
inputs, outputs, storage points and the routes between each destination.
Data flowcharts can range from simple, even hand-drawn process overviews, to in-depth,
multi-level DFDs that dig progressively deeper into how the data is handled. They can be
used to analyse an existing system or model a new one.
1. External entity: an outside system that sends or receives data, communicating with the
system being diagrammed. They are the sources and destinations of information entering
or leaving the system. They might be an outside organization or person, a computer
system or a business system. They are also known as terminators, sources and sinks or
actors. They are typically drawn on the edges of the diagram.
2. Process: any process that changes the data, producing an output. It might perform
computations, or sort data based on logic, or direct the data flow based on business rules.
A short label is used to describe the process, such as “Submit payment.”
3. Data store: files or repositories that hold information for later use, such as a database
table or a membership form. Each data store receives a simple label, such as “Orders.”
4. Data flow: the route that data takes between the external entities, processes and data
stores. It portrays the interface between the other components and is shown with arrows,
typically labelled with a short data name, like “Billing details.”
16
DFD levels and layers
A data flow diagram can dive into progressively more detail by using levels and layers,
zeroing in on a particular piece. DFD levels are numbered 0, 1 or 2, and occasionally go to
even Level 3 or beyond. The necessary level of detail depends on the scope of what we are
trying to accomplish.
DFD Level 0 is also called a Context Diagram. It’s a basic overview of the whole
system or process being analysed or modelled. It’s designed to be an at-a-glance view,
showing the system as a single high-level process, with its relationship to external
entities. It should be easily understood by a wide audience, including stakeholders,
business analysts, data analysts and developers.
DFD Level 1 provides a more detailed breakout of pieces of the Context Level
Diagram. You will highlight the main functions carried out by the system, as you
break down the high-level process of the Context Diagram into its sub processes.
DFD Level 2 then goes one step deeper into parts of Level 1. It may require more text
to reach the necessary level of detail about the system’s functioning.
17
DATAFLOW DIAGRAM (LEVEL 0) FOR NEWSPAPER AGENCY AUTOMATION SYSTEM
Newspaper
Agency
Manager Automation Distributor
System
0
18
DATAFLOW DIAGRAM (LEVEL 1) FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
ils
er deta Customers
custom
customer details Manage
Customers
0.2 custom er subscrition
s
cus Customer_Subscriptions
to mer
_id,
dura
Manager tion
Withhold_Subscriptions
distributor details Manage
Distributors
ils
0.3
ta
customer subscriptions
de
ls
etai
er
rd
buto
m
ri customer details
dist
sto
cu
distr
ibuto
r det newspaper details
Distributors ails
Delivery of
Publications
0.4
deliv
ery d
ails etails
er det , dat
e
s pap
ew
e r, n
tom d
cus s re ceive Delivery_summary
c ation
printed bill Customer publi
Bills
0.5 red
ve
eli
sd
tion
ca
bli
pu
Distributor
payment Distributor
Payment
0.6
19
DATAFLOW DIAGRAM (LEVEL 2) FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
critions
Add customer subs Customer_Subscriptions
Customers
newspaper details
0.2.1 custom
custom er deta
s
er_id ils
il
eta
er d
Customers
tom
Withold customer_id
cus
Subscriptions
ils,
d eta 0.2.2
r
t o me ation cus
tom
s r
cu du er_
id,
dur
Manager atio
n
Withhold_Subscriptions
distributor details Manage
Distributors
0.3 r_id
Check if any me
de tails sto
utor _id
customers are cu
rib er
dist m
out of station
sto 0.4.2
cu
distr
ibuto Group
Distributors r det Allocate
ails customer customer details
each area to address groups,
addresses in
a distributor customer details
one locality
0.4.3
0.4.1
s
scri ption
customer, distributor details
me r sub
custo
Bills
0.5
Distributor
Calculate
payment Distributor
Calculate sum of all
Payment sum
25% of sum publications
0.6
0.6.2 delivered
0.6.1
20
USE CASE DIAGRAMS
In the Unified Modeling Language (UML), a use case diagram can summarize the details of your
system's users (also known as actors) and their interactions with the system. To build one, you'll
use a set of specialized symbols and connectors. An effective use case diagram can help your
team discuss and represent:
Actor
Use case
System
Package
Actor
Actor in a use case diagram is any entity that performs a role in one given system. This could be
a person, organization or an external system and usually drawn like skeleton shown below.
Use Case
A use case represents a function or an action within the system. It’s drawn as an oval and named
with the function.
21
System
The system is used to define the scope of the use case and drawn as a rectangle. This an optional
element but useful when you’re visualizing large systems. For example, you can create all the
use cases and then use the system object to define the scope covered by your project. Or you can
even use it to show the different areas covered in different releases.
Package
The package is another optional element that is extremely useful in complex diagrams. Similar to
class diagrams, packages are used to group together use cases. They are drawn like the image
shown below.
There are five types of relationships in a use case diagram. They are
22
USE CASE DIAGRAM FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
Add
Customers
Edit
Customers
With-hold
Customers
Customer
Manager Bills
Add
Publications
View Edit
Summary Publications
Delivery
details
Deliverer Distributor
Payment
23
CLASS DIAGRAMS
Class diagrams are one of the most useful types of diagrams in UML as they clearly map out the
structure of a particular system by modeling its classes, attributes, operations, and relationships
between objects.
Upper section: Contains the name of the class. This section is always required, whether
you are talking about the classifier or an object.
Middle section: Contains the attributes of the class. Use this section to describe the
qualities of the class. This is only required when describing a specific instance of a class.
Bottom section: Includes class operations (methods). Displayed in list format, each
operation takes up its own line. The operations describe how a class interacts with data.
All classes have different access levels depending on the access modifier (visibility). Here are
the access levels with their corresponding symbols:
Public (+)
Private (-)
Protected (#)
Package (~)
Derived (/)
Static (underlined)
Class Relationships
A class may be involved in one or more relationships with other classes. A relationship can be
one of the following types
24
Relationship Type Graphical Representation
Inheritance (or Generalization):
Simple Association:
Aggregation:
Composition:
Dependency:
25
CLASS DIAGRAM FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
User
+ user_id : integer
+ user_name : string
Manager Distributor
+ addCustomer() + allocateArea()
+ editCustomer() + distributorBills()
+ addPublication()
+ editPublication()
+ withHold()
Summary
+ customerBills()
+ user_id : integer
+ dueRemainder()
+ customer_id : integer
+ summary()
+ date : string
withHold
+ customer_id : integer
+ duration : integer
Publications
+ paper_id : integer 1
1
+ paper_name : string
Customers
+ language : string
+ customer_id : integer
+ description : string M + customer_name : string
+ price : integer
+ address : string
+ phone_no : integer
+ subscriptions : string
+ amount : integer
M
+ due : integer
26
OBJECT DIAGRAM
Object is an instance of a particular moment in runtime, including objects and data values. A
static UML object diagram is an instance of a class diagram; it shows a snapshot of the detailed
state of a system at a point in time, thus an object diagram encompasses objects and their
relationships at a point in time. It may be considered a special case of a class diagram or a
communication diagram.
The use of object diagrams is fairly limited, mainly to show examples of data structures.
During the analysis phase of a project, you might create a class diagram to describe the
structure of a system and then create a set of object diagrams as test cases to verify the
accuracy and completeness of the class diagram.
Before you create a class diagram, you might create an object diagram to discover facts
about specific model elements and their links, or to illustrate specific examples of the
classifiers that are required.
Object Names:
Object Attributes:
Similar to classes, you are able to list object attributes inside a separate
compartment. However, unlike classes, object attributes should have
values assigned for them.
Links:
27
OBJECT DIAGRAM FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
Customers
P1 : Publications P3 : Publications
XYZ : Customer
28
SEQUENCE DIAGRAMS
Sequence diagrams are a popular dynamic modeling solution in UML because they specifically
focus on lifelines, or the processes and objects that live simultaneously, and the messages
exchanged between them to perform a function before the lifeline ends.
To understand what a sequence diagram is, you should be familiar with its symbols and
components. Sequence diagrams are made up of the following icons and elements:
Activation Represents the time needed for an object to complete a task. The longer
box the task will take, the longer the activation box becomes.
Actor
Shows entities that interact with or are external to the system.
symbol
29
Common message symbols
Use the following arrows and message symbols to show how information is transmitted between
objects. These symbols may reflect the start and execution of an operation or the sending and
reception of a signal.
Asynchronous return
Represented by a dashed line with a lined arrowhead.
message symbol
30
SEQUENCE DIAGRAM FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
Manage Customers
:System :Database
: Manager
alt
[ add customer ]
1: add customer()
2: customer details
3: display status
1: getCustomer()
2: display edit page
3: Edit details
5: display status
1: getCustomer()
2: display edit page
3: WithHold()
4: with hold duration details
5: display status
[ customer bills]
1: CustomerBills()
2: getDetails()
3: Customer details
4: Generete Bills
31
Manage Publications
:System :Database
: Manager
alt
[ add publication ]
1: addPublication()
2: publication details
3: display status
1: get publication
2: display edit page
3: editPublication()
5: display status
:System :Database
: Manager
1: summary()
2: get summary
3: sumary details
4: display summary
32
Delivery details
:System :Database
: Distributor
login
alt
[ delivery details ]
3: customer details
4: allocateArea()
5: Distribution details
1: distributorBills()
3: distribution list
4: generate bills
5: display bills
33
COLLABORATION DIAGRAM
It shows the object organization as seen in the following diagram. In the collaboration diagram,
the method call sequence is indicated by some numbering technique. The number indicates how
the methods are called one after another. We have taken the same order management system to
describe the collaboration diagram.
Method calls are similar to that of a sequence diagram. However, difference being the sequence
diagram does not describe the object organization, whereas the collaboration diagram shows the
object organization.
To choose between these two diagrams, emphasis is placed on the type of requirement. If the
time sequence is important, then the sequence diagram is used. If organization is required, then
collaboration diagram is used.
34
Delegation is like inheritance done manually through object composition.
Link to self is used to link the objects that fulfill more than one role.
Constraint is an extension mechanism that enables you to refine the semantics of a UML
model element.
35
COLLABORATION DIAGRAM FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
Add Customers
: System : Database
1: getCustomer()
3: Edit details 4: edit customer information
: System : Database
: Manager
2: display edit page
5: display status
Withhold Customers
1: getCustomer()
3: WithHold() 4: with hold duration details
: System : Database
Customer Bills
1: CustomerBills() 2: getDetails()
: System : Database
4: Generete Bills
36
Add Publications
1: addPublication()
2: publication details
: System : Database
: Manager
3: display status
: System : Database
: Manager
2: display edit page
5: display status
View Summary
: System : Database
Delivery details
2: get customer details
1: get delivery details 5: Distribution details
: System : Database
4: allocateArea()
Distributor payment
: System : Database
4: generate bills
37
STATE CHART DIAGRAM
State chart diagram is one of the five UML diagrams used to model the dynamic nature of a
system. They define different states of an object during its lifetime and these states are changed
by events. State chart diagrams are useful to model the reactive systems. Reactive systems can be
defined as a system that responds to external or internal events.
Initial state – We use a black filled circle represent the initial state of a System or a
class.
Transition – We use a solid arrow to represent the transition or change of control from
one state to another. The arrow is labeled with the event which causes the change in state.
State – We use a rounded rectangle to represent a state. A state represents the conditions
or circumstances of an object of a class at an instant of time.
Fork – We use a rounded solid rectangular bar to represent a Fork notation with
incoming arrow from the parent state and outgoing arrows towards the newly created
states. We use the fork notation to represent a state splitting into two or more concurrent
states
38
Join – We use a rounded solid rectangular bar to represent a Join notation with incoming
arrows from the joining states and outgoing arrow towards the common goal state. We
use the join notation when two or more states concurrently converge into one on the
occurrence of an event or events.
Self-transition – We use a solid arrow pointing back to the state itself to represent a self-
transition. There might be scenarios when the state of the object does not change upon the
occurrence of an event. We use self-transitions to represent such cases.
Final state – We use a filled circle within a circle notation to represent the final state in a
state machine diagram.
39
STATECHART DIAGRAM FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
Idle
send login
details
are credentials
correct no
yes
manage manage
customers customers due
publications bills remainder summary
Enter customer Enter publication enter customer enter customer enter customer
details details details details details
fetch details
from database
caculate bills
operation completed
40
Statechart diagram for Distributor
Idle
send login
details
are credentials
correct no
yes
fetch
fetch distribution
customer details
details
update
database
display status
operation completed
41
ACTIVITY DIAGRAM
Activity diagram is another important behavioral diagram in UML diagram to describe dynamic
aspects of the system. Activity diagram is essentially an advanced version of flow chart that
modeling the flow from one activity to another activity.
These activity diagram shapes and symbols are some of the most common types you'll find in
UML diagrams.
42
Symbol Name Description
Send signal symbol Indicates that a signal is being sent to a receiving activity.
43
ACTIVITY DIAGRAM FOR NEWSPAPER AGENCY AUTOMATION SOFTWARE
Add Customers
select add
customers
display customer
entry form
enter customer
details
select submit
option
update database
display update
succesful
44
Edit Customer details
select edit
customers
display customer
edit page
enter customer
details
fetch customer
details
display customer
details
select submit
option
update database
display update
succesful
45
Withhold Customers
select withhold
customers
display customer
withhold page
enter customer
details
fetch customer
details
display customer
details
enter withhold
details
select submit
option
update database
display update
succesful
46
Customer Bills
select customers
bills
fetch customer
details
calculate customer
bills
display customer
bills
View Summary
select view
summary
fetch delivery
summary details
display summary
details
47
Add Publications
select add
publications
display publications
entry form
enter publications
details
select submit
option
update database
display update
succesful
48
Edit Publication details
select edit
publications
display publications
edit page
enter publications
details
fetch publications
details
display publications
details
select submit
option
update database
display update
succesful
49
Delivery details
Distributor System Database
select delivery
details
fetch customer
details
allocate area
update database
display delivery
details
Distributor payment
select payment
details
fetch distribution
details
calculate payment
amount
display payment
details
50
IMPLEMENTATION
Implementation of the functionalities mentioned in SRS document is done using python framework,
DjangoRest.
STEPS:
1. New python environment for the project is created.
2. Dependencies – DjangoRest, pandas, fpdf, MySQL required for the project are installed.
3. A database is created in MySQL and linked to the project through the python file
‘settings.py’.
4. The python file ‘models.py’ contains code for creating tables in the database
5. The python file ‘serializers.py’ contains code for serialising the user input.
6. The python file ‘views.py’ contains code for functionalities of the project.
7. The python file ‘urls.py’ contains code for urls required for the project.
CODE:
settings.py
"""
Django settings for news project.
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR,
...)
BASE_DIR =
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '%p_4c&s7((gy&^n=q@t61x5&8w#t(5n_ponwbc0xf%tbj03ea@'
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
51
'rest_framework',
'agency.apps.AgencyConfig',
'rest_framework.authtoken',
'multiselectfield'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'news.urls'
TEMPLATES = [
{
'BACKEND':
'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
52
},
]
WSGI_APPLICATION = 'news.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "newsAgency",
'USER': "root",
'PASSWORD': 'hacker',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME':
'django.contrib.auth.password_validation.UserAttributeSimilarityVal
idator',
},
{
'NAME':
'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.NumericPasswordValidator',
53
},
]
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = False
STATIC_URL = '/static/'
urls.py – news
from django.contrib import admin
from django.urls import path
urlpatterns = [
url(r'agency/',include('agency.urls')),
url(r'^admin/', admin.site.urls),
]
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news.settings')
application = get_wsgi_application()
54
apps.py
from django.apps import AppConfig
class AgencyConfig(AppConfig):
name = 'agency'
models.py
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from django.contrib.auth.models import User
from multiselectfield import MultiSelectField
# from django.db import models
from django.contrib.auth.models import AbstractUser
# from datetime import datetime
from django.utils import timezone
from django.core.validators import RegexValidator
class Distributors(models.Model):
distributor_name = models.CharField(max_length=200)
address = models.CharField(max_length=200)
d_phone = models.CharField(max_length=200, validators=[d_ten])
class Publications(models.Model):
paper_name = models.CharField(max_length=200,
validators=[a_numeric])
55
language = models.CharField(max_length=200,
validators=[a_numeric])
description = models.CharField(max_length=200)
price = models.FloatField()
def __str__(self):
return self.paper_name
class Meta:
ordering = ('paper_name',)
class Customers(models.Model):
customer_name = models.CharField(max_length=200,
validators=[a_numeric])
address = models.CharField(max_length=200)
pincode = models.CharField(max_length=6, default='',
validators=[d_six])
phone = models.CharField(max_length=200, validators=[d_ten])
subscription =
models.ManyToManyField('Publications',default='')
due = models.FloatField(default=0)
class Subscript(models.Model):
phone = models.CharField(max_length=200)
subscription = models.ManyToManyField('Publications',
default='')
class WithHold(models.Model):
customer_id = models.ForeignKey('Customers',
on_delete=models.CASCADE)
from_date = models.DateField(default=timezone.now)
to_date = models.DateField(default=timezone.now)
class Summary(models.Model):
56
distributor_id = models.ForeignKey('Distributors',
on_delete=models.CASCADE)
customer_id = models.ForeignKey('Customers',
on_delete=models.CASCADE)
date = models.DateField(default=timezone.now)
serializers.py
from rest_framework import serializers, fields
from django import forms
from agency.models import Customers, Distributors, Publications,
WithHold, Summary, Subscript
from django.contrib.auth.models import User
from rest_framework import permissions
from django.contrib.auth import get_user_model
class CustomersSerializer(serializers.ModelSerializer):
# subscription = fields.MultipleChoiceField(choices=CHOICES)
class Meta:
model = Customers
fields = ('id', 'customer_name', 'address', 'pincode',
'phone', 'subscription')
class EditCustomersSerializer(serializers.ModelSerializer):
# subscription = fields.MultipleChoiceField(choices=CHOICES)
class Meta:
model = Subscript
fields = ('id','phone', 'subscription')
class EditPubicationSerializer(serializers.ModelSerializer):
class Meta:
57
model = Publications
fields = ('id','paper_name', 'price')
class DistributorsSerializer(serializers.ModelSerializer):
class Meta:
model = Distributors
fields = ('id','distributor_name', 'address', 'd_phone')
class PublicationsSerializer(serializers.ModelSerializer):
class Meta:
model = Publications
fields = ('id','paper_name', 'language', 'description',
'price')
class WithHoldSerializer(serializers.ModelSerializer):
phone = serializers.IntegerField()
class Meta:
model = WithHold
fields = ('id','phone', 'from_date', 'to_date')
class SummarySerializer(serializers.ModelSerializer):
class Meta:
model = Summary
fields = ('id', 'date')
class AllocationSerializer(serializers.ModelSerializer):
distributor_name = serializers.CharField(max_length=200)
58
class Meta:
model = Summary
fields = ('id', 'distributor_name', 'date')
class DistributorPaymentSerializer(serializers.ModelSerializer):
month = serializers.IntegerField(default=1)
year = serializers.IntegerField(default=2018)
class Meta:
model = Distributors
fields = ('id', 'distributor_name', 'month', 'year')
class CustomerBillsSerializer(serializers.ModelSerializer):
month = serializers.IntegerField(default=1)
year = serializers.IntegerField(default=2018)
class Meta:
model = Customers
fields = ('id', 'month', 'year')
class PaymentReceiptSerializer(serializers.ModelSerializer):
month = serializers.IntegerField(default=1)
year = serializers.IntegerField(default=2018)
amount = serializers.IntegerField(default=0)
class Meta:
model = Customers
fields = ('id', 'phone', 'month', 'year','amount')
59
fuctions.py
import math
def partition_list(a, k):
#check degenerate conditions
if k <= 1: return [a]
if k >= len(a): return [[x] for x in a]
partition_between = []
for i in range(k-1):
partition_between.append((i+1)*len(a)/k)
average_height = float(sum(a))/k
best_score = None
best_partitions = None
count = 0
no_improvements_count = 0
while True:
partitions = []
index = 0
for div in partition_between:
partitions.append(a[index:int(div)])
index = int(div)
partitions.append(a[index:])
worst_height_diff = 0
worst_partition_index = -1
for p in partitions:
height_diff = average_height - sum(p)
if abs(height_diff) > abs(worst_height_diff):
worst_height_diff = height_diff
worst_partition_index = partitions.index(p)
if best_score is None or abs(worst_height_diff) <
best_score:
best_score = abs(worst_height_diff)
best_partitions = partitions
60
no_improvements_count = 0
else:
no_improvements_count += 1
if worst_height_diff == 0 or no_improvements_count > 5 or
count > 100:
return best_partitions
count += 1
if worst_partition_index == 0:
if worst_height_diff < 0: partition_between[0] -= 1
else: partition_between[0] += 1
elif worst_partition_index == len(partitions)-1:
if worst_height_diff < 0: partition_between[-1] += 1
else: partition_between[-1] -= 1
else:
left_bound = worst_partition_index - 1
right_bound = worst_partition_index
if worst_height_diff < 0:
if sum(partitions[worst_partition_index-1]) >
sum(partitions[worst_partition_index+1]):
partition_between[right_bound] -= 1
else:
partition_between[left_bound] += 1
else:
if sum(partitions[worst_partition_index-1]) >
sum(partitions[worst_partition_index+1]):
partition_between[left_bound] -= 1
else:
partition_between[right_bound] += 1
61
views.py
from django.http import HttpResponse
from agency.models import Customers, Distributors, Publications,
WithHold, Summary, Subscript
from agency.serializers import CustomersSerializer,
DistributorsSerializer, PublicationsSerializer, WithHoldSerializer,
SummarySerializer
from agency.serializers import EditCustomersSerializer,
EditPubicationSerializer, AllocationSerializer,
DistributorPaymentSerializer
from agency.serializers import CustomerBillsSerializer,
PaymentReceiptSerializer
from rest_framework import generics
from django.contrib.auth.models import User
from rest_framework import permissions
from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework import permissions
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.views.static import serve
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import redirect
from django.template.loader import get_template
import numpy as np
import pickle
from django.db.models import Count
from agency.functions import partition_list
from datetime import datetime
62
import pandas as pd
import fpdf
import pdfkit, json
import calendar
def index(request):
return HttpResponse("Welcome to Newspaper Automation Agency
System")
class AddCustomer(generics.CreateAPIView):
queryset = Customers.objects.all()
serializer_class = CustomersSerializer
class EditCustomerSubscription(generics.CreateAPIView):
serializer_class = EditCustomersSerializer
serializer1 =
EditCustomersSerializer(Subscript.objects.get(phone=request.data['p
hone']))
h = serializer1.data['subscription']
Subscript.objects.all().delete()
t = Customers.objects.get(phone=request.data['phone'])
t.subscription.set(h)
t.save()
63
class AddPublication(generics.CreateAPIView):
queryset = Publications.objects.all()
serializer_class = PublicationsSerializer
class EditPublication(generics.CreateAPIView):
serializer_class = EditPubicationSerializer
Publications.objects.filter(paper_name=request.data['paper_name']).
update(price=request.data['price'])
return Response("update successful")
class AddDistributor(generics.CreateAPIView):
queryset = Distributors.objects.all()
serializer_class = DistributorsSerializer
class WithHoldCustomer(generics.CreateAPIView):
serializer_class = WithHoldSerializer
class AllocateArea(generics.CreateAPIView):
queryset = Summary.objects.all()
serializer_class = SummarySerializer
64
def create(self, request, *args, **kargs):
p =
Customers.objects.values('pincode').order_by('pincode').annotate(co
unt=Count('pincode'))
count_list = list()
pincode_list = list()
for i in p:
count_list.append(int(i['count']))
pincode_list.append(i['pincode'])
d_count = Distributors.objects.all().count()
sol = partition_list(count_list, d_count)
distributor = Distributors.objects.all()
index = 0
pin_no = 0
for d in distributor:
for i in range(len(sol[index])):
ctms =
Customers.objects.filter(pincode=pincode_list[pin_no])
for c in ctms:
hold =
WithHold.objects.filter(customer_id_id=c.id)
if hold:
for date in hold:
t_date =
pd.to_datetime(request.data['date']).date()
s_date = date.from_date
e_date = date.to_date
if s_date <= t_date <= e_date:
None
else:
summ =
Summary(distributor_id_id=d.id, customer_id_id=c.id,
date=request.data['date'])
summ.save()
65
else:
summ = Summary(distributor_id_id=d.id,
customer_id_id=c.id, date=request.data['date'])
summ.save()
pin_no = pin_no + 1
index = index + 1
class DistributorAllocation(generics.CreateAPIView):
queryset = Customers.objects.all()
serializer_class = AllocationSerializer
cus['subscriptions'].append(Publications.objects.get(id=customer.da
ta['subscription'][i]).paper_name)
c_list.append(cus)
66
return Response(c_list)
class DistributorPayment(generics.CreateAPIView):
queryset = Customers.objects.all()
serializer_class = DistributorPaymentSerializer
return Response(payment/4)
class CustomersBills(generics.CreateAPIView):
queryset = Customers.objects.all()
serializer_class = CustomerBillsSerializer
67
customers = Customers.objects.all()
for ctmr in customers:
bill = dict()
sub =
Summary.objects.filter(customer_id_id=ctmr.id).filter(date__range=(
s_date, e_date)).count()
bill['Name'] = ctmr.customer_name
bill['Month'] = request.data['month'] + '-' +
request.data['year']
bill['Bill'] = dict()
c =
CustomersSerializer(Customers.objects.get(phone=ctmr.phone))
for i in range(len(c.data['subscription'])):
name =
Publications.objects.get(id=c.data['subscription'][i]).paper_name
price =
Publications.objects.get(id=c.data['subscription'][i]).price
bill['Bill'][name] = price
amt = 0
bills = list()
st = 'Name ' + bill['Name']
bills.append(st)
st = 'Month ' + bill['Month']
bills.append(st)
bills.append("Bills")
for key, value in bill['Bill'].items():
st = ' ' + key + ' : ' + str(sub) + ' x
' + str(value)
bills.append(st)
amt = amt + sub * value
due = ctmr.due
amt = amt + due
st = 'Due ' + str(due)
bills.append(st)
68
st = 'Total Amount : Rs.' + str(amt)
bills.append(st)
Customers.objects.filter(id=ctmr.id).update(due=amt)
if amt:
pdf = fpdf.FPDF(format='letter')
pdf.add_page()
pdf.image('logo.jpg',0,0,210,45)
pdf.set_font("Arial", size=12)
pdf.cell(100)
pdf.ln(30)
pdf.write(bill)
for i in bills:
pdf.write(5,i)
pdf.ln()
p = "bills/" + bill['Month'] + "/" + str(ctmr.id) +
'_' + ctmr.customer_name + '.pdf'
pdf.output(p)
return Response("Bills saved")
class ViewSummary(generics.CreateAPIView):
queryset = Summary.objects.all()
serializer_class = CustomerBillsSerializer
69
customers = Customers.objects.all()
summ = list()
paper = dict()
publica = Publications.objects.all()
for p in publica:
paper[p.paper_name] = 0
for ctmr in customers:
sub =
Summary.objects.filter(customer_id_id=ctmr.id).filter(date__range=(
s_date, e_date)).count()
subscri = ''
c =
CustomersSerializer(Customers.objects.get(phone=ctmr.phone))
for i in range(len(c.data['subscription'])):
name =
Publications.objects.get(id=c.data['subscription'][i]).paper_name
paper[name] = paper[name] + sub
subscri = subscri + ', ' + name + '-' + str(sub)
pdf = fpdf.FPDF(format='letter')
70
pdf.add_page()
pdf.image('logo.jpg',0,0,210,45)
pdf.set_font("Arial", size=12)
pdf.cell(100)
pdf.ln(30)
pdf.write(5, month)
pdf.write(5,tit)
for i in summ:
pdf.write(5,i)
pdf.ln()
class PaymentReceipts(generics.CreateAPIView):
queryset = Customers.objects.all()
serializer_class = PaymentReceiptSerializer
customers =
Customers.objects.get(phone=request.data['phone'])
bills = list()
st = 'Name ' + customers.customer_name
bills.append(tit)
bills.append(st)
71
bills.append(month)
Customers.objects.filter(id=customers.id).update(due=int(customers.
due) - int(request.data['amount']))
pdf = fpdf.FPDF(format='letter')
pdf.add_page()
pdf.image('logo.jpg',0,0,210,45)
pdf.set_font("Arial", size=12)
pdf.cell(100)
pdf.ln(30)
for i in bills:
pdf.write(5,i)
pdf.ln()
72
urls.py
from django.conf.urls import url
from rest_framework.authtoken import views as tokenview
from rest_framework.urlpatterns import format_suffix_patterns
from agency import views
from django.conf.urls import include
from django.contrib.auth.decorators import login_required
from django.views.static import serve
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^addCustomer/$', views.AddCustomer.as_view()),
url(r'^editCustomer/$',
views.EditCustomerSubscription.as_view()),
url(r'^addDistributor/$', views.AddDistributor.as_view()),
url(r'^addPublication/$', views.AddPublication.as_view()),
url(r'^editPublication/$', views.EditPublication.as_view()),
url(r'^withHold/$', views.WithHoldCustomer.as_view()),
url(r'^allocateArea/$', views.AllocateArea.as_view()),
url(r'^distributorCheck/$',
views.DistributorAllocation.as_view()),
url(r'^distributorPayment/$',
views.DistributorPayment.as_view()),
url(r'^customerBills/$', views.CustomersBills.as_view()),
url(r'^viewSummary/$', views.ViewSummary.as_view()),
url(r'^paymentReceipts/$', views.PaymentReceipts.as_view()),
urlpatterns = format_suffix_patterns(urlpatterns)
73
urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
Output:
Add Customers
Input
output
74
Edit customers
input
Output
Add Publication
Input
75
Output
Edit Publication
Input
Output
76
WithHold Customers
Allocate Area
77
Distributor Allocation
78
Distributor payment
Customer Bills
79
customer_bill.pdf
80
Receipt.pdf
View Summary
81
Summary.pdf
---------------- x x x ----------------
82