Commit a1127cde authored by Juorder Antonio's avatar Juorder Antonio

se modifica la vista de ventas, para solo hacer solicitudes de compras de...

se modifica la vista de ventas, para solo hacer solicitudes de compras de casillas al area de ventas
parent f38a5fb5
import React from 'react'; import React from 'react';
import PageInfo from '../page_info.jsx'; import PageInfo from '../page_info.jsx';
import Panel from '../panel.jsx'; import Panel from '../panel.jsx';
import moment from 'moment';
import currencyFormatter from 'currency-formatter';
import EventStore from '../../stores/event_store.jsx';
import UserStore from '../../stores/user_store.jsx'; import UserStore from '../../stores/user_store.jsx';
import * as GlobalActions from '../../action_creators/global_actions.jsx';
import * as Utils from '../../utils/utils.jsx'; import * as Utils from '../../utils/utils.jsx';
import * as Client from '../../utils/client.jsx'; import * as Client from '../../utils/client.jsx';
import sweetAlert from 'sweetalert';
import ZimbraStore from '../../stores/zimbra_store.jsx';
export default class SalesForm extends React.Component { export default class SalesForm extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.handleSetNumbersOfMailboxes = this.handleSetNumbersOfMailboxes.bind(this); this.buildPurchase = this.buildPurchase.bind(this);
this.getPrices = this.getPrices.bind(this);
this.onlyNumber = this.onlyNumber.bind(this);
this.confirmShipping = this.confirmShipping.bind(this); this.confirmShipping = this.confirmShipping.bind(this);
this.getDomainInfo = this.getDomainInfo.bind(this);
this.tryAgain = this.tryAgain.bind(this);
this.cos = Utils.getEnabledPlansByCos(ZimbraStore.getAllCos());
this.plans = window.manager_config.plans;
this.keys = Object.keys(this.cos);
this.sales = {};
this.isNAN = false;
this.currency = window.manager_config.invoiceAPI.currency;
const precision = this.currency === 'CLP' ? 0 : 2;
this.currencyParams = {code: this.currency, symbol: '', precision};
this.state = { const {name, attrs} = UserStore.getCurrentUser();
loading: true, const {displayName, cn, sn} = attrs._attrs;
errorAjax: false,
disabled: false
};
}
confirmShipping(e) { const state = {
e.preventDefault(); disabled: true,
const plans = []; purchase: {},
const {domain} = this.state; user: {
const domainId = domain.id; email: name,
const companyId = domain.attrs.businessCategory; fullname: this.buildFullName(displayName, cn, sn)
const adminEmail = UserStore.getCurrentUser().name; },
const items = {}; domainId: props.params.domainId
const data = {
domainId,
companyId,
adminEmail,
upgrade: false,
currency: this.currency
}; };
this.keys.forEach((plan) => { this.avoidPlans = ['archiving', 'default'];
if (this.sales[plan] && this.sales[plan].quantity && this.sales[plan].quantity > 0) { this.plans = window.manager_config.plans;
items[plan] = this.sales[plan]; this.messageCode = window.manager_config.messageCode;
items[plan].type = 'Producto';
plans.push(`${Utils.titleCase(plan)} : <strong>${this.sales[plan].quantity}</strong>`);
}
});
if (plans.length < 1) {
return EventStore.emitToast({
type: 'error',
title: 'Compra Casillas',
body: 'Debe indicar cuantas casillas desea comprar.',
options: {
timeOut: 4000,
extendedTimeOut: 2000,
closeButton: true
}
});
}
const content = plans.join(', '); this.mailboxes = Object.keys(this.plans).filter((plan) => {
const total = `${this.refs.total.value} ${this.currency}`; const isValidPlan = !this.avoidPlans.includes(plan);
const options = {
title: 'Confirmación',
text: `Esta seguro de realizar la compra de ${content} por un total de <strong>${total}</strong>`,
html: true,
confirmButtonText: 'Si, compraré',
confirmButtonColor: '#4EA5EC',
showLoaderOnConfirm: true,
closeOnConfirm: false
};
Utils.alertToBuy((isConfirmed) => { if (isValidPlan) {
if (isConfirmed) { state.purchase[plan] = 0;
data.items = items;
const requestObject = JSON.stringify(data);
Client.makeSale(requestObject, () => {
Utils.alertToBuy((isConfirmed) => {
if (isConfirmed) {
Utils.handleLink(null, `/domains/${domainId}/mailboxes/new`);
}
}, {
title: 'Compra de Casillas',
text: 'Su compra se ha realizado con éxito.',
showCancelButton: false,
confirmButtonColor: '#4EA5EC',
confirmButtonText: 'Muy bien',
type: 'success'
});
}, (error) => {
Utils.alertToBuy(() => {
return null;
}, {
title: 'Error',
text: error.message || error.error.message || 'Ha ocurrido un error desconocido.',
showCancelButton: false,
confirmButtonColor: '#4EA5EC',
confirmButtonText: 'Entiendo',
type: 'error',
closeOnConfirm: true
});
});
} }
}, options);
}
getPrices() {
const {domainId} = this.props.params || this.state.domain.name || null;
const attrs = this.state.domain.attrs;
const {zimbraCreateTimestamp} = attrs;
const {businessCategory} = attrs;
const createdDate = moment(zimbraCreateTimestamp, ['YYYYDDMM', 'YYYY-DD-MM', 'DD-MM-YYYY', 'YYYY-MM-DD']); return isValidPlan;
if (!createdDate.isValid()) {
this.setState({
disabled: true,
loading: false,
errorAjax: true
}); });
return EventStore.emitToast({ this.state = state;
type: 'error',
title: 'Compras - Precios',
body: 'Ha ocurrido un error al obtener su fecha de creación de dominio.',
options: {
timeOut: 4000,
extendedTimeOut: 2000,
closeButton: true
}
});
} }
const data = { onKeyupInput(event, label) {
domainId, const value = event.target.value;
domainCreatedDate: createdDate.format('MM/DD/Y'),
anualRenovation: true,
companyId: businessCategory,
type: 'standar',
currency: this.currency
};
Client.getPrices(data, (success) => {
this.setState({
loading: false,
disabled: false,
prices: success.result.prices,
isAnual: success.result.isAnual,
description: success.result.isAnual ? success.result.description : null
});
}, (error) => {
this.setState({
errorAjax: true,
loading: false
});
return EventStore.emitToast({ this.checkAmount(label, value);
type: 'error',
title: 'Compras - Precios',
body: error.message || error.error.message || 'Ha ocurrido un error al intentar obtener los precios, vuelva a intentarlo por favor.',
options: {
timeOut: 4000,
extendedTimeOut: 2000,
closeButton: true
} }
});
});
}
tryAgain(e) {
e.preventDefault();
this.setState({ buildFullName(displayName, cn, sn) {
loading: true, const fullname = displayName && displayName.trim() !== '' ? displayName : `${cn} ${sn}`;
errorAjax: false
});
this.getPrices(); return fullname;
} }
getDomainInfo() { checkAmount(label, _value) {
const {domainId} = this.props.params; const value = _value || 0;
const state = this.state;
Client.getDomain(domainId, (res, err) => { const purchase = state.purchase;
if (err) { const isEnabled = this.mailboxes.some((plan) => {
return Utils.alertToBuy(() => { const planAmount = plan === label ? value : purchase[plan];
return null; return planAmount > 0;
}, {
title: 'Error',
text: err.message || err.error.message || 'Ha ocurrido un error desconocido, cuando se recuperaba la información del dominio.',
showCancelButton: false,
confirmButtonColor: '#4EA5EC',
confirmButtonText: 'Entiendo',
type: 'error',
closeOnConfirm: true
}); });
}
this.setState({ this.setState({
domain: res disabled: !isEnabled,
}); purchase: {...purchase, [label]: parseInt(value, 10)}
return this.getPrices();
}); });
} }
componentDidMount() { onKeydownInput(event) {
GlobalActions.emitEndLoading(); const keycode = event.keyCode || event.which;
this.getDomainInfo(); const allows = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
if (allows.includes(keycode)) {
return true;
} }
handleSetNumbersOfMailboxes(e, id) { event.preventDefault();
if (this.isNAN) {
e.preventDefault();
return null; return null;
} }
const amount = e.target.value.trim(); buildPurchase(purchase) {
let totalPrice = 0; const plans = this.plans;
let description = 'Nuevas Casillas '; const content = [];
this.mailboxes.reduce((last, current) => {
this.keys.forEach((plan) => { const quantity = purchase[current];
if (this.cos[plan] === id) { if (quantity > 0) {
const price = this.state.prices[plan]; const plan = plans[current];
const size = amount.length > 0 ? parseInt(amount, 10) : 0; const label = quantity > 1 ? 'casillas' : 'casilla';
const total = size ? size * price : size; last.push(`${quantity} ${label} ${plan.label}`);
const totalFormatted = total ? currencyFormatter.format(total, this.currencyParams) : total;
this.refs[`${plan}-total`].value = totalFormatted;
description += Utils.titleCase(plan);
this.sales[plan] = {
quantity: size,
description,
price,
id,
total
};
} }
if (this.sales[plan] && this.sales[plan].total && this.sales[plan].total > 0) { return last;
totalPrice += this.sales[plan].total; }, content);
return content;
} }
});
const currentTotal = totalPrice ? currencyFormatter.format(totalPrice, this.currencyParams) : totalPrice; transformToHTML(content) {
this.refs.total.value = currentTotal; const list = content.join('</strong>, <strong>');
return `<p><strong>${list}</strong></p>`;
} }
onlyNumber(e) { confirmShipping(e) {
const key = e.keyCode;
const forbidden = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 9, 37, 39];
this.isNAN = false;
if (!(forbidden.indexOf(key) > -1)) {
this.isNAN = true;
e.preventDefault(); e.preventDefault();
return null; const {purchase, user, domainId} = this.state;
} const content = this.transformToHTML(this.buildPurchase(purchase));
} let data = {
purchase,
render() { user: user.email,
const plans = this.cos; fullname: user.fullname
const configPlans = this.plans; };
const keysPlans = this.keys; const options = {
let form = null; title: 'Confirmación',
let actions; text: `Esta seguro de realizar la compra de ${content}`,
const buttons = []; html: true,
const {description, disabled} = this.state; confirmButtonText: 'Si, compraré',
let descriptionText; confirmButtonColor: '#4EA5EC',
showLoaderOnConfirm: true,
if (description) { closeOnConfirm: false
descriptionText = ( };
<div
key='desc-key'
className='alert alert-info margin-bottom'
>
<span
className='glyphicon glyphicon glyphicon-question-sign'
aria-hidden='true'
></span>
<span className='sr-only'>Info:</span>
{description}
</div>
);
}
if (this.state.errorAjax) { Utils.alertToBuy((isConfirmed) => {
form = ( if (isConfirmed) {
<div Client.getDomain(domainId, (domain, err) => {
className='text-center' if (err) {
key={'errorajax-loading'} return sweetAlert('Error', 'El Dominio no existe.', 'error');
>
<i
className='fa fa-refresh fa-4x fa-fw pointer'
onClick={this.tryAgain}
>
</i>
<p>{'Intentarlo de nuevo'}</p>
</div>
);
} }
if (this.state.isAnual) { const {name} = domain;
buttons.push( data.domain = name;
{ Client.requestMailboxes(data, (response) => {
label: 'Anual', const text = this.messageCode[response.messageCode];
props: { sweetAlert('Compra éxitosa', text, 'success');
className: 'btn btn-success btn-xs' }, (error) => {
} const text = this.messageCode[error.messageCode];
} sweetAlert('Error', text, 'error');
); });
} else { });
buttons.push(
{
label: 'Mensual',
props: {
className: 'btn btn-info btn-xs'
}
}
);
} }
}, options);
if (this.state.loading) {
form = (
<div
className='text-center'
key={'prices-loading'}
>
<i className='fa fa-spinner fa-spin fa-4x fa-fw'></i>
<p>{'Cargando Precios...'}</p>
</div>
);
} }
if (!this.state.loading && this.state.prices) { renderInputs() {
const prices = this.state.prices; const {purchase} = this.state;
const rows = keysPlans.map((plan) => { return this.mailboxes.map((input, index) => {
const cosId = plans[plan]; const plan = this.plans[input];
const salesArray = configPlans[plan].sales; const value = purchase[input];
const fields = salesArray.map((field, index) => {
const label = field.label || `Casillas ${Utils.titleCase(plan)}`;
const price = field.hasPrice ? currencyFormatter.format(prices[plan], this.currencyParams) : '';
const myref = field.ref ? {ref: `${plan}-${field.ref}`} : {};
return ( return (
<div <div
key={`sale-input-${plan}-${index}`} key={`sale-input-${plan.label}-${index}`}
className='col-xs-4' className='col-xs-4'
> >
<div className='form-group'> <div className='form-group'>
<div className='input-group'> <div className='input-group'>
<div className='input-group-addon'>{label}</div> <div className='input-group-addon'>{`Casilla ${plan.label}`}</div>
<input <input
type='text' type='text'
className='form-control' className='form-control'
disabled={field.disabled} defaultValue={value}
defaultValue={price} onKeyUp={(event) => this.onKeyupInput(event, input)}
{...myref} onKeyDown={this.onKeydownInput}
onKeyUp={(e) => {
this.handleSetNumbersOfMailboxes(e, cosId);
}}
onKeyDown={this.onlyNumber}
/> />
</div> </div>
</div> </div>
</div> </div>
); );
}); });
}
render() {
const {disabled} = this.state;
return ( return (
<div <div>
key={`row-fields-${plan}`} <PageInfo
className='row' titlePage='Compras'
descriptionPage='Comprar casillas'
/>
<div className='content animate-panel'>
<div className='row'>
<div className='col-md-12 central-content'>
<Panel
hasHeader={true}
title={'Selecciona la cantidad de casillas que deseas comprar.'}
> >
{fields}
</div>
);
});
form = (
<form key='form-container'> <form key='form-container'>
{rows}
<div className='row'> <div className='row'>
<div className='col-xs-4 pull-right'> {this.renderInputs()}
<div className='form-group'>
<div className='input-group'>
<div className='input-group-addon'>Total</div>
<input
type='text'
disabled={true}
className='form-control'
ref='total'
/>
<div className='input-group-addon'>{this.currency}</div>
</div>
</div> </div>
</div>
</div>
</form>
);
actions = (
<div <div
className='row' className='row'
key='actions-container'
> >
<div className='col-xs-12 text-right'> <div className='col-xs-12 text-right'>
<button className='btn btn-default'>Cancelar</button>
<button <button
disabled={disabled} disabled={disabled}
className='btn btn-info' className='btn btn-info'
...@@ -428,22 +200,8 @@ export default class SalesForm extends React.Component { ...@@ -428,22 +200,8 @@ export default class SalesForm extends React.Component {
>Comprar</button> >Comprar</button>
</div> </div>
</div> </div>
); </form>
} </Panel>
return (
<div>
<PageInfo
titlePage='Compras'
descriptionPage='Comprar casillas'
/>
<div className='content animate-panel'>
<div className='row'>
<div className='col-md-12 central-content'>
<Panel
btnsHeader={buttons}
children={[descriptionText, form, actions]}
/>
</div> </div>
</div> </div>
</div> </div>
......
...@@ -75,7 +75,7 @@ function initZimbra() { ...@@ -75,7 +75,7 @@ function initZimbra() {
export function getClientConfig(success, error) { export function getClientConfig(success, error) {
return $.ajax({ return $.ajax({
url: 'https://manager-api.zboxapp.com/parse/functions/getConfigManager', url: 'https://manager.zboxapp.com/ventas_api/parse/functions/getConfigManager',
//url: './config/config.json', //url: './config/config.json',
dataType: 'json', dataType: 'json',
method: 'POST', method: 'POST',
...@@ -845,6 +845,30 @@ export function getPrices(data, success, error) { ...@@ -845,6 +845,30 @@ export function getPrices(data, success, error) {
}); });
} }
export function requestMailboxes(data, success, error) {
const appId = window.manager_config.salesAPI.appId;
const endpoints = window.manager_config.salesAPI;
const url = endpoints.base + endpoints.requestSale;
$.ajax({
url: url,
method: 'POST',
data: data,
contentType: 'application/json',
headers: {
'X-Parse-Application-Id': appId,
'X-Parse-REST-API-Key': 'master'
},
dataType: 'json',
success: function onSuccess(response) {
success(response);
},
error: function onError(err) {
error(err.responseJSON || err);
}
});
}
export function makeSale(data, success, error) { export function makeSale(data, success, error) {
const appId = window.manager_config.salesAPI.appId; const appId = window.manager_config.salesAPI.appId;
const endpoints = window.manager_config.salesAPI; const endpoints = window.manager_config.salesAPI;
......
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