Skip to content

Commit

Permalink
gestita paginazione tenants (BE e FE)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdslp committed Mar 26, 2020
1 parent c659cb9 commit 98f845e
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 74 deletions.
8 changes: 8 additions & 0 deletions backend/src/interfaces/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ export interface IRole {
name?: string;
}

export interface ISearchOpt {
count?: number;
needle?: string;
itemsPerPage?: number;
activePage?: number;
totalPages?: number;
}

export interface ITenant {
id?: number;
description?: string;
Expand Down
19 changes: 13 additions & 6 deletions backend/src/routes/private/tenantRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as express from 'express';
import * as HttpStatus from 'http-status-codes';
import TenantStore from '../../stores/tenantStore';

import { ITenant } from '../../interfaces/interfaces';
import { ITenant, ISearchOpt } from '../../interfaces/interfaces';
const _ = require('lodash');
const factory = require('../../shared/factory');
const router = express.Router();
Expand Down Expand Up @@ -41,10 +41,19 @@ router.get(
next: express.NextFunction
) => {
try {
const tenantsRes = await tenantStore.findAll();
console.log("req.query", req.query);
const options = req.query.options;
const search = req.query.search;
let searchOptions: ISearchOpt = options ? JSON.parse(options) : {};
searchOptions.itemsPerPage = searchOptions.itemsPerPage || 25;
searchOptions.activePage = searchOptions.activePage || 1;
searchOptions.needle = search || "";
const tenantsRes = await tenantStore.getAll(searchOptions);


if (tenantsRes && tenantsRes.length > 0) {
const result = factory.generateSuccessResponse(
tenantsRes,
{tenants: tenantsRes, options: searchOptions},
null,
'Tenants found'
);
Expand Down Expand Up @@ -75,8 +84,6 @@ router.post('/create', async (req, res, next) => {
let message = '';
if (!tenants || tenants.length == 0) {
const resCreation = await tenantStore.create(tenant);
console.log("resCreatio", resCreation);

if (resCreation && resCreation.length == 1) {
message = 'Tenant successfully created'
const result = factory.generateSuccessResponse(null, null, message);
Expand All @@ -86,7 +93,7 @@ router.post('/create', async (req, res, next) => {
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json(result);
}
} else {
message = 'Tenant already exists.'
message = 'Tenant already exists'
const result = factory.generateSuccessResponse(null, null, message);
res.status(HttpStatus.OK).json(result);
}
Expand Down
18 changes: 17 additions & 1 deletion backend/src/stores/tenantStore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ITenant } from '../interfaces/interfaces';
import { ITenant, ISearchOpt } from '../interfaces/interfaces';
const _ = require('lodash');
const moment = require('moment');
const config = require('../../../backend/knexfile');
Expand Down Expand Up @@ -32,4 +32,20 @@ export default class TenantStore {
findAll() {
return knex('tenants').returning('*');
}

getAll(options: ISearchOpt) {
return knex.raw(`SELECT *
FROM tenants
WHERE description LIKE '%${options.needle}%'
OR edge_interface_name LIKE '%${options.needle}%'
ORDER BY created_at DESC
LIMIT ${options.itemsPerPage}
OFFSET ${(options.itemsPerPage * (options.activePage - 1))}`
)
.then((data: any) => {
return data;
}).catch((err: any) => {
return err;
});
}
}
7 changes: 1 addition & 6 deletions frontend/interfaces/rest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,6 @@ export interface IDataResponse {

export interface IPaginationOpts {
activePage: number,
boundaryRange?: number,
siblingRange?: number,
showEllipsis?: boolean,
showFirstAndLastNav?: boolean,
showPreviousAndNextNav?: boolean,
totalPages: number;
itemPerPage: number;
itemsPerPage: number;
}
2 changes: 1 addition & 1 deletion frontend/src/api/tenantApi.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class TenantsApi extends api {
const url = '/api/private/tenant/create';
let params = tenant;
this.getClient(axiosClient => {
axiosClient.post(url, params)
axiosClient.post(url, { params })
.then((data) => {
resolve(data);
}).catch((error) => {
Expand Down
82 changes: 30 additions & 52 deletions frontend/src/components/forms/tenantForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,29 @@ import { connect } from 'react-redux';
import authutils from '../../utils/authutils';
import * as NotificationActions from '../../actions/notificationActions';
import * as UserActions from '../../actions/userActions';
import UserApi from './../../api/userApi';
import TenantApi from './../../api/tenantApi';
import DNSBaseComponent from '../dnsBaseComponent';
import { Grid, Input, Button, Container, Segment, Card, Image, Form } from 'semantic-ui-react';
import { history } from '../../main';
import _ from 'lodash';
import { Link } from 'react-router-dom';
import { IUser } from '../../../interfaces/user';
import { ITenant } from '../../../interfaces/tenant';

interface CompProps {
tenant?: ITenant;
onBack?: (arg?: any) => any;

}

interface CompState {
confirm_password?: string;
email?: string;
username?: string;
password?: string;
isLogin?: boolean;
description?: string;
edge_interface_name?: string;
}


class TenantForm extends DNSBaseComponent<CompProps | any, CompState> {
state = {
confirm_password: '',
email: '',
username: '',
password: '',
description: '',
edge_interface_name: ''
};

constructor(props: any) {
Expand Down Expand Up @@ -58,22 +55,24 @@ class TenantForm extends DNSBaseComponent<CompProps | any, CompState> {
});
}

async createUser() {
async createTenant() {
try {
if (this.state.email && this.state.username && this.state.password && this.state.confirm_password) {
const user: IUser = {
username: this.state.username,
email: this.state.email,
password: this.state.password
if (this.state.edge_interface_name && this.state.description) {
const tenant: ITenant = {
description: this.state.description,
edge_interface_name: this.state.edge_interface_name
};
const registerPromise = UserApi.createUser(user);
const registerPromise = TenantApi.create(tenant);
this.registerPromise(registerPromise);
const responseCreate: any = await registerPromise;
if (responseCreate && responseCreate.status === 200 && responseCreate.data) {
if (responseCreate.data.message === 'Creation successfully done')
if (responseCreate.data.message === 'Tenant successfully created') {
this.props.dispatchNotification('Creation successfully done', 'success', Math.random());
if (responseCreate.data.message === 'User already exists.')
this.props.dispatchNotification(`User already exists.`, 'warning', Math.random());
} else if (responseCreate.data.message === 'Tenant already exists') {
this.props.dispatchNotification('Creation successfully done', 'warning', Math.random());
} else {
this.props.dispatchNotification(`Error creation.`, 'error', Math.random());
}
}
} else {
this.props.dispatchNotification(`Missing Data`, 'warning', Math.random());
Expand All @@ -89,60 +88,39 @@ class TenantForm extends DNSBaseComponent<CompProps | any, CompState> {
<Segment raised>
<Card fluid centered>
<Card.Content>
<Card.Header className="headerHomePage">Create User</Card.Header>
<Card.Header className="headerHomePage">Create Tenant</Card.Header>
<Card.Description>

<Form size="small">
<Grid textAlign="center" className='loginForm'>
<Grid.Row width={12}>
<Input
placeholder="username"
name="username"
placeholder="edge interface name"
name="edge_interface_name"
type="text"
value={this.state.username}
value={this.state.edge_interface_name}
onChange={(event: any) => {
this.handleChange(event);
}}
/>
</Grid.Row>
<Grid.Row width={12}>
<Input
placeholder="email"
name="email"
placeholder="description"
name="description"
type="text"
value={this.state.email}
onChange={(event: any) => {
this.handleChange(event);
}}
/>
</Grid.Row>
<Grid.Row width={12}>
<Input
placeholder="password"
name="password"
type="password"
value={this.state.password}
onChange={(event: any) => {
this.handleChange(event);
}}
/>
</Grid.Row>
<Grid.Row width={12}>
<Input
placeholder="confirm password"
name="confirm_password"
type="password"
value={this.state.confirm_password}
value={this.state.description}
onChange={(event: any) => {
this.handleChange(event);
}}
/>
</Grid.Row>

<Button
type='submit'
className="buttonLoginForm"
onClick={(event: any) => {
this.createUser(event);
this.createTenant();
}}
>Crea
</Button>
Expand Down
14 changes: 7 additions & 7 deletions frontend/src/components/tables/tenantTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class TenantTable extends DNSBaseComponent<CompProps | any, CompState> {
paginationOpts: {
activePage: 1,
totalPages: 1,
itemPerPage: Constants.pagination.itemPerPage
itemsPerPage: Constants.pagination.itemsPerPage
},
search: '',
selectedTenant: {},
Expand Down Expand Up @@ -113,16 +113,16 @@ class TenantTable extends DNSBaseComponent<CompProps | any, CompState> {
const options = search ? {
activePage: 1,
totalPages: 1,
itemPerPage: Constants.pagination.itemPerPage
itemsPerPage: Constants.pagination.itemsPerPage
} : this.state.paginationOpts;
const getTenantsPromise = TenantApi.getAll(options, searchValue);
this.registerPromise(getTenantsPromise);
const tenantsResponse: any = await getTenantsPromise;
const newSearch = search ? this.state.search : "";
if (tenantsResponse && tenantsResponse.data && tenantsResponse.data.payload) {
if (tenantsResponse && tenantsResponse.data && tenantsResponse.data.payload.tenants && tenantsResponse.data.payload.options) {
_.defer(() => {
this.setState({
tenants: tenantsResponse.data.payload,
tenants: tenantsResponse.data.payload.tenants,
paginationOpts: tenantsResponse.data.payload.options,
search: newSearch,
loading: false
Expand All @@ -135,7 +135,7 @@ class TenantTable extends DNSBaseComponent<CompProps | any, CompState> {
paginationOpts: {
activePage: 1,
totalPages: 1,
itemPerPage: Constants.pagination.itemPerPage
itemsPerPage: Constants.pagination.itemsPerPage
},
search: newSearch,
loading: false
Expand Down Expand Up @@ -228,15 +228,15 @@ class TenantTable extends DNSBaseComponent<CompProps | any, CompState> {
<Table.Footer fullWidth>
<Table.Row>
<Table.HeaderCell colSpan='1'>
{/* <Pagination
<Pagination
activePage={this.state.paginationOpts.activePage}
boundaryRange={1}
size='mini'
onPageChange={(event: any, { activePage }) => {
this.handlePaginationChange(event, { activePage });
}}
totalPages={this.state.paginationOpts.totalPages}
/> */}
/>
</Table.HeaderCell>

<Table.HeaderCell colSpan='1' className="buttonCell">
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ export const jwt = {
};

export const pagination = {
itemPerPage: 25
itemsPerPage: 25
};

10 changes: 10 additions & 0 deletions frontend/src/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import _ from 'lodash';
import LoginPage from './components/pages/loginPage';
import DNSForm from './components/forms/DNSForm';
import HomePage from './components/pages/homePage';
import TenantForm from './components/forms/tenantForm';

interface ApplicationRouteGroup {
name: string;
Expand Down Expand Up @@ -41,6 +42,15 @@ export const appRoutes: ApplicationRouteGroup[] = [
menuLabel: 'home',
showTopbar: true
},
{
path: '/tenant/new',
name: 'tenant',
restricted: false,
exact: true,
component: TenantForm,
menuLabel: 'Tenant',
showTopbar: true
},
]
},
{
Expand Down

0 comments on commit 98f845e

Please sign in to comment.