let {Switch,Route,useHistory,useParams,useRouteMatch,useLocation } = ReactRouterDOM;
const {Container,Row,Col,Table,Form,Image,OverlayTrigger,Tooltip,Button} = ReactBootstrap;
const _functions = FunctionsApp()
function Home({state,updateState}) {
const {arrCategoriesProducts} = state;
let { id } = useParams();
const history = useHistory();
return (
{ history.push('/productos/5f6cabb395fde'); }} style={{ position: 'relative', textAlign: 'center', marginBottom: 10, }}>
RES
{ history.push('/productos/5f6cabdd4bc14'); }} style={{ position: 'relative', textAlign: 'center', marginBottom: 10, }}>
CERDO
{ history.push('/productos/5f6cabe442592'); }} style={{ position: 'relative', textAlign: 'center', marginBottom: 10, }}>
POLLO
{ history.push('/productos/5f6cac034c14f'); }} style={{ position: 'relative', textAlign: 'center', marginBottom: 10, }}>
ABARROTES
);
}
function ProductosList({state,updateState}) {
const { arrCategoriesProducts, } = state;
let { id_categoria } = useParams();
const history = useHistory();
let arrItem, indexItem = -1;
arrCategoriesProducts.map((t, e) => {
if(t.id_categoria === id_categoria) {
indexItem = e;
arrItem = t;
}
})
return (
{
( arrItem.productos.length > 0 )
?
:
{ history.push('/') }}>No se encontraron productos. Haz clic para regresar
}
);
}
function Categorias({state,updateState}){
let { path, url } = useRouteMatch();
return(
)
}
function ViewCategoria({state,updateState}) {
let { topicId } = useParams();
const {arrCategoriesProducts} = state;
return (
{/*
*/}
{
(arrCategoriesProducts.length>0) ?
arrCategoriesProducts.map((category,index) => (
(category.id_categoria==topicId) ?
:
null
))
:
null
}
);
}
function Carrito({state,updateState}){
let { arrCategoriesProducts, carritoProductos, porcDesc, } = state
if(carritoProductos.length === 0) {
window.location = '/'
}
let total = 0, descuento = porcDesc;
carritoProductos.map((t0,e0) => {
total += t0.cantidad * t0.precio_venta
});
return(
Carrito
PRODUCTO
PRECIO
CANTIDAD
TOTAL
{
carritoProductos.map((t,e) => (
{t.nombre}
${number_format(t.precio_venta)}
{
if(carritoProductos[e].cantidad > 1) {
carritoProductos[e].cantidad = (carritoProductos[e].cantidad - 1)
updateState({carritoProductos})
}
}}
>-
{t.cantidad}
{
carritoProductos[e].cantidad = (carritoProductos[e].cantidad + 1)
updateState({carritoProductos})
}}
>+
{
let newArr = []
arrCategoriesProducts[t.indexCategoria].productos[t.index].active = false
carritoProductos.map((t0,e0) => {
if(e0 != e)
newArr.push(t0)
})
carritoProductos = newArr
updateState({carritoProductos})
}}
className="mb-0 pt-3 pb-3 btn w_c_1">ELIMINAR
${number_format(t.cantidad * t.precio_venta)}
))
}
SUBTOTAL: ${
number_format(total)
}
DESCUENTO: ${number_format(total * descuento)}
TOTAL: ${number_format( total - (total * descuento) )}
Los gatos de envio se calculan durante el pago
Aplicar un código de descuento
{
state.porcDesc > 0 ? (
CÓDIGO: {state.code}
{ updateState({ porcDesc: 0, }) }}>Remover
) : (
{ updateState({ code: e.target.value, }); }} placeholder={'Ingresa un código aquí.'} />
{ onValidateCode(state, updateState) }}>Validar
)
}
Pagar
Seguir Comprando
)
}
function onValidateCode(state,updateState) {
let { code } = state
if(!code || code === '') {
alert('No haz ingresado un código.')
return false
} else {
_functions.fetch('validarCodePromocion', {
code,
}, (res) => {
console.log(res)
if(res.stat) {
if(!res.response.status) {
alert('El código introducido no fue encontrado o ya expiró.')
return false
} else {
updateState({ porcDesc: res.response.descuento / 100, })
}
}
})
}
}
function Pago({state,updateState}){
let {stepPagos,addCard,arrDatos, carritoProductos, loginNumber, proccessPayment, porcDesc, } = state;
let total = 0, descuento = porcDesc;
if(carritoProductos.length === 0) {
window.location = '/'
}
carritoProductos.map((t0,e0) => {
total += t0.cantidad * t0.precio_venta
});
return(
{`Paso ${stepPagos} de 4`}
{
stepPagos==='validateCode' ?
'Validando mi usuario'
: stepPagos===1 ?
'Información de Contacto'
: stepPagos === 2 ?
'Datos de entrega'
: stepPagos === 3 ?
'Selecciona el método de pago'
:
null
}
{
stepPagos===1 ?
¿Ya estás registrado?
Inicia sesión con tu teléfono
:
null
}
{
stepPagos==='validateCode' ?
Confirma el código enviado
:
null
}
{
stepPagos === 'validateCode' ?
Se te ha enviado un código a tu whatsapp }
>
Código
{
updateState({loginCode: e.target.value})
}
}
/>
{
getValidateCode(state, updateState)
}
}
>Confirmar código
: stepPagos===1?
Agrega tu whatsapp }
>
Teléfono
{
updateState({ loginNumber: e.target.value, })
}
}
/>
{
getValidateLogin(state, updateState)
}
}
>Iniciar sesión
{
updateState({
stepPagos:2
})
}
}
>Soy nuevo
: stepPagos === 2 ?
Agrega tu nombre }
>
Nombre
{
console.log(e.target.oldValue)
}
}
/>
Agrega tus apellidos }
>
Apellidos
{
console.log(e.target.oldValue)
}
}
/>
Agrega tu dirección }
>
Dirección
{
console.log(e.target.oldValue)
}
}
/>
Agrega tu ciudad }
>
Ciudad
{
console.log(e.target.oldValue)
}
}
/>
Agrega tu estado }
>
Estado
{
console.log(e.target.oldValue)
}
}
/>
Agrega tu código postal }
>
CP
{
console.log(e.target.oldValue)
}
}
/>
Agrega tu teléfono }
>
Teléfono
{
console.log(e.target.oldValue)
}
}
/>
{
updateState({
stepPagos:3
})
}
}
>{(state.submitForm) ? 'Guardando datos...' : 'IR AL PAGO' }
: stepPagos === 3 ?
addCard === 0 ?
No tienes
tarjetas registradas
Pero puedes agregar una
{
updateState({
addCard:2
})
}
}
>
Agregar tarjeta
o utiliza otros métodos de pago
: addCard === 1 ?
: addCard === 2 ?
:
null
: stepPagos === 4 ?
{
(!proccessPayment) ?
Tu pago se
está procesando...
:
}
:
null
}
{
carritoProductos.map((t,e) => (
${number_format(t.cantidad * t.precio_venta)}
))
}
${number_format( (total - (total * descuento) + 100) )}
{/*Display only in mobile*/}
Total
${number_format( total - (total * descuento) )}
)
function procesarPago(state, updateState) {
//Primero pasa por el procesar pago
updateState({ stepPagos: 4, proccessPayment: false, })
const $form = document.getElementById('ws_payment_conekta')
Conekta.Token.create($form,
({id, object, used}) => {
if(object === 'token') {
_functions.fetch('setRegisterOrder', {
token_conekta: id,
arrDatos: state.arrDatos,
code: 'DESCUENTOCITA',
arrProductos: carritoProductos,
}, (res) => {
if(res.stat) {
setTimeout(() => {
updateState({ proccessPayment: true, id_order: res.response.id_order, })
}, 1000)
}
})
}
},
(err) => {
if(err.object === 'error') {
alert(`Error: ${err.message_to_purchaser}`)
updateState({
stepPagos: 3,
proccessPayment: false,
})
return false
}
});
}
function getValidateLogin(state, updateState) {
const { loginNumber } = state
_functions.fetch('existPhonePatient', { phone: loginNumber, }, (res) => {
const { response } = res
if(res.stat) {
if( !response.status ) {
alert( 'Lo sentimos, este número de teléfono no se encuentra en los registros.' )
return false
}
updateState({ loginStep: 0, })
setTimeout(() => {
updateState({ stepPagos: 'validateCode', loginToken: response.token, })
}, 1500)
}
})
}
function getValidateCode(state, updateState) {
const { loginToken, loginCode, loginIntent, } = state
_functions.fetch('validateCodeLogin', { token: loginToken, code: loginCode, }, (res) => {
const { response } = res
if(res.stat) {
if( !response.status ) {
if(loginIntent >= 3) {
alert( `Lo sentimos, no pudiste autentificar tu cuenta.\nSerás redireccionado al inicio` )
window.location = `https://tienda.nutriologasadett.com`;
} else {
alert( `Lo sentimos, el código introducido no es válido.\nIntento: ${loginIntent} de 3.` )
}
updateState({ loginIntent: (loginIntent + 1) })
return false
} else {
//Si es exitoso le precargamos su nombre.
if(response.tarjeta.length > 0)
arrDatos = { ...arrDatos, ...response.tarjeta[0] };
if(response.patient.length > 0)
arrDatos = { ...arrDatos, ...response.patient[0] };
updateState({ arrDatos, stepPagos: 3, addCard: 2, })
}
}
})
}
function handleChange(e){
let { name, value } = e.target;
if (
name === "numero" ||
name === "telefono" ||
name === "cvc" ||
name === "month" ||
name === "year"
) {
value = value.replace(/\D/, "");
}
arrDatos = {...arrDatos, [name]: value}
updateState({ arrDatos })
}
}
//Barra de navegación principal
function NavbarTop({state,updateState}){
const {Image,Nav,NavDropdown} = ReactBootstrap;
const { showMenu, carritoProductos, } = state;
let { path, url } = useRouteMatch();
return(
{/*
Login
*/}
0 ? '/carrito' : '/'}`} className="nav-link">
{
}
}
/>
{carritoProductos.length}
{
(showMenu) ?
{ updateState({ showMenu:false }) }} >
:
{ updateState({ showMenu:true }) }} >
}
0 ? '/carrito' : '/'}`} className="nav-link">
{carritoProductos.length}
)
}
// Anuncio de descuentos
function Anouncement({state,updateState}){
return(
)
}
//Carousel de imagenes
function Carousel({state,updateState}){
var Carousel = ReactBootstrap.Carousel;
return(
)
}
//Sección Categorias
function CategoriesList({state,updateState,organizador=false}){
var Container = ReactBootstrap.Container;
var Row = ReactBootstrap.Row;
var Col = ReactBootstrap.Col;
var Form = ReactBootstrap.Form;
return(
{
(organizador) ?
Organizar por:
Más vendidos
Alfabéticamente, A-Z
Alfabéticamente, Z-A
Precio mayor a menor
Precio menor a mayor
:
Categorías
{
state.arrCategoriesList.map((category,index) => (
))
}
}
)
}
//Sección Categoria
function Category({state,updateState,title,productos, indexCategoria}) {
var Container = ReactBootstrap.Container;
var Row = ReactBootstrap.Row;
var Col = ReactBootstrap.Col;
return(
{title}
{
productos.map((producto,index) => (
{producto.nombre}
$ {producto.precio_venta}
{ onAddProductToCarrito(state, updateState, indexCategoria, index); }}
className={`btn ${producto.active ? 'btn-secondary' : 'ws_button'}`}>{ producto.active ? 'Quitar del carrito' : 'Agregar al carrito' }
))
}
)
}
function onAddProductToCarrito(state, updateState, indexCategoria, index) {
let { arrCategoriesProducts, carritoProductos, } = state;
if(!arrCategoriesProducts[indexCategoria].productos[index].active) {
//Se agrega
arrCategoriesProducts[indexCategoria].productos[index].active = true
arrCategoriesProducts[indexCategoria].productos[index].cantidad = 1;
carritoProductos.push({
...arrCategoriesProducts[indexCategoria].productos[index],
indexCategoria,
index,
})
updateState({
carritoProductos,
arrCategoriesProducts,
})
} else {
let newArr = []
arrCategoriesProducts[indexCategoria].productos[index].active = false
carritoProductos.map((t,e) => {
if(t.id_producto !== arrCategoriesProducts[indexCategoria].productos[index].id_producto)
newArr.push(t)
})
carritoProductos = newArr;
updateState({
carritoProductos,
arrCategoriesProducts,
})
}
}
function Footer({state,updateState}){
const {Container,Row,Col,Image} = ReactBootstrap;
return(
©2021, Carnicerías Hermanos Gonzalez, All Rights Reserved
Powered by W Soft
)
}
function number_format(number, decimals, decPoint, thousandsSep) {
number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number
var prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
var s = ''
var toFixedFix = function (n, prec) {
var k = Math.pow(10, prec)
return '' + (Math.round(n * k) / k)
.toFixed(prec)
}
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}