Commit 7d8f60ff by Mahendra_Kr

Added leave module and write test cases

parent ebb60b88
class Api::V1::LeaveAllocationController < ApplicationController
def index
leave = LeaveAllocation.all.order(created_at: :desc)
render json: leave
end
def create
leave = LeaveAllocation.create!(leave_params)
if leave
render json: leave
else
render json: leave.errors
end
end
# def show
# end
def destroy
leave&.destroy
render json: { message: 'Leave Allocation deleted!' }
end
def leave_params
params.permit(:leaveType, :allowDaysPerMonth, :allowDaysPerYear)
end
def leave
@leave ||= LeaveAllocation.find(params[:id])
end
end
import React from "react";
import { Link } from "react-router-dom";
export default class AddLeaveAllocation extends React.Component {
constructor(props) {
super(props);
this.state = {
leaveType: "",
allowDaysPerMonth: "",
allowDaysPerYear: "",
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.stripHtmlEntities = this.stripHtmlEntities.bind(this);
}
stripHtmlEntities(str) {
return String(str)
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
onChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
/***************************Add Leave Allocation**********************/
onSubmit(event) {
event.preventDefault();
const url = "/api/v1/leave_allocation/create";
const { leaveType, allowDaysPerMonth, allowDaysPerYear } = this.state;
if (leaveType.length == 0 || allowDaysPerMonth.length == 0 || allowDaysPerYear.length == 0)
return;
const body = {
leaveType,
allowDaysPerMonth,
allowDaysPerYear,
};
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch(url, {
method: "POST",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => {
this.props.history.push(`leave-allocation-list`)
})
.catch(error => console.log(error.message));
}
/****************************End of Add Leave Allocation***********************/
render() {
return (
<div className="container mt-5">
<div className="row">
<div className="col-sm-12 col-lg-6 offset-lg-3">
<h1 className="font-weight-normal mb-5">Create Leave Allocation</h1>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label htmlFor="recipeName">Leave Type</label>
<input
type="text"
name="leaveType"
id="type"
className="form-control"
required
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="recipeIngredients">Allow Days Per Month</label>
<input
type="text"
name="allowDaysPerMonth"
id="daysPerMonth"
className="form-control"
required
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="recipeIngredients">Allow Days Per Year</label>
<input
type="text"
name="allowDaysPerYear"
id="daysPerYear"
className="form-control"
required
onChange={this.onChange}
/>
</div>
<button type="submit" className="btn btn-success mt-3">Add</button>
<Link to="leave-allocation-list" className="btn btn-link mt-3">
Back </Link>
</form>
</div>
</div>
</div>
);
}
}
\ No newline at end of file
...@@ -19,7 +19,7 @@ export default () => ( ...@@ -19,7 +19,7 @@ export default () => (
> >
View Recipes View Recipes
</Link> </Link>
<br></br> <br></br><br></br>
<Link <Link
to="/employees" to="/employees"
className="btn btn-lg custom-button" className="btn btn-lg custom-button"
...@@ -27,6 +27,14 @@ export default () => ( ...@@ -27,6 +27,14 @@ export default () => (
> >
View Employees View Employees
</Link> </Link>
<br></br><br></br>
<Link
to="/leave-allocation-list"
className="btn btn-lg custom-button"
role="button"
>
Leave
</Link>
</div> </div>
</div> </div>
</div> </div>
......
import React from "react";
import { Link } from "react-router-dom";
export default class LeaveAllocationList extends React.Component {
constructor(props) {
super(props);
this.state = {
leaveAllocationList: []
};
}
/*************************************Fetching Leave allocation list**************************************************/
fetchLeaveAllocation() {
const url = "/api/v1/leave_allocation/index";
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => this.setState({ leaveAllocationList: response }))
.catch(() => this.props.history.push(`leave-allocation-list`));
}
/********************************End Of Fetching leave allocation list***************************************/
/******************************************Function for Delete Leave Allocation******************************************/
deleteLeaveAllocation(id) {
const url = `/api/v1/leave_allocation/destroy/${id}`;
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch(url, {
method: "DELETE",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
}
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(() => {
this.fetchLeaveAllocation();
this.props.history.push(`leave-allocation-list`);
})
.catch(error => console.log(error.message));
}
/******************************************End of Function for Delete Leave Allocation************************************/
render() {
const { leaveAllocationList } = this.state;
const allLeaveAllocationList = leaveAllocationList.map((l, index) => (
<div key={index} className="col-md-6 col-lg-4">
<div className="card mb-4">
<div className="card-body">
<h5 className="card-title">Leave Type. :- {l.leaveType}</h5>
<h5 className="card-title">Allowe Days Per Month :- {l.allowDaysPerMonth}</h5>
<h5 className="card-title">Allow Days Per Year :- {l.allowDaysPerYear}</h5>
<button className="btn custom-button" onClick={() => this.deleteLeaveAllocation(l.id)}>Delete Student</button>
</div>
</div>
</div>
));
const noLeaveAllocation = (
<div className="vw-100 vh-50 d-flex align-items-center justify-content-center">
<h4>
No Data
</h4>
</div>
);
return (
<>
<section className="jumbotron jumbotron-fluid text-center">
<div className="container py-0">
<h1 className="display-4">List of Leave Allocaton</h1>
</div>
</section>
<div className="py-5">
<main className="container">
<div className="text-right mb-3">
<Link to="/add-leave-allocation" className="btn custom-button">
Create Leave Allocaton
</Link>
</div>
<div className="row">
{leaveAllocationList.length > 0 ? allLeaveAllocationList : noLeaveAllocation}
</div>
</main>
</div>
</>
);
}
componentDidMount() {
this.fetchLeaveAllocation();
}
}
\ No newline at end of file
...@@ -7,7 +7,8 @@ import NewRecipe from "../components/NewRecipe"; ...@@ -7,7 +7,8 @@ import NewRecipe from "../components/NewRecipe";
import Employees from "../components/Employees"; import Employees from "../components/Employees";
import Employee from "../components/Employee"; import Employee from "../components/Employee";
import NewEmployee from "../components/NewEmployee"; import NewEmployee from "../components/NewEmployee";
import AddLeaveAllocation from "../components/AddLeaveAllocation";
import LeaveAllocationList from "../components/LeaveAllocationList";
export default ( export default (
<Router> <Router>
<Switch> <Switch>
...@@ -18,6 +19,8 @@ export default ( ...@@ -18,6 +19,8 @@ export default (
<Route path="/employees" exact component={Employees} /> <Route path="/employees" exact component={Employees} />
<Route path="/employee/:id" exact component={Employee} /> <Route path="/employee/:id" exact component={Employee} />
<Route path="/employee" exact component={NewEmployee} /> <Route path="/employee" exact component={NewEmployee} />
<Route path="/add-leave-allocation" exact component={AddLeaveAllocation} />
<Route path="/leave-allocation-list" exact component={LeaveAllocationList} />
</Switch> </Switch>
</Router> </Router>
); );
\ No newline at end of file
class LeaveAllocation < ApplicationRecord
validates :leaveType, presence: true
validates :allowDaysPerMonth, presence: true
validates :allowDaysPerYear, presence: true
end
...@@ -29,7 +29,7 @@ development: ...@@ -29,7 +29,7 @@ development:
# To create additional roles in postgres see `$ createuser --help`. # To create additional roles in postgres see `$ createuser --help`.
# When left blank, postgres will use the default role. This is # When left blank, postgres will use the default role. This is
# the same name as the operating system user that initialized the database. # the same name as the operating system user that initialized the database.
username: agami username: agami-l25
# The password associated with the postgres role (username). # The password associated with the postgres role (username).
password: agami password: agami
......
Rails.application.routes.draw do Rails.application.routes.draw do
namespace :api do namespace :api do
namespace :v1 do namespace :v1 do
get 'leave_allocation/index'
post 'leave_allocation/create'
# get 'leave_allocation/show'
delete 'leave_allocation/destroy/:id',to:'leave_allocation#destroy'
end
end
namespace :api do
namespace :v1 do
get 'employees/index' get 'employees/index'
post 'employees/create' post 'employees/create'
get 'employee/show/:id', to: 'employees#show' get 'employee/show/:id', to: 'employees#show'
......
class CreateLeaveAllocations < ActiveRecord::Migration[5.2]
def change
create_table :leave_allocations do |t|
t.string :leaveType, null:false
t.text :allowDaysPerMonth, null:false
t.text :allowDaysPerYear, null:false
t.timestamps
end
end
end
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_09_30_024252) do ActiveRecord::Schema.define(version: 2020_10_03_051624) do
# These are extensions that must be enabled in order to support this database # These are extensions that must be enabled in order to support this database
enable_extension "plpgsql" enable_extension "plpgsql"
...@@ -27,6 +27,14 @@ ActiveRecord::Schema.define(version: 2020_09_30_024252) do ...@@ -27,6 +27,14 @@ ActiveRecord::Schema.define(version: 2020_09_30_024252) do
t.datetime "updated_at", null: false t.datetime "updated_at", null: false
end end
create_table "leave_allocations", force: :cascade do |t|
t.string "leaveType", null: false
t.text "allowDaysPerMonth", null: false
t.text "allowDaysPerYear", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "recipes", force: :cascade do |t| create_table "recipes", force: :cascade do |t|
t.string "name", null: false t.string "name", null: false
t.text "ingredients", null: false t.text "ingredients", null: false
......
FactoryBot.define do
factory :leave do
leaveType {'Casual Leave'}
allowDaysPerMonth {'10'}
allowDaysPerYear {'24'}
end
factory :random_leave, class: Employee do
leaveType { Faker::Name.leaveType }
allowDaysPerMonth { Faker::Name.allowDaysPerMonth }
allowDaysPerYear { Faker::Name.allowDaysPerYear }
end
end
\ No newline at end of file
require "rails_helper"
RSpec.describe "leaveFile" do
describe 'Fixture file test case' do
it "reads sample file" do
fileData = file_fixture("leave.txt").read;
expect(fileData).to eq("Casual Leave")
end
end
end
Casual Leave
\ No newline at end of file
require 'rails_helper'
RSpec.describe LeaveAllocation, type: :model do
context 'Validation tests' do
# let(:leave) { build(:leave) }
it 'leaveType validation' do
leave = LeaveAllocation.new( allowDaysPerMonth:'10',allowDaysPerYear:'24').save
expect(leave).to eq(false);
end
it 'allowDaysPerMonth validation' do
leave = LeaveAllocation.new(leaveType:'Casual Leave', allowDaysPerYear:'24').save
expect(leave).to eq(false);
end
it 'allowDaysPerYear validation' do
leave = LeaveAllocation.new(leaveType:'Casual Leave',allowDaysPerMonth:'10').save
expect(leave).to eq(false);
end
it 'Should save successfully' do
leave =LeaveAllocation.new(leaveType:'Casual Leave', allowDaysPerMonth:'10',allowDaysPerYear:'24').save
expect(leave).to eq(true);
end
end
context 'Scope tests ' do
end
# pending "add some examples to (or delete) #{__FILE__}"
end
require 'rails_helper'
RSpec.describe "Api::V1::LeaveAllocations", type: :request do
describe "GET /index" do
it "returns http success" do
get "/api/v1/leave_allocation/index"
# expect(response).to have_http_status(:success)
expect(response.status).to eq(200)
end
end
describe "GET /create" do
it "returns http success" do
get "/api/v1/leave_allocation/create"
expect(response).to have_http_status(:success)
end
end
# describe "GET /show" do
# it "returns http success" do
# get "/api/v1/leave_allocation/show"
# expect(response).to have_http_status(:success)
# end
# end
describe "GET /destroy" do
it "returns http success" do
get "/api/v1/leave_allocation/destroy"
expect(response).to have_http_status(:success)
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment