text
stringlengths 7
3.69M
|
|---|
const ethereum_info = {
'weth_address' : '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
}
export default ethereum_info;
|
import { setPageCache } from '@/helpers/setPageCache'
import { getParsedCampaignQueryWithAttr } from '@/helpers/getParsedCampaignQueryWithAttr'
export default async function ({ app, store, route, error, res }) {
const pageType = 'campaign'
const url_key = route.fullPath.slice(1).split('?')[0]
const id = route.query.category_path || route.query.cat
const requestData = {
query: route.query,
params: {
url_key: url_key
},
pageType
}
try {
await store.dispatch('campaign/fetchCampaignPageData', url_key)
const { query } = store.state.campaign.campaignPageData
requestData.params.additionalQuery = getParsedCampaignQueryWithAttr(query, id)
await store.dispatch('products/fetchProducts', requestData)
id && await store.dispatch('category/fetchCategoryData', id)
store.commit('category/setStructuredData', { products: store.state.products.products })
setPageCache(res, 'LANDING', app.$device)
return {
page_type: pageType,
url_key,
title: store.state.campaign.campaignPageData.title
}
} catch (e) {
error(e.$nuxtPayload || { statusCode: 500, errorMessage: 'InternalError' })
}
}
|
describe('personal log', function() {
beforeEach(function() {
browser().navigateTo('../personalLog.html');
});
afterEach(function() {
clearCookies();
});
it('should create new logs and order them in reverse chronological order', function(){
//create first msg
input('newMsg').enter('my first message');
element('form input[type="submit"]').click();
expect(repeater('ul li').count()).toEqual(1);
expect(repeater('ul li').column('log.msg')).toEqual('my first message');
//create second msg
input('newMsg').enter('my second message');
element('form input[type="submit"]').click();
expect(repeater('ul li').count()).toEqual(2);
expect(repeater('ul li').column('log.msg')).toEqual(['my second message', 'my first message']);
});
it('should delete a log when user clicks on the related X link', function() {
//create first msg
input('newMsg').enter('my first message');
element('form input[type="submit"]').click();
//create second msg
input('newMsg').enter('my second message');
element('form input[type="submit"]').click();
expect(repeater('ul li').count()).toEqual(2);
element('ul li a:eq(1)').click();
expect(repeater('ul li').count()).toEqual(1);
expect(repeater('ul li').column('log.msg')).toEqual('my second message');
element('ul li a:eq(0)').click();
expect(repeater('ul li').count()).toEqual(0);
});
it('should delete all cookies when user clicks on "remove all" button', function() {
//create first msg
input('newMsg').enter('my first message');
element('form input[type="submit"]').click();
//create second msg
input('newMsg').enter('my second message');
element('form input[type="submit"]').click();
expect(repeater('ul li').count()).toEqual(2);
element('input[value="remove all"]').click();
expect(repeater('ul li').count()).toEqual(0);
});
it('should preserve logs over page reloads', function() {
input('newMsg').enter('my persistent message');
element('form input[type="submit"]').click();
expect(repeater('ul li').count()).toEqual(1);
browser().reload();
expect(repeater('ul li').column('log.msg')).toEqual('my persistent message');
expect(repeater('ul li').count()).toEqual(1);
});
});
/**
* DSL for deleting all cookies.
*/
angular.scenario.dsl('clearCookies', function() {
/**
* Deletes cookies by interacting with the cookie service within the application under test.
*/
return function() {
this.addFutureAction('clear all cookies', function($window, $document, done) {
var rootScope = $window.angular.element($document[0]).data('$scope'),
$cookies = rootScope.$service('$cookies'),
cookieName;
for (cookieName in $cookies) {
delete $cookies[cookieName];
}
rootScope.$eval();
done();
});
};
});
|
'use strict'
module.exports = {
NODE_ENV: '"production"',
API_HOST: '"http://api.yx_monitor.yunsee.cn"' //
}
|
'use strict';
describe('Service: igService', function () {
// load the service's module
beforeEach(module('postalyzerApp'));
// instantiate service
var igService;
beforeEach(inject(function (_igService_) {
igService = _igService_;
}));
it('should do something', function () {
expect(!!igService).toBe(true);
});
});
|
import React from "react";
import { Link } from "gatsby";
import { GatsbyImage } from "gatsby-plugin-image";
import * as classes from './Product.module.css';
const Product = (props) => {
const price = `${props.price}$`;
return (
<div className={classes.product}>
<div className={classes.product__imgContainer}>
<Link to={props.id}>
<GatsbyImage alt='Product' image={props.img} />
</Link>
</div>
<div className={classes.product__desc}>
<p className={classes.product__name}>{props.title}</p>
<p className={classes.product__price}>{price}</p>
</div>
</div>
);
}
export default Product;
|
function addPromise(a,b) {
return new Promise(function (resolve, reject) {
if (typeof a === 'number' && typeof b === 'number') {
resolve(a+b);
} else {
reject('You must supply two numbers');
}
});
}
addPromise(5, 5).then(
function (num) {
console.log('success', num);
},
function (err) {
console.log('error', err);
}
);
addPromise(2,'f').then(
function (num) {
console.log('success', num);
},
function (err) {
console.log('error', err);
}
);
addPromise().then(
function (num) {
console.log('success', num);
},
function (err) {
console.log('error', err);
}
);
|
import React from 'react';
import Drawer from '@material-ui/core/Drawer';
import Button from '@material-ui/core/Button';
import Cart from './Cart'
// export default function TemporaryDrawer() {
// const [state, setState] = React.useState({
// top: false,
// left: false,
// bottom: false,
// right: false,
// });
// const toggleDrawer = (anchor, open) => (event) => {
// if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
// return;
// }
// setState({ ...state, [anchor]: open });
// };
// const right = 'right'
// return (
// <div>
// <React.Fragment key={right}>
// <Button onClick={toggleDrawer(right, true)}>{right}</Button>
// <Drawer anchor={right} open={state[right]} onClose={toggleDrawer(right, false)}>
// <Cart></Cart>
// </Drawer>
// </React.Fragment>
// </div>
// );
// }
|
import React from 'react';
import Modal from 'react-modal';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
const customStyles = {
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
height: 'auto',
width: '250px',
backgroundColor: 'red',
color: 'white',
marginRight: '-50%',
transform: 'translate(-50%, -50%)'
}
};
// const previewImageStyles = {
// // height: '250px',
// // width: '250px',
// // marginTop: '30px',
// // border: '2px solid white'
// };
Modal.setAppElement('#root')
class UploadImageModal extends React.Component {
fileInputRef = null;
render() {
return (
<Modal
isOpen={this.props.modalIsOpen}
onRequestClose={() => { this.props.onClose(); }}
style={customStyles}
>
<div style={{ textAlign: "center" }} onClick={() => {
if (this.fileInputRef) {
this.fileInputRef.click();
}
}}>
<FontAwesomeIcon icon="file-upload" style={{ fontSize: '3em' }} />
<span style={{ fontSize: '2em', marginLeft: '20px' }}>Upload an image</span>
{
// this.props.newUploadPreview
// ? <img src={this.props.newUploadPreview} alt="" style={previewImageStyles} />
// : ''
}
</div>
<input
type="file"
style={{ display: 'none' }}
ref={(input) => {
this.fileInputRef = input;
}}
onChange={(event) => { this.handleChange(event); }} />
</Modal>
);
}
handleChange(event) {
const fileInput = event.target;
const file = fileInput.files[0];
const reader = new FileReader();
reader.addEventListener("load", () => {
const res = reader.result;
this.props.onFileRead && this.props.onFileRead(res);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
}
export default UploadImageModal;
|
import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Container from '@material-ui/core/Container'
import SectionHeader from '../SectionHeader'
import Grid from '@material-ui/core/Grid'
import Card from '@material-ui/core/Card'
import CardActions from '@material-ui/core/CardActions'
import CardContent from '@material-ui/core/CardContent'
import Button from '@material-ui/core/Button'
import Typography from '@material-ui/core/Typography'
import List from '@material-ui/core/List'
import CardHeader from '@material-ui/core/CardHeader'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import { Link } from 'gatsby'
const useStyles = makeStyles((theme) => ({
container: {
padding: theme.spacing(10, 2)
},
containerInner: {
padding: theme.spacing(0)
},
card: {
minWidth: 275,
backgroundColor: theme.palette.white.main,
padding: theme.spacing(0, 0, 4, 0),
boxShadow: '0px 2px 4px -1px rgba(0,0,0,0.2), ' +
'0px 4px 5px 0px rgba(0,0,0,0.14), ' +
'0px 1px 10px 0px rgba(0,0,0,0.12)'
},
cardHeader: {
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText,
textAlign: 'center'
},
cardContent: {
padding: theme.spacing(2, 1)
},
cardActions: {
display: 'flex',
justifyContent: 'center'
},
title: {
textAlign: 'center'
},
price: {
color: theme.palette.secondary.main,
fontSize: '4rem',
textAlign: 'center',
fontFamily: theme.typography.h1.fontFamily
},
list: {
marginBottom: 12
},
listItemText: {
textAlign: 'center',
fontSize: theme.typography.body1.fontSize
},
gridCenter: {
display: 'flex',
justifyContent: 'center',
alignSelf: 'center',
flexDirection: 'column',
width: '100%',
height: 'fit-content'
}
}))
const Pricing = ({ title, subTitle, lang, prices }) => {
const classes = useStyles()
const data = {
title: title,
subTitle: subTitle
}
return (
<Container maxWidth={false} className={classes.container}>
<SectionHeader data={data}/>
<Container maxWidth={'lg'} className={classes.containerInner}>
<Grid container spacing={4}>
{prices.edges.map(({ node }, index) => (
<Grid key={index} item xs={12} md={4} className={classes.gridCenter}>
<Card className={classes.card} variant="outlined" raised={true}>
{node.popular === true ? (
<CardHeader title={lang === 'de' ? 'Beliebte Wahl' : 'Popular Choice'}
className={classes.cardHeader}/>) : (<></>)}
<CardContent className={classes.cardContent}>
<Typography className={classes.title} variant={'h5'} component={'h2'}
color={'textPrimary'} gutterBottom>
{node.title}
</Typography>
<Typography component={'h3'} className={classes.price}>
{node.sessionPrice}€
</Typography>
<List component="ul" aria-label="full service included" className={classes.list}>
{node.included.map((item, index) => (
<ListItem key={index}>
<ListItemText
primary={
<Typography variant={'body2'} component={'p'} color={'textPrimary'}>
{item}
</Typography>
}
className={classes.listItemText}/>
</ListItem>
))}
</List>
</CardContent>
<CardActions className={classes.cardActions}>
<Button variant={'contained'} component={Link} color={'secondary'} size="small"
to={lang === 'de' ? `kontakt` : `contact`}
aria-label={'book this session.'}>{lang === 'de' ? `Kontakt aufnehmen` : `Contact me`}</Button>
</CardActions>
</Card>
</Grid>
))}
</Grid>
</Container>
</Container>
)
}
export default Pricing
|
let score1 = 0;
let score2 = 0;
function setup() {
rectMode(CENTER)
ball = new Ball();
p1 = new paddle();
p1.x=10
p2 = new paddle();
p2.x=390
createCanvas(400, 400);
}
function keyPressed() {
if(keyCode==65) {
p1.change_dir(-2)
}
if(keyCode==90) {
p1.change_dir(2)
}
if(keyCode==38) {
p2.change_dir(-2)
}
if(keyCode==40) {
p2.change_dir(2)
}
}
function draw() {
background(30);
fill("yellow")
line(200,0,200,height)
textSize(10);
text("Player 1",30,30)
text(score1,35,15)
text("Player 2",350,30)
text(score2,355,15)
p1.show()
p2.show()
p1.move()
p1.update()
p2.move()
p2.update()
ball.show()
ball.move()
ball.update()
//ResetTheBall
if(ball.x>=width)
{
score1++;
ball.reset()
}
if(ball.x<=0)
{
score2++;
ball.reset()
}
//CollisionUser
if(ball.x>=380 && ball.y<=(p2.y+50) && ball.y>=(p2.y-50)){
ball.vx *= -1;
}
//CollisionComputer
if(ball.x<=20 && ball.y<=(p1.y+50) && ball.y>=(p1.y-50)){
ball.vx *= -1;
}
}
|
class Calculator {
constructor(a, b) {
this.a = a;
this.b = b;
}
Plus() {
return (this.a + this.b);
}
Minus() {
return (this.a - this.b);
}
Multi() {
return (this.a * this.b);
}
Division() {
return (this.a / this.b);
}
Percent() {
return (this.a / 100) * this.b;
}
}
let btn = document.querySelectorAll('.operation');
btn.forEach((item) => {
item.addEventListener('click', function(event) {
event.preventDefault();
let form = document.querySelector('.formCalc'),
aNum = Number(form.querySelector('.first-num').value),
bNum = Number(form.querySelector('.second-num').value),
res = document.querySelector('.result');
if(aNum === 0 || bNum === 0) {
res.innerHTML = 'Зачем ноль?';
return false;
}
let Calc = new Calculator(aNum, bNum);
let map = new Map();
map.set('Plus', Calc.Plus());//******************
map.set('Minus', Calc.Minus());//******************
map.set('Multi', Calc.Multi());//****************** Не знаю зачем так замудренно и неоптимизированно сделал, может скучно было :)
map.set('Division', Calc.Division());//**********
map.set('Percent', Calc.Percent());//**********
res.innerHTML = map.get(String(this.dataset.operation));
});
});
|
import '../styles/wstyles.css';
const WeekView = ({ view, dayView }) => {
const month = new Date().getMonth();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
const today = new Date().getDay();
const todaysDate = new Date().getDate();
// Get Mondays Date
const getMon = () => {
if (today > 1) {
return todaysDate - (today - 1)
} else if (today < 1) {
return todaysDate + 1
} else if (today === 1) {
return todaysDate
}
}
// Get Tuesdays Date
const getTue = () => {
if (today > 2) {
return todaysDate - (today - 2)
} else if (today < 2) {
return todaysDate + (2 - today )
} else if (today === 2) {
return todaysDate
}
}
// Get Wedesdays Date
const getWed = () => {
if (today > 3) {
return todaysDate - (today - 3)
} else if (today < 3) {
return todaysDate + (3 - today )
} else if (today === 3) {
return todaysDate
}
}
// Get Thurs Date
const getThur = () => {
if (today > 4) {
return todaysDate - (today - 4)
} else if (today < 4) {
return todaysDate + (4 - today )
} else if (today === 4) {
return todaysDate
}
}
// Get Fridays Date
const getFri = () => {
if (today > 5) {
return todaysDate - (today - 5)
} else if (today < 5) {
return todaysDate + (5 - today )
} else if (today === 5) {
return todaysDate
}
}
// Get Saturdays Date
const getSat = () => {
if (today > 6) {
return todaysDate - (today - 6)
} else if (today < 6) {
return todaysDate + (6 - today )
} else if (today === 6) {
return todaysDate
}
}
// Get Sunday Date
const getSun = () => {
return getSat() + 1
}
return(
<div className={view ? 'w week-view' : 'd week-view' }>
<p>{ months[month] }</p>
<p>Mon <span>/{ getMon() }</span></p>
<p>Tue <span>/{ getTue() }</span></p>
<p>Wed <span>/{ getWed() }</span></p>
<p>Thur <span>/{ getThur() }</span></p>
<p>Fri <span>/{ getFri() }</span></p>
<p>Sat <span>/{ getSat() }</span></p>
<p>Sun <span>/{ getSun() }</span></p>
<svg onClick={() => {dayView()}} xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-arrow-left-short" viewBox="0 0 16 16">
<path fillRule="evenodd" d="M12 8a.5.5 0 0 1-.5.5H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5a.5.5 0 0 1 .5.5z"/>
</svg>
</div>
)
}
export default WeekView;
|
import React, { useState } from "react";
import { StyledPasswordResetForm } from "./PasswordResetForm.styled";
import Input from "../Input/Input";
import { StyledSubmitButton } from "../../styles/GlobalStyles";
import { updatePassword } from "../../actions/authActions";
import { connect } from "react-redux";
function PasswordResetForm(props) {
let [formState, setFormState] = useState({
password: "",
newPassword: "",
newPasswordConfirm: "",
});
let onInputChange = (e) => {
setFormState({
...formState,
[e.target.name]: e.target.value,
});
};
let handleFormSubmit = (e) => {
e.preventDefault();
props.updatePassword(formState);
};
return (
<StyledPasswordResetForm>
<form className="password-reset" onSubmit={handleFormSubmit}>
<Input
label="Current Password"
type="password"
name="password"
value={formState.password}
onInputChange={onInputChange}
placeholder="********"
/>
<Input
label="New Password"
type="password"
name="newPassword"
value={formState.newPassword}
onInputChange={onInputChange}
placeholder="********"
/>
<Input
label="New Password Confirm"
type="password"
name="newPasswordConfirm"
value={formState.newPasswordConfirm}
onInputChange={onInputChange}
placeholder="********"
/>
<div className="button-wrapper">
<StyledSubmitButton>
{props.loading ? "Updating...." : "Update Password"}
</StyledSubmitButton>
</div>
</form>
</StyledPasswordResetForm>
);
}
let mapStateToProps = (state) => {
return {
loading: state.authState.loading,
};
};
export default connect(mapStateToProps, { updatePassword })(PasswordResetForm);
|
angular.module('WeatherCtrl', [])
.controller('WeatherCtrl', function ($scope, $state, $ionicPopup, $cordovaGeolocation, WeathersService,
PlacesService, SettingFactory, LocationsService) {
var selectedCity = SettingFactory.getCity();
var result = PlacesService.all();
result.push({
id: -1,
name: 'Use my current location'
});
changeSelection(result, selectedCity);
$scope.places = result;
$scope.$on("settings-changed", function () {
loadData();
});
loadData();
$scope.changeLocation = function () {
$ionicPopup.show({
templateUrl: 'templates/tab-popup.html',
title: 'Please select a city to get displayed at your \'My City\' screen.',
scope: $scope,
buttons: [
{
text: '<b>OK</b>',
type: 'button-positive orange',
onTap: function (e) {
return true;
}
}
]
});
};
$scope.selectCity = function (city) {
if (city.id === -1) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
LocationsService.getLocation(position.coords.latitude, position.coords.longitude)
.then(function (response) {
var currentCity = {
name: response.city,
latitude: response.latt,
longitude: response.longt
};
SettingFactory.setCity(currentCity);
})
.catch(console.error);
}, function (err) {
console.log(err)
});
} else {
SettingFactory.setCity(city);
changeSelection($scope.places, city)
}
};
$scope.goToDetail = function () {
$state.go("tab.weather-detail");
};
function changeSelection(result, selectedCity) {
for (var index = 0; index < result.length; ++index) {
result[index].selected = selectedCity.id === result[index].id;
}
}
function loadData() {
WeathersService.dailyWeather().then(function (result) {
$scope.weathers = result.daily.data;
$scope.latitude = result.latitude;
$scope.longitude = result.longitude;
$scope.icon = result.daily.iconToShow;
$scope.cityName = SettingFactory.getCity().name;
});
}
});
|
import breakpoints from './breakpoints';
import colors from './colors';
import fonts from './fonts';
import space from './space';
import typography from './typography';
export default {
breakpoints,
colors,
fonts,
space,
typography,
};
|
/*
Create an array of people objects with first name, last name, and age, then write a
JavaScript program to display the first and last names of all the people.
Your function should take in an object and return the the values above.
*/
function personDetails(obj) {
obj.forEach((element) => {
let personName =
element.firstName + " " + element.lastName + " " + element.age;
console.log(personName);
});
}
let person = [
{ firstName: "Mike", lastName: "Core", age: 30 },
{ firstName: "Chris", lastName: "Moe", age: 10 },
{ firstName: "John", lastName: "Doe", age: 20 },
];
personDetails(person);
|
import {combineReducers} from 'redux';
import optimist from 'redux-optimist';
import {routerReducer as routing} from 'react-router-redux';
import jobs from '../ducks/jobs';
import auth from '../ducks/auth';
import landing from '../ducks/landing';
export default optimist(combineReducers({
routing,
jobs,
auth,
landing,
}));
|
'use strict';
angular.module('photoAlbum', ['ngRoute', 'core.photo'])
angular.
module('photoAlbum').
component('photoAlbum', {
templateUrl: 'components/photo-album/photo-album.template.html',
controller: ['$routeParams', 'Photo', '$window','$rootScope', '$scope',
function PhotoAlbumController($routeParams, Photo, $window, $rootScope, $scope ) {
var vm = this;
vm.photos= [];
console.log("PhotoAlbumController AlbumId="+$routeParams.albumId)
vm.albumId=$routeParams.albumId;
Photo.query(function(response){
vm.photos = response.filter((response)=> response.albumId==vm.albumId );
});
vm.openModal = function (id)
{
console.log("Photo clicked: "+id);
$rootScope.$broadcast('photoid', id);
$('#myModal').modal('show')
}
vm.back = function()
{
console.log("back button clicked");
$window.history.back();
}
}
]
});
|
import React from 'react';
import {storiesOf} from '@storybook/react';
import {withKnobs, color, number} from '@storybook/addon-knobs';
import {Explosion} from './exsplosion';
import {Current} from './current';
import {Demo} from './demo';
const defaultColor = '#ff1461';
const canvasWidth = 400;
const canvasHeight = 300;
const AnimationGroup = 'Animation';
const PositionGroup = 'Animation';
storiesOf('Canvas effects|Explosion', module)
.addDecorator(withKnobs)
.add('Default', () => (
<Demo
animation={Explosion}
args={{
color: color('Color', defaultColor, AnimationGroup),
duration: number('Duration', 1200, {range: true, min: 200, max: 10000, step: 100}, AnimationGroup),
distance: number('Distance', 32, {min: 0, max: 100}, AnimationGroup),
particles: number('Particles', 25, {min: 1, max: 100}, AnimationGroup),
x: number('X', canvasWidth / 2, {min: 0, max: canvasWidth}, PositionGroup),
y: number('Y', canvasHeight / 2, {min: 0, max: canvasHeight}, PositionGroup),
}}
/>
));
storiesOf('Canvas effects|Current', module)
.addDecorator(withKnobs)
.add('Default', () => (
<Demo
animation={Current}
args={{
color: color('Color', defaultColor, AnimationGroup),
x1: number('X1', canvasWidth / 8, {min: 0, max: canvasWidth}, PositionGroup),
y1: number('Y1', canvasHeight / 2, {min: 0, max: canvasHeight}, PositionGroup),
x2: number('X2', canvasWidth / 1.2, {min: 0, max: canvasWidth}, PositionGroup),
y2: number('Y2', canvasHeight / 2, {min: 0, max: canvasHeight}, PositionGroup),
}}
/>
));
|
/* global describe, it, expect, beforeEach */
import TypographyConfig, { fontStyles, makeTypographyStyle } from '.'
describe('TypographyConfig', () => {
let c
beforeEach(() => {
c = new TypographyConfig()
})
it('should return a TypographyConfig instance', () => {
expect(c instanceof TypographyConfig).toEqual(true)
})
it('should set the text direction based on the specified value', () => {
c = new TypographyConfig({ direction: 'rtl' })
expect(c.direction).toBe('rtl')
})
it('should default to left-to-right if the specified direction is invalid', () => {
c = new TypographyConfig({ direction: 'ujnbds' })
expect(c.direction).toBe('ltr')
})
it('should create a style for each style and heading level', () => {
expect(Object.keys(c.styles).sort()).toEqual(fontStyles.sort())
})
describe('getDirection', () => {
it('should return the configured text direction', () => {
const result = c.getDirection()
expect(result).toEqual(c.direction)
})
})
describe('getStyle', () => {
it('should return the specified style', () => {
const result = c.getStyle('paragraph')
expect(result).toEqual(c.styles.paragraph)
})
it('should return the default text style if an invalid style is specified', () => {
const result = c.getStyle('asdf')
expect(result).toEqual(c.styles.text)
})
})
})
describe('makeTypographyStyle', () => {
let c
beforeEach(() => {
c = new TypographyConfig()
})
it('should set the font size for headings correctly', () => {
const result = makeTypographyStyle(c.config, 'heading', 'h1')
expect(result.fontSize).toEqual(c.config.sizes.h1)
})
it('should set the font size for non-headings correctly', () => {
const result = makeTypographyStyle(c.config, 'paragraph')
expect(result.fontSize).toEqual(c.config.sizes.base)
})
it('should set the text justify property if the style alignment is "justify"', () => {
const result = makeTypographyStyle(c.config, 'paragraph')
expect(result.textJustify).not.toBeNull()
})
})
|
import pickAnswers from "./apputils";
test('shouldPickUniqueAnswers',()=>{
const answers=pickAnswers();
expect((new Set(answers)).size === answers.length).toBe(true);
})
|
// export constant messages
module.exports = {
MUST_LOGIN: 'You must be logged in.',
MUST_LOGOUT: 'You must be logged out.',
WRONG_EMAIL_PASSWORD: 'Incorrect email or password. Please try again.',
TOO_SHORT: (fieldName, minLength) =>
`[${fieldName}] must have a minimum of ${minLength} characters.`,
TOO_LONG: (fieldName, maxLength) =>
`[${fieldName}] must have a maximum of ${maxLength} characters.`,
REQUIRED: fieldName => `[${fieldName}] is required (cannot be empty)`,
WRONG_EMAIL_FORMAT: 'Please provide a valid email address.',
INVALID_DATE_FORMAT: 'Please provide a valid date format',
MUST_BE_ABOVE: (fieldName, min) => `The value of [${fieldName}] should be above ${min}`
};
|
export default (state = {loading: false}, action) => {
switch (action.type) {
case 'LOADING_STARTED':
return {
loading: true,
error: null
};
case 'LOADING_SUCCESS':
return {
loading: false,
error: null
}
case 'LOADING_FAILED':
return {
loading: false,
error: action.error
};
default:
return state;
}
}
|
import bookshelf from '../config/bookshelf';
import FirstProject from './first_level_project.model';
import ThirdProject from './third_level_project.model';
import Qa from './qa.model';
import Product from './product.model';
import Skill from './skill.model';
import Service from './service.model';
/**
* Second Level Project model.
*/
class SecondProject extends bookshelf.Model {
get tableName() {
return 'second_project';
}
get hasTimestamps() {
return true;
}
FirstProject() {
return this.belongsTo(FirstProject, "First_Project_Id");
}
ThirdProjects() {
return this.hasMany(ThirdProject, "Second_Project_Id");
}
Questions() {
return this.hasMany(Qa, "Second_Project_Id");
}
Products() {
return this.hasMany(Product, "First_Project_Id");
}
Skill() {
return this.hasMany(Skill, "Second_Project_Id");
}
Service() {
return this.hasMany(Service, "Second_Project_Id");
}
}
export default SecondProject;
|
// @flow strict
import { CarRentalMenuItem } from '../CarRentalMenuItem';
it('adds correct parameters to the URL', () => {
const Component = new CarRentalMenuItem();
expect(Component.buildWhitelabelURL('MOCKED')).toBe(
'MOCKED?adplat=mobileapp_ios&forceMobile=true',
);
});
it('appends parameters correctly', () => {
const Component = new CarRentalMenuItem();
expect(Component.buildWhitelabelURL('MOCKED?test=true')).toBe(
'MOCKED?test=true&adplat=mobileapp_ios&forceMobile=true',
);
});
|
//function -> keyword
//std function
// function fun()
// {
// console.log("hi!!");
// }
//function acts like a variable
//function expression
let sayHi = function(){
console.log("say hi!!");
}
sayHi();
//global execution context
//1. memory allocation phase => any variable gets undefined, func_name get function body
//2. code execution phase => variable gets its value (var a=10), since func_name has the code by now, where ever you call it, it doesn't
//matter, it will execute
//in case of var=func(), not same
let say;
say = function () {
console.log("Say Hiii !!");
}
say();
//in this case, say is a var, in memory allocation phase it get undefined and then in code execution phase it gets the function and
//then it can get executed as the call is made afterwards but if call made before function assignment to say, say would contain undefined and
// wouldn't know it's supposed to be a function and will throw error
//callback thing
//high order func => accepts function as argument
//callback function => which is passed as an argument in other func
function argument(){
console.log("hello there");
}
function highorder(cb)
{
console.log("entered highorder");
cb();
console.log("exiting highorder");
}
highorder(argument);
//sync func => normal function ie does complete work no matter how much time it consumes then move fwd
//async func => multitasking kind, does work in bg and in fg does some other independent tasks
//usage of callback => implement async functions
|
OC.L10N.register(
"lib",
{
"Unknown filetype" : "មិនស្គាល់ប្រភេទឯកសារ",
"Invalid image" : "រូបភាពមិនត្រឹមត្រូវ",
"today" : "ថ្ងៃនេះ",
"yesterday" : "ម្សិលមិញ",
"last month" : "ខែមុន",
"_%n month ago_::_%n months ago_" : ["%n ខែមុន"],
"last year" : "ឆ្នាំមុន",
"_%n hour ago_::_%n hours ago_" : ["%n ម៉ោងមុន"],
"_%n minute ago_::_%n minutes ago_" : ["%n នាទីមុន"],
"seconds ago" : "វិនាទីមុន",
"None" : "គ្មាន",
"Username" : "ឈ្មោះអ្នកប្រើ",
"Password" : "ពាក្យសម្ងាត់",
"__language_name__" : "__language_name__",
"App directory already exists" : "មានទីតាំងផ្ទុកកម្មវិធីរួចហើយ",
"Can't create app folder. Please fix permissions. %s" : "មិនអាចបង្កើតថតកម្មវិធី។ សូមកែសម្រួលសិទ្ធិ។ %s",
"Apps" : "កម្មវិធី",
"General" : "ទូទៅ",
"Storage" : "ឃ្លាំងផ្ទុក",
"Security" : "សុវត្ថិភាព",
"Encryption" : "កូដនីយកម្ម",
"Sharing" : "ការចែករំលែក",
"Search" : "ស្វែងរក",
"%s enter the database username." : "%s វាយបញ្ចូលឈ្មោះអ្នកប្រើមូលដ្ឋានទិន្នន័យ។",
"%s enter the database name." : "%s វាយបញ្ចូលឈ្មោះមូលដ្ឋានទិន្នន័យ។",
"Oracle connection could not be established" : "មិនអាចបង្កើតការតភ្ជាប់ Oracle",
"DB Error: \"%s\"" : "កំហុស DB៖ \"%s\"",
"PostgreSQL username and/or password not valid" : "ឈ្មោះអ្នកប្រើ និង/ឬ ពាក្យសម្ងាត់ PostgreSQL គឺមិនត្រូវទេ",
"Set an admin username." : "កំណត់ឈ្មោះអ្នកគ្រប់គ្រង។",
"Set an admin password." : "កំណត់ពាក្យសម្ងាត់អ្នកគ្រប់គ្រង។",
"Could not find category \"%s\"" : "រកមិនឃើញចំណាត់ក្រុម \"%s\"",
"A valid username must be provided" : "ត្រូវផ្ដល់ឈ្មោះអ្នកប្រើឲ្យបានត្រឹមត្រូវ",
"A valid password must be provided" : "ត្រូវផ្ដល់ពាក្យសម្ងាត់ឲ្យបានត្រឹមត្រូវ",
"Settings" : "ការកំណត់",
"Users" : "អ្នកប្រើ",
"Application is not enabled" : "មិនបានបើកកម្មវិធី",
"Authentication error" : "កំហុសការផ្ទៀងផ្ទាត់ភាពត្រឹមត្រូវ",
"Unknown user" : "មិនស្គាល់អ្នកប្រើប្រាស់"
},
"nplurals=1; plural=0;");
|
'use strict'
window.addEventListener('load',()=>{
var share = document.querySelector('#share');
var menuS= document.querySelector('.menu__share');
var btnShare = document.querySelector('.share');
share.addEventListener('click',()=>{
if(menuS.classList.contains('show')){
menuS.classList.remove('show');
menuS.classList.add('hide');
btnShare.classList.remove('active');
}else{
menuS.classList.add('show');
menuS.classList.remove('hide');
btnShare.classList.add('active');
// share.style.color="white";
// btnShare.style.backgroundColor = "hsl(214, 17%, 51%)";
}
});
});
|
({
fireTemplateEvent : function(cmp, selectedPostTemplate) {
var cmpEvent = cmp.getEvent("selectTemplate");
cmpEvent.setParams({
"templateIdentifier" : selectedPostTemplate });
cmpEvent.fire();
}
})
|
var rating_selector = '.rating .num',
karma_selector = '.score .num',
comments_selector = '.posts .post .comments .all',
rating = parseFloat($(rating_selector).html().replace(',', '.')),
karma = parseFloat($('.score .num').html().replace(',', '.')),
lastPostCommentsCount = parseInt($(comments_selector).first().html()),
delay = 1 * 1000, // 1 second
username = document.location.pathname.split('/')[2]; // Get username from current URL
setInterval(function () {
$.ajax({
method: 'GET',
url: 'http://habrahabr.ru/users/' + username + '/topics/',
success: function (data) {
var body = $(data),
newRating = parseFloat(body.find(rating_selector).html().replace(',', '.')),
newKarma = parseFloat(body.find(karma_selector).html().replace(',', '.')),
newCommentsCount = parseInt(body.find(comments_selector).first().html());
if (newRating != rating) {
alert("New rating: " + newRating + ', change: ' + (newRating - rating));
rating = newRating;
}
if (newKarma != karma) {
alert("New carma: " + newKarma + ', change: ' + (newKarma - karma));
karma = newKarma;
}
if (newCommentsCount != lastPostCommentsCount) {
alert("Comments added: " + (newCommentsCount - lastPostCommentsCount));
lastPostCommentsCount = newCommentsCount;
}
}
})
}, delay);
|
import { CARGO_GET_ALL_FAILURE, CARGO_GET_ALL_REQUEST, CARGO_GET_ALL_SUCCESS } from './index';
import Axios from 'axios';
export const getAllCargo = () => ({
types: [CARGO_GET_ALL_REQUEST, CARGO_GET_ALL_SUCCESS, CARGO_GET_ALL_FAILURE],
request: () => Axios.get('/api/cargo/'),
shouldSkip: (state) => state.cargo.isFetching,
});
|
const https = require('https');
const POSTRequestWrapper = async (requestName, hostName, apiPath, acceptHeaderValue, authToken, postData) => {
const postBody = JSON.stringify(postData);
const options = {
hostname: hostName,
port: 443,
path: apiPath,
method: 'POST',
headers: {
'Content-Type': acceptHeaderValue
},
json: true,
requestCert: true,
agent: false
};
if (authToken !== '') {
options.headers.Cookie = authToken;
}
return await new Promise((resolve, reject) => {
const request = https.request(options, (response) => {
let str = '';
const obj = {
body: str,
statusCode: 0,
headers: []
};
response
.on('data', (data) => {
str += data;
})
.on('end', () => {
obj.body = str;
obj.statusCode = response.statusCode;
obj.headers.push(response.headers);
resolve(obj);
})
.on('error', (err) => {
obj.body = err;
obj.statusCode = response.statusCode;
reject(obj);
});
});
request.on('error', (err) => {
console.log(`POST request ${requestName} encountered the following error: ${err.message}`);
reject(err);
});
request.write(postBody);
request.end();
});
};
const DELETERequestWrapper = async (requestName, hostName, apiPath, acceptHeaderValue, authToken) => {
const options = {
hostname: hostName,
port: 443,
path: apiPath,
method: 'DELETE',
headers: {
'Content-Type': acceptHeaderValue
},
json: true,
requestCert: true,
agent: false
};
if (authToken !== '') {
options.headers.Cookie = authToken;
}
return await new Promise((resolve, reject) => {
const request = https.request(options, (response) => {
let str = '';
const obj = {
body: str,
statusCode: 0
};
response
.on('data', data => {
str += data;
})
.on('end', () => {
const data = str;
obj.body = data;
obj.statusCode = response.statusCode;
resolve(obj);
})
.on('error', err => {
obj.body = err;
obj.statusCode = response.statusCode;
reject(obj);
});
});
request.on('error', (err) => {
console.log(`DELETE request ${requestName} encountered the following error: ${err.message}`);
reject(err);
});
request.end();
});
};
module.exports = {
POSTRequestWrapper: POSTRequestWrapper,
DELETERequestWrapper: DELETERequestWrapper
};
|
TRAFFIC.Road = function (source, target) {
this.source = source;
this.target = target;
this.id = TRAFFIC.uniqueId('road');
this.lanes = [];
this.lanesNumber = null;
this.update();
Object.defineProperty(this, 'length', {
get: function() {
return this.targetSide.target.subtract(this.sourceSide.source).length;
}
});
Object.defineProperty(this, 'leftmostLane', {
get: function() {
return this.lanes[this.lanesNumber - 1];
}
});
Object.defineProperty(this, 'rightmostLane', {
get: function() {
return this.lanes[0];
}
});
}
TRAFFIC.Road.prototype = {
constructor: TRAFFIC.Road,
copy : function(road) {
var result;
result = Object.create(TRAFFIC.Road.prototype);
TRAFFIC.extend.extend(result, road);
if (result.lanes == null) result.lanes = [];
return result;
},
toJSON : function() {
var obj;
return obj = { id: this.id, source: this.source.id, target: this.target.id };
},
getTurnDirection : function(other) {
var side1, side2, turnNumber;
if (this.target !== other.source) throw Error('invalid roads');
side1 = this.targetSideId;
side2 = other.sourceSideId;
return turnNumber = (side2 - side1 - 1 + 8) % 4;
},
update : function() {
var i, sourceSplits, targetSplits, _base, _i, _j, _ref, _ref1, _results;
if (!(this.source && this.target)) throw Error('incomplete road');
this.sourceSideId = this.source.rect.getSectorId(this.target.rect.center());
this.sourceSide = this.source.rect.getSide(this.sourceSideId).subsegment(0.5, 1.0);
this.targetSideId = this.target.rect.getSectorId(this.source.rect.center());
this.targetSide = this.target.rect.getSide(this.targetSideId).subsegment(0, 0.5);
this.lanesNumber = TRAFFIC.min(this.sourceSide.length, this.targetSide.length) | 0;
this.lanesNumber = TRAFFIC.max(2, this.lanesNumber / TRAFFIC.settings.gridSize | 0);
sourceSplits = this.sourceSide.split(this.lanesNumber, true);
targetSplits = this.targetSide.split(this.lanesNumber);
if ((this.lanes == null) || this.lanes.length < this.lanesNumber) {
if (this.lanes == null) this.lanes = [];
for (i = _i = 0, _ref = this.lanesNumber - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
if ((_base = this.lanes)[i] == null) _base[i] = new TRAFFIC.Lane(sourceSplits[i], targetSplits[i], this);
}
}
_results = [];
for (i = _j = 0, _ref1 = this.lanesNumber - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
this.lanes[i].sourceSegment = sourceSplits[i];
this.lanes[i].targetSegment = targetSplits[i];
this.lanes[i].leftAdjacent = this.lanes[i + 1];
this.lanes[i].rightAdjacent = this.lanes[i - 1];
this.lanes[i].leftmostAdjacent = this.lanes[this.lanesNumber - 1];
this.lanes[i].rightmostAdjacent = this.lanes[0];
_results.push(this.lanes[i].update());
}
return _results;
}
}
|
// REGEX - practice source: https://fireship.io/lessons/regex-cheat-sheet-js/
// Ways to create a regular expression
// 1. literal
const re = /foo/;
// 2. instantiate RegExp()
const re2 = new RegExp(/foo/);
// Ways to use a regular expression on a string primitive,
// 1. 'match' all the occurrances
const matches = 'aBC'.match(/[A-Z]/g) // anything outside / / is a flag; in this case g for global
// console.log(`matches result: ${matches}`)
// expected output: [B,C]
// 2. 'search' for the existence of a pattern
const index = 'aBC'.search(/[A-Z]/)
// console.log(`search result: ${index}`)
// expected output: 1
// 3. 'replace' matches with new values
const next = 'aBC'.replace(/a/, 'A')
// console.log(`next result: ${next}`)
// expected output: ABC
// Password Validation with REGEX!
// Lets force passwords to contain a capital letter, lowercase letter, a number and a min. length of 8 {8, } and max. length of {, 16}
const pw = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).{8,}$/g
// const pw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,16}$/gm
const mypws = ["Fernando", "f3rn4", "F3rnand0!", "fernando123!", "1sMyPasswordOK?", "Testing123!"]
const validatepassword = (pwarray, regexrules) => {
for(const mypw of pwarray){
console.log("\n"+mypw)
const match = mypw.match(regexrules)
!match ? console.log("invalid password.") : console.log(`${mypw} is valid.`)
}
}
// validatepassword(mypws, pw)
// Smart Character Replacement
// source: https://blog.bitsrc.io/4-practical-use-cases-for-regular-expressions-b6ab140894fd
let camelRE = /([A-Z])/g
let phrase = "thisIsACamelCaseString"
console.log(phrase.replace(camelRE, " $1")) // should increment the $1 when working with more than one capture group...?
// expected output: this Is A Camel Case String // we add spaces :P.
// Old School Function to Arrow Function
// example old school function:
function sayHello(first_name, last_name){
console.log(`Hellow there ${first_name} ${last_name}!`)
}
// Node.js Script
const oldToNew = (somefunc) => {
// Node File System Module
const fs = require("fs")
const regExp = /function (.+)(\(.+\))(\{.+\})/gms
fs.readFile("./test2.js", (err, cnt) => {
console.log(cnt.toString().replace(regExp, "const $1 = $2 = $3"))
})
}
|
const nodemailer = require('nodemailer');
const pool = require('./database');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const PdfPrinter = require('pdfmake');
const Roboto = require('./public/fonts/Roboto');
const moment = require('moment');
const e = require('connect-flash');
//const puppeteer = require('puppeteer');
moment.locale('es');
const transpoter = nodemailer.createTransport({
host: 'smtpout.secureserver.net',
port: 80,
secure: false,
auth: {
user: 'info@grupoelitefincaraiz.co',
pass: 'C0l0mb1@1q2w3e4r5t*'
},
tls: {
rejectUnauthorized: false
}
});
const noCifra = valor => {
if (!valor) return 0;
const num = /[^0-9.-]/g.test(valor)
? parseFloat(valor.replace(/[^0-9.]/g, ''))
: parseFloat(valor);
if (typeof num != 'number') throw TypeError('El argumento no puede ser de tipo string');
return num;
};
const Cifra = valor => {
if (!valor) return 0;
const punto = /\.$/.test(valor);
const num = /[^0-9.-]/g.test(valor)
? parseFloat(valor.replace(/[^0-9.]/g, ''))
: parseFloat(valor);
if (typeof num != 'number') throw TypeError('El argumento no puede ser de tipo string');
return punto
? num.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 }) + '.'
: num.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
};
const Percent = valor => {
if (!valor) return valor;
const punto = /\.$/.test(valor);
const num =
(/[^0-9.]/g.test(valor) ? parseFloat(valor.replace(/[^0-9.]/g, '')) : parseFloat(valor)) / 100;
if (typeof num != 'number') throw TypeError('El argumento no puede ser de tipo string');
return punto
? num.toLocaleString('en-CO', {
style: 'percent',
minimumFractionDigits: 0,
maximumFractionDigits: 2
}) + '.'
: num.toLocaleString('en-CO', {
style: 'percent',
minimumFractionDigits: 0,
maximumFractionDigits: 2
});
};
function ID(lon) {
let chars = '0A1B2C3D4E5F6G7H8I9J0KL1M2N3O4P5Q6R7S8T9U0V1W2X3Y4Z',
code = '';
for (x = 0; x < lon; x++) {
let rand = Math.floor(Math.random() * chars.length);
code += chars.substr(rand, 1);
}
return code;
}
function ID2(lon) {
let chars = '1234567890',
code = '';
for (x = 0; x < lon; x++) {
let rand = Math.floor(Math.random() * chars.length);
code += chars.substr(rand, 1);
}
return code;
}
var normalize = (function () {
var from = 'ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç',
to = 'AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuuNnCc',
mapping = {};
for (var i = 0, j = from.length; i < j; i++) mapping[from.charAt(i)] = to.charAt(i);
return function (str) {
var ret = [];
for (var i = 0, j = str.length; i < j; i++) {
var c = str.charAt(i);
if (mapping.hasOwnProperty(str.charAt(i))) ret.push(mapping[c]);
else ret.push(c);
}
return ret.join('');
};
})();
async function Desendentes(pin, stados) {
if (stados != 10) {
return false;
}
let linea = '',
lDesc = '';
var hoy = moment().format('YYYY-MM-DD');
var month = moment().subtract(3, 'month').format('YYYY-MM-DD');
var venta = 0,
bono = 0,
bonop = 0,
personal = 0;
const asesor = await pool.query(
`SELECT * FROM pines p INNER JOIN users u ON p.acreedor = u.id
INNER JOIN rangos r ON u.nrango = r.id WHERE p.id = ? LIMIT 1`,
pin
);
var j = asesor[0];
const directas = await pool.query(
`SELECT * FROM preventa p
INNER JOIN productosd l ON p.lote = l.id
INNER JOIN productos o ON l.producto = o.id
INNER JOIN users u ON p.asesor = u.id
INNER JOIN clientes c ON p.cliente = c.idc
WHERE p.asesor = ? AND l.estado = 10 AND l.fechar BETWEEN '${month}' and '${hoy}'`,
j.acreedor
);
if (directas.length > 0) {
await directas.map(async (a, x) => {
var val = a.valor - a.ahorro;
var monto = val * j.comision;
var retefuente = monto * 0.1;
var reteica = (monto * 8) / 1000;
personal += val;
if (a.directa === null) {
bonop += val;
var f = {
fech: hoy,
monto,
concepto: 'COMISION DIRECTA',
stado: 9,
descp: 'VENTA DIRECTA',
asesor: j.acreedor,
porciento: j.comision,
total: val,
lt: a.lote,
retefuente,
reteica,
pagar: monto - (retefuente + reteica)
};
await pool.query(`UPDATE productosd SET ? WHERE id = ?`, [{ directa: j.acreedor }, a.lote]);
await pool.query(`INSERT INTO solicitudes SET ?`, f);
}
});
}
const lineaUno = await pool.query(
`SELECT * FROM pines WHERE usuario = ? AND usuario IS NOT NULL`,
j.acreedor
);
if (lineaUno.length > 0) {
await lineaUno.map((p, x) => {
lDesc += x === 0 ? `p.asesor = ${p.acreedor}` : ` OR p.asesor = ${p.acreedor}`;
linea += x === 0 ? `usuario = ${p.acreedor}` : ` OR usuario = ${p.acreedor}`;
});
const reporte = await pool.query(`SELECT * FROM preventa p
INNER JOIN productosd l ON p.lote = l.id
INNER JOIN productos o ON l.producto = o.id
INNER JOIN users u ON p.asesor = u.id
INNER JOIN clientes c ON p.cliente = c.idc
WHERE (${lDesc}) AND l.estado = 10 AND l.fechar BETWEEN '${month}' and '${hoy}'`);
if (reporte.length > 0) {
await reporte.map(async (a, x) => {
var val = a.valor - a.ahorro;
var monto = val * j.nivel1;
var retefuente = monto * 0.1;
var reteica = (monto * 8) / 1000;
venta += val;
if (a.uno === null) {
bono += val;
var f = {
fech: hoy,
monto,
concepto: 'COMISION INDIRECTA',
stado: 9,
descp: 'PRIMERA LINEA',
asesor: j.acreedor,
porciento: j.nivel1,
total: val,
lt: a.lote,
retefuente,
reteica,
pagar: monto - (retefuente + reteica)
};
await pool.query(`UPDATE productosd SET ? WHERE id = ?`, [{ uno: j.acreedor }, a.lote]);
await pool.query(`INSERT INTO solicitudes SET ?`, f);
}
});
}
const lineaDos = await pool.query(`SELECT * FROM pines WHERE ${linea}`);
(lDesc = ''), (linea = '');
await lineaDos.map((p, x) => {
lDesc += x === 0 ? `p.asesor = ${p.acreedor}` : ` OR p.asesor = ${p.acreedor}`;
linea += x === 0 ? `usuario = ${p.acreedor}` : ` OR usuario = ${p.acreedor}`;
});
const reporte2 = await pool.query(`SELECT * FROM preventa p
INNER JOIN productosd l ON p.lote = l.id
INNER JOIN productos o ON l.producto = o.id
INNER JOIN users u ON p.asesor = u.id
INNER JOIN clientes c ON p.cliente = c.idc
WHERE (${lDesc}) AND l.estado = 10 AND l.fechar BETWEEN '${month}' and '${hoy}'`);
if (reporte2.length > 0) {
await reporte2.map(async (a, x) => {
var val = a.valor - a.ahorro;
var monto = val * j.nivel2;
var retefuente = monto * 0.1;
var reteica = (monto * 8) / 1000;
venta += val;
if (a.dos === null) {
bono += val;
var f = {
fech: hoy,
monto,
concepto: 'COMISION INDIRECTA',
stado: 9,
descp: 'SEGUNDA LINEA',
asesor: j.acreedor,
porciento: j.nivel2,
total: val,
lt: a.lote,
retefuente,
reteica,
pagar: monto - (retefuente + reteica)
};
await pool.query(`UPDATE productosd SET ? WHERE id = ?`, [{ dos: j.acreedor }, a.lote]);
await pool.query(`INSERT INTO solicitudes SET ?`, f);
}
});
}
const lineaTres = await pool.query(`SELECT * FROM pines WHERE ${linea}`);
(lDesc = ''), (linea = '');
await lineaTres.map((p, x) => {
lDesc += x === 0 ? `p.asesor = ${p.acreedor}` : ` OR p.asesor = ${p.acreedor}`;
});
const reporte3 = await pool.query(`SELECT * FROM preventa p
INNER JOIN productosd l ON p.lote = l.id
INNER JOIN productos o ON l.producto = o.id
INNER JOIN users u ON p.asesor = u.id
INNER JOIN clientes c ON p.cliente = c.idc
WHERE (${lDesc}) AND l.estado = 10 AND l.fechar BETWEEN '${month}' and '${hoy}'`);
if (reporte3.length > 0) {
await reporte3.map(async (a, x) => {
var val = a.valor - a.ahorro;
var monto = val * j.nivel3;
var retefuente = monto * 0.1;
var reteica = (monto * 8) / 1000;
venta += val;
if (a.tres === null) {
bono += val;
var f = {
fech: hoy,
monto,
concepto: 'COMISION INDIRECTA',
stado: 9,
descp: 'TERCERA LINEA',
asesor: j.acreedor,
porciento: j.nivel3,
total: val,
lt: a.lote,
retefuente,
reteica,
pagar: monto - (retefuente + reteica)
};
await pool.query(`UPDATE productosd SET ? WHERE id = ?`, [{ tres: j.acreedor }, a.lote]);
await pool.query(`INSERT INTO solicitudes SET ?`, f);
}
});
}
}
var rango = j.nrango;
var tot = venta + personal;
if (personal >= j.venta && tot >= j.ventas) {
if (tot >= 500000000 && tot < 1000000000) {
var retefuente = j.premio * 0.1;
var reteica = (j.premio * 8) / 1000;
var f = {
fech: hoy,
monto: j.premio,
concepto: 'PREMIACION',
stado: 9,
descp: 'ASENSO A DIRECTOR',
asesor: j.acreedor,
total: tot,
retefuente,
reteica,
pagar: j.premio - (retefuente + reteica)
};
await pool.query(`INSERT INTO solicitudes SET ?`, f);
await pool.query(`UPDATE users SET ? WHERE id = ?`, [{ nrango: 4 }, j.acreedor]);
rango = 4;
} else if (tot >= 1000000000 && tot < 2000000000) {
var retefuente = j.premio * 0.1;
var reteica = (j.premio * 8) / 1000;
var f = {
fech: hoy,
monto: j.premio,
concepto: 'PREMIACION',
stado: 9,
descp: 'ASENSO A GERENTE',
asesor: j.acreedor,
total: tot,
retefuente,
reteica,
pagar: j.premio - (retefuente + reteica)
};
await pool.query(`INSERT INTO solicitudes SET ?`, f);
await pool.query(`UPDATE users SET ? WHERE id = ?`, [{ nrango: 3 }, j.acreedor]);
rango = 3;
} else if (tot >= 2000000000 && tot < 3000000000) {
var retefuente = j.premio * 0.1;
var reteica = (j.premio * 8) / 1000;
var f = {
fech: hoy,
monto: j.premio,
concepto: 'PREMIACION',
stado: 9,
descp: 'ASENSO A VICEPRESIDENTE',
asesor: j.acreedor,
total: tot,
retefuente,
reteica,
pagar: j.premio - (retefuente + reteica)
};
await pool.query(`INSERT INTO solicitudes SET ?`, f);
await pool.query(`UPDATE users SET ? WHERE id = ?`, [{ nrango: 2 }, j.acreedor]);
rango = 2;
} else if (tot >= 300000000) {
var retefuente = j.premio * 0.1;
var reteica = (j.premio * 8) / 1000;
var f = {
fech: hoy,
monto: j.premio,
concepto: 'PREMIACION',
stado: 9,
descp: 'ASENSO A PRESIDENTE',
asesor: j.acreedor,
total: tot,
retefuente,
reteica,
pagar: j.premio - (retefuente + reteica)
};
await pool.query(`INSERT INTO solicitudes SET ?`, f);
await pool.query(`UPDATE users SET ? WHERE id = ?`, [{ nrango: 1 }, j.acreedor]);
rango = 1;
}
}
var bonus = j.bono;
if (rango !== j.nrango) {
const ucr = await pool.query(`SELECT * FROM users WHERE id = ?`, j.acreedor);
rango = ucr[0].nrango;
bonus = ucr[0].bono;
}
if (rango === 5) {
await pool.query(
`DELETE FROM solicitudes WHERE concepto = 'COMISION INDIRECTA' AND asesor = ?`,
j.acreedor
);
} else if (rango === 3) {
var monto = bonop * bonus;
var retefuente = monto * 0.1;
var reteica = (monto * 8) / 1000;
var f = {
fech: hoy,
monto,
concepto: 'BONO',
stado: 9,
porciento: bonus,
descp: 'BONO GERENCIAL',
asesor: j.acreedor,
total: bonop,
retefuente,
reteica,
pagar: monto - (retefuente + reteica)
};
await pool.query(`INSERT INTO solicitudes SET ?`, f);
} else if (rango === 2 || rango === 1) {
var monto = (bonop + bono) * bonus;
var retefuente = monto * 0.1;
var reteica = (monto * 8) / 1000;
var f = {
fech: hoy,
monto,
concepto: 'BONO',
stado: 9,
porciento: bonus,
descp: 'BONO PRESIDENCIAL',
asesor: j.acreedor,
total: bonop + bono,
retefuente,
reteica,
pagar: monto - (retefuente + reteica)
};
await pool.query(`INSERT INTO solicitudes SET ?`, f);
}
return true;
}
async function Eli(img) {
fs.exists(img, function (exists) {
if (exists) {
fs.unlink(img, function (err) {
if (err) throw err;
console.log('Archivo eliminado');
return 'Archivo eliminado';
});
} else {
console.log('El archivo no exise');
return 'El archivo no exise';
}
});
}
function Moneda(valor) {
if (valor) {
valor = valor
.toString()
.split('')
.reverse()
.join('')
.replace(/(?=\d*\.?)(\d{3})/g, '$1.');
valor = valor.split('').reverse().join('').replace(/^[\.]/, '');
return valor;
}
return 0;
}
/*const SCOPES = ['https://www.googleapis.com/auth/contacts'];
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), listConnectionNames);
});*/
function authorize(credentials, callback) {
const { client_secret, client_id, redirect_uris } = Contactos;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris);
// Comprueba si previamente hemos almacenado un token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Autorice esta aplicación visitando esta url: ', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Ingrese el código de esa página aquí: ', code => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Almacenar el token en el disco para posteriores ejecuciones del programa
fs.writeFile(TOKEN_PATH, JSON.stringify(token), err => {
if (err) return console.error(err);
console.log('Token almacenado en', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
function listConnectionNames(auth) {
const service = google.people({ version: 'v1', auth });
service.people.connections.list(
{
resourceName: 'people/me',
pageSize: 100,
personFields:
'biographies,birthdays,coverPhotos,emailAddresses,events,genders,imClients,interests,locales,memberships,metadata,names,nicknames,occupations,organizations,phoneNumbers,photos,relations,residences,sipAddresses,skills,urls,userDefined'
},
(err, res) => {
if (err) return console.error('The API returned an error: ' + err);
const connections = res.data.connections;
if (connections) {
console.log('Connections:');
connections.forEach(person => {
if (person.names && person.names.length > 0) {
console.log(person.names);
} else {
console.log('No display name found for connection.');
}
});
} else {
console.log('No connections found.');
}
}
);
}
//////////////* CIFRAS EN LETRAS *///////////////////
function Unidades(num) {
switch (num) {
case 1:
return 'UN';
case 2:
return 'DOS';
case 3:
return 'TRES';
case 4:
return 'CUATRO';
case 5:
return 'CINCO';
case 6:
return 'SEIS';
case 7:
return 'SIETE';
case 8:
return 'OCHO';
case 9:
return 'NUEVE';
}
return '';
} //Unidades()
function Decenas(num) {
decena = Math.floor(num / 10);
unidad = num - decena * 10;
switch (decena) {
case 1:
switch (unidad) {
case 0:
return 'DIEZ';
case 1:
return 'ONCE';
case 2:
return 'DOCE';
case 3:
return 'TRECE';
case 4:
return 'CATORCE';
case 5:
return 'QUINCE';
default:
return 'DIECI' + Unidades(unidad);
}
case 2:
switch (unidad) {
case 0:
return 'VEINTE';
default:
return 'VEINTI' + Unidades(unidad);
}
case 3:
return DecenasY('TREINTA', unidad);
case 4:
return DecenasY('CUARENTA', unidad);
case 5:
return DecenasY('CINCUENTA', unidad);
case 6:
return DecenasY('SESENTA', unidad);
case 7:
return DecenasY('SETENTA', unidad);
case 8:
return DecenasY('OCHENTA', unidad);
case 9:
return DecenasY('NOVENTA', unidad);
case 0:
return Unidades(unidad);
}
} //Decenas()
function DecenasY(strSin, numUnidades) {
if (numUnidades > 0) return strSin + ' Y ' + Unidades(numUnidades);
return strSin;
} //DecenasY()
function Centenas(num) {
centenas = Math.floor(num / 100);
decenas = num - centenas * 100;
switch (centenas) {
case 1:
if (decenas > 0) return 'CIENTO ' + Decenas(decenas);
return 'CIEN';
case 2:
return 'DOSCIENTOS ' + Decenas(decenas);
case 3:
return 'TRESCIENTOS ' + Decenas(decenas);
case 4:
return 'CUATROCIENTOS ' + Decenas(decenas);
case 5:
return 'QUINIENTOS ' + Decenas(decenas);
case 6:
return 'SEISCIENTOS ' + Decenas(decenas);
case 7:
return 'SETECIENTOS ' + Decenas(decenas);
case 8:
return 'OCHOCIENTOS ' + Decenas(decenas);
case 9:
return 'NOVECIENTOS ' + Decenas(decenas);
}
return Decenas(decenas);
} //Centenas()
function Seccion(num, divisor, strSingular, strPlural) {
cientos = Math.floor(num / divisor);
resto = num - cientos * divisor;
letras = '';
if (cientos > 0)
if (cientos > 1) letras = Centenas(cientos) + ' ' + strPlural;
else letras = strSingular;
if (resto > 0) letras += '';
return letras;
} //Seccion()
function Miles(num) {
divisor = 1000;
cientos = Math.floor(num / divisor);
resto = num - cientos * divisor;
strMiles = Seccion(num, divisor, 'MIL', 'MIL');
strCentenas = Centenas(resto);
if (strMiles == '') return strCentenas;
return strMiles + ' ' + strCentenas;
//return Seccion(num, divisor, "UN MIL", "MIL") + " " + Centenas(resto);
} //Miles()
function Millones(num) {
divisor = 1000000;
cientos = Math.floor(num / divisor);
resto = num - cientos * divisor;
strMillones = Seccion(num, divisor, 'UN MILLON', 'MILLONES');
strMiles = Miles(resto);
if (strMillones == '') return strMiles;
return strMillones + ' ' + strMiles;
//return Seccion(num, divisor, "UN MILLON", "MILLONES") + " " + Miles(resto);
} //Millones()
function NumeroALetras(num, centavos) {
var data = {
numero: num,
enteros: Math.floor(num),
centavos: Math.round(num * 100) - Math.floor(num) * 100,
letrasCentavos: ''
};
if (centavos == undefined || centavos == false) {
data.letrasMonedaPlural = 'PESOS';
data.letrasMonedaSingular = 'PESO';
} else {
data.letrasMonedaPlural = 'CENTAVOS';
data.letrasMonedaSingular = 'CENTAVO';
}
if (data.centavos > 0) data.letrasCentavos = 'CON ' + NumeroALetras(data.centavos, true);
if (data.enteros == 0) return 'CERO ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos;
if (data.enteros == 1) {
res = Millones(data.enteros) + ' ' + data.letrasMonedaSingular + ' ' + data.letrasCentavos;
if (res.indexOf('UN MILLON PESO') > 0)
return res.replace('UN MILLON PESO', 'UN MILLON DE PESO');
return res;
} else {
res = Millones(data.enteros) + ' ' + data.letrasMonedaPlural + ' ' + data.letrasCentavos;
if (res.indexOf('MILLONES PESOS') > 0)
return res.replace('MILLONES PESOS', 'MILLONES DE PESOS');
return res;
}
} //NumeroALetras()
//////////////* CIFRAS EN LETRAS END *///////////////////
//////////////* EMAILS *////////////////////////////////
async function EnviarEmail(email, asunto, destinatario, html, texto, archivos) {
let data = {
from: "'GRUPO ELITE' <info@grupoelitefincaraiz.co>",
to: email,
subject: asunto
};
html ? (data.html = texto) : (data.text = destinatario + ' ' + texto);
if (Array.isArray(archivos) && archivos.length) {
data.attachments = archivos.map((e, i) => {
return {
// file on disk as an attachment
filename: e.fileName,
path: e.ruta // stream this file
};
});
}
console.log(data);
envio = await transpoter.sendMail(data);
//console.log(envio)
}
//////////////* EMAILS END *////////////////////////////////
async function QuienEs(document, chatId) {
const cliente = await pool.query(`SELECT * FROM clientes WHERE documento = ?`, document);
if (cliente.length) {
const Id = ID(5) + '@7';
EnviarEmail(
cliente[0].email,
'Comprobacion de identidad',
cliente[0].nombre,
false,
`Su codigo de comprobacion es ${Id}`
);
let email = cliente[0].email.split('@');
encrip = email[0].slice(0, 2) + '****' + email[0].slice(-3) + '@' + email[1];
await pool.query(`UPDATE clientes SET code = ? WHERE documento = ?`, [Id, document]);
apiChatApi('message', {
chatId: chatId,
body: `_🙂 Muy bien *${
cliente[0].nombre.split(' ')[0]
}*, para terminar con la verificación, ve a tu *correo* electrónico 📧 y escríbenos *aquí* 👇🏽 el *código de comprobación* 🔐 que te enviamos al ${encrip}, recuerda que si no lo ves en tu *bandeja de entrada* puede que este en tus *"Spam"* o *"Correo no deseado"*_`
});
return true;
} else {
await pool.query(`UPDATE clientes SET code = NULL WHERE documento = ?`, document);
apiChatApi('message', {
chatId: chatId,
body: `😞 Lo sentimos no encontramos a nadie con ese numero de documento en nuestro sistema`
});
}
}
async function EstadoCuenta(movil, nombre, author) {
const cel = movil.slice(-10);
const estado =
await pool.query(`SELECT pd.valor - p.ahorro AS total, pt.proyect, cu.pin AS cupon, cp.pin AS bono, s.stado,
p.ahorro, pd.mz, pd.n, pd.valor, p.vrmt2, p.fecha, s.fech, s.ids, s.formap, s.descp,s.monto, s.img, cu.descuento, p.id cparacion,
c.nombre, c.documento, c.email, c.movil, cp.monto mtb, pd.mtr2 FROM solicitudes s INNER JOIN productosd pd ON s.lt = pd.id
INNER JOIN productos pt ON pd.producto = pt.id INNER JOIN preventa p ON pd.id = p.lote
LEFT JOIN cupones cu ON cu.id = p.cupon LEFT JOIN cupones cp ON s.bono = cp.id
INNER JOIN clientes c ON p.cliente = c.idc LEFT JOIN clientes c2 ON p.cliente2 = c2.idc
LEFT JOIN clientes c3 ON p.cliente3 = c3.idc LEFT JOIN clientes c4 ON p.cliente4 = c4.idc
WHERE s.stado != 6 AND s.concepto IN('PAGO', 'ABONO') AND p.tipobsevacion IS NULL
AND (c.movil LIKE '%${cel}%' OR c.code LIKE '%${cel}%' OR c.nombre = '${nombre}'
OR c2.movil LIKE '%${cel}%' OR c2.code LIKE '%${cel}%' OR c2.nombre = '${nombre}'
OR c3.movil LIKE '%${cel}%' OR c3.code LIKE '%${cel}%' OR c3.nombre = '${nombre}'
OR c4.movil LIKE '%${cel}%' OR c4.code LIKE '%${cel}%' OR c4.nombre = '${nombre}')`);
if (estado.length) {
const cuerpo = [];
let totalAbonado = 0;
estado.map((e, i) => {
totalAbonado += e.stado === 4 ? e.monto : 0;
if (!i) {
cuerpo.push(
[
{
text: `Area: ${e.mtr2} mt2`,
style: 'tableHeader',
colSpan: 2,
alignment: 'center'
},
{},
{
text: `Vr Mt2: $${Moneda(e.vrmt2)}`,
style: 'tableHeader',
colSpan: 2,
alignment: 'center'
},
{},
{
text: '$' + Moneda(e.valor),
style: 'tableHeader',
alignment: 'center',
colSpan: 2
},
{}
],
[
'Cupon',
'Dsto',
{ text: 'Ahorro', colSpan: 2 },
{},
{ text: `Total lote`, colSpan: 2 },
{}
],
[
{ text: e.cupon, style: 'tableHeader', alignment: 'center' },
{
text: `${e.descuento}%`,
style: 'tableHeader',
alignment: 'center'
},
{
text: `-$${Moneda(e.ahorro)}`,
style: 'tableHeader',
colSpan: 2,
alignment: 'center'
},
{},
{
text: `$${Moneda(e.total)}`,
style: 'tableHeader',
colSpan: 2,
alignment: 'center'
},
{}
],
['Fecha', 'Recibo', 'Estado', 'Forma de pago', 'Tipo', 'Monto'],
[
moment(e.fech).format('L'),
`RC${e.ids}`,
{
text: e.stado === 4 ? 'Aprobado' : 'Pendiente',
color: e.stado === 4 ? 'green' : 'blue'
},
e.formap,
e.descp,
{
text: '$' + Moneda(e.monto),
color: e.stado === 4 ? 'green' : 'blue',
decoration: e.stado !== 4 && 'lineThrough',
decorationStyle: e.stado !== 4 && 'double'
}
]
);
} else {
cuerpo.push([
moment(e.fech).format('L'),
`RC${e.ids}`,
{
text: e.stado === 4 ? 'Aprobado' : 'Pendiente',
color: e.stado === 4 ? 'green' : 'blue'
},
e.formap,
e.descp,
{
text: '$' + Moneda(e.monto),
color: e.stado === 4 ? 'green' : 'blue',
decoration: e.stado !== 4 && 'lineThrough',
decorationStyle: e.stado !== 4 && 'double'
}
]);
}
});
cuerpo.push(
[
{
text: 'TOTAL ABONADO',
style: 'tableHeader',
alignment: 'center',
colSpan: 4
},
{},
{},
{},
{
text: '$' + Moneda(totalAbonado),
style: 'tableHeader',
alignment: 'center',
colSpan: 2
},
{}
],
[{ text: NumeroALetras(totalAbonado), style: 'small', colSpan: 6 }, {}, {}, {}, {}, {}],
[
{
text: 'SALDO A LA FECHA',
style: 'tableHeader',
alignment: 'center',
colSpan: 4
},
{},
{},
{},
{
text: '$' + Moneda(estado[0].total - totalAbonado),
style: 'tableHeader',
alignment: 'center',
colSpan: 2
},
{}
],
[
{
text: NumeroALetras(estado[0].total - totalAbonado),
style: 'small',
colSpan: 6
},
{},
{},
{},
{},
{}
]
);
////////////////////////* CREAR PDF *//////////////////////////////
const printer = new PdfPrinter(Roboto);
let docDefinition = {
background: function (currentPage, pageSize) {
return {
image: path.join(__dirname, '/public/img/avatars/avatar1.png'),
width: pageSize.width,
opacity: 0.1
}; //, height: pageSize.height
},
pageSize: {
width: 595.28,
height: 'auto'
},
/* footer: function (currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; },
header: function (currentPage, pageCount, pageSize) {
// you can apply any logic and return any valid pdfmake element
return [
{ text: 'simple text', alignment: (currentPage % 2) ? 'right' : 'right' },
{ canvas: [{ type: 'rect', x: 170, y: 32, w: pageSize.width - 170, h: 40 }] }
]
}, */
//watermark: { text: 'Grupo Elite', color: 'blue', opacity: 0.1, bold: true, italics: false, fontSize: 200 }, //, angle: 180
//watermark: { image: path.join(__dirname, '/public/img/avatars/avatar.png'), width: 100, opacity: 0.3, fit: [100, 100] }, //, angle: 180
info: {
title: 'Estado de cuenta',
author: 'RedElite',
subject: 'Detallado del estado de los pagos de un producto',
keywords: 'estado de cuenta',
creator: 'Grupo Elite',
producer: 'G.E.'
},
content: [
// pageBreak: 'before',
{
columns: [
[
{ text: 'ESTADO DE CUENTA', style: 'header' },
'Conoce aqui el estado el estado de tus pagos y montos',
{ text: estado[0].nombre, style: 'subheader' },
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 9,
margin: [0, 0, 0, 5],
columns: [
{ text: `Doc. ${estado[0].documento}` },
{ text: `Movil ${estado[0].movil}` },
{ text: estado[0].email }
]
},
{
alignment: 'justify',
italics: true,
columns: [
{ width: 250, text: estado[0].proyect },
{ text: `MZ: ${estado[0].mz ? estado[0].mz : 'No aplica'}` },
{ text: `LT: ${estado[0].n}` }
]
}
],
{
width: 100,
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [100, 100]
}
]
},
{
style: 'tableBody',
color: '#444',
table: {
widths: ['auto', 'auto', 'auto', 'auto', 'auto', 'auto'],
headerRows: 4,
// keepWithHeaderRows: 1,
body: cuerpo
}
},
{
fontSize: 11,
italics: true,
text: [
'\nLos montos que se muestran de color ',
{ text: 'azul ', bold: true, color: 'blue' },
'no se suman al total ',
{ text: 'abonado, ', bold: true, color: 'green' },
'ya que estos montos aun no cuentan con la ',
{ text: 'aprobacion ', bold: true, color: 'green' },
'del area de ',
{ text: 'contabilidad. ', bold: true },
'Una ves se hallan aprobado se sumaran al saldo ',
{ text: 'abonado.\n\n', bold: true, color: 'green' }
]
},
{
columns: [
{
width: 100,
qr: 'https://grupoelitefincaraiz.com',
fit: '50',
foreground: 'yellow',
background: 'black'
},
[
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 10,
columns: [
{ text: 'GRUPO ELITE FINCA RAÍZ S.A.S.' },
{
text: 'https://grupoelitefincaraiz.com',
link: 'https://grupoelitefincaraiz.com'
}
]
},
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 10,
columns: [{ text: 'Nit: 901311748-3' }, { text: 'info@grupoelitefincaraiz.co' }]
},
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 10,
columns: [
{ text: 'Mz L lt 17 Urb. la granja, Turbaco' },
{
text: '57 300-285-1046',
link: 'https://wa.me/573007861987?text=Hola'
}
]
}
]
]
}
],
styles: {
header: {
fontSize: 18,
bold: true,
margin: [0, 0, 0, 10]
},
subheader: {
fontSize: 16,
bold: true,
margin: [0, 5, 0, 2]
},
tableBody: {
margin: [0, 5, 0, 5]
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
},
small: {
fontSize: 9,
italics: true,
color: 'gray',
alignment: 'right'
}
}
};
let ruta = path.join(__dirname, `/public/uploads/estadodecuenta-${estado[0].cparacion}.pdf`);
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream(ruta));
pdfDoc.end();
var dataFile = {
phone: author,
body: `https://grupoelitefincaraiz.co/uploads/estadodecuenta-${estado[0].cparacion}.pdf`,
filename: `ESTADO DE CUENTA ${estado[0].cparacion}.pdf`
};
let r = await apiChatApi('sendFile', dataFile);
r.msg = estado[0].cparacion;
await EnviarEmail(
estado[0].email,
`Estado de cuenta Lt: ${estado[0].n}`,
estado[0].nombre,
false,
'Grupo Elite te da la bienvenida',
[{ fileName: `Estado de cuenta ${estado[0].cparacion}.pdf`, ruta }]
);
return r; //JSON.stringify(estado);
} else {
return { sent: false };
}
}
async function FacturaDeCobro(ids) {
const Proyeccion = await pool.query(`SELECT s.ids, s.fech, s.monto, s.concepto,
s.porciento, s.total, u.fullname nam, u.cel clu, u.username mail, pd.mz, pr.id,
pd.n, s.retefuente, s.pagar, s.lt, cl.nombre, p.proyect, u.document, p.imagenes,
s.stado FROM solicitudes s INNER JOIN productosd pd ON s.lt = pd.id
INNER JOIN users u ON s.asesor = u.id INNER JOIN preventa pr ON pr.lote = pd.id
INNER JOIN productos p ON pd.producto = p.id INNER JOIN clientes cl ON pr.cliente = cl.idc
WHERE s.ids IN(${ids})`);
let cuerpo = [];
if (Proyeccion.length) {
Proyeccion.map((e, i) => {
let std;
switch (e.stado) {
case 1:
std = 'Auditando';
break;
case 4:
std = 'Pagada';
break;
case 6:
std = 'Declinada';
break;
case 3:
std = 'Pendiente';
break;
case 15:
std = 'Inactiva';
break;
case 9:
std = 'Disponible';
break;
default:
std = 'En espera';
}
if (!i) {
cuerpo.push(
[
{ text: `Id`, style: 'tableHeader', alignment: 'center' },
{ text: `Orden`, style: 'tableHeader', alignment: 'center' },
{ text: 'Fecha', style: 'tableHeader', alignment: 'center' },
//{ text: 'Cliente', style: 'tableHeader', alignment: 'center' },
//{ text: 'Proyecto', style: 'tableHeader', alignment: 'center' },
{ text: 'Mz', style: 'tableHeader', alignment: 'center' },
{ text: 'Lt', style: 'tableHeader', alignment: 'center' },
{ text: 'Concepto', style: 'tableHeader', alignment: 'center' },
{ text: 'Estado', style: 'tableHeader', alignment: 'center' },
{ text: 'Venta', style: 'tableHeader', alignment: 'center' },
{ text: '%', style: 'tableHeader', alignment: 'center' },
{ text: 'Monto', style: 'tableHeader', alignment: 'center' }
/* { text: 'Iva', style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' } */
],
[
e.ids,
e.id,
{ text: moment(e.fech).format('L'), alignment: 'center' },
//e.proyect,
e.mz,
e.n,
e.concepto, //e.nombre,
std,
{ text: '$' + Cifra(e.total || 0), alignment: 'center' },
e.porciento * 100 + '%',
{ text: '$' + Cifra(e.monto || 0), alignment: 'right' }
/* '$' + Moneda(e.retefuente),
'$' + Moneda(e.pagar) */
]
);
} else {
cuerpo.push([
e.ids,
e.id,
{ text: moment(e.fech).format('L'), alignment: 'center' },
//e.proyect,
e.mz,
e.n,
e.concepto, //, e.nombre
std,
{ text: '$' + Cifra(e.total || 0), alignment: 'center' },
e.porciento * 100 + '%',
{ text: '$' + Cifra(e.monto || 0), alignment: 'right' }
/* '$' + Moneda(e.retefuente),
'$' + Moneda(e.pagar) */
]);
}
});
console.log(Proyeccion[0].imagenes);
////////////////////////* CREAR PDF *//////////////////////////////
const printer = new PdfPrinter(Roboto);
let docDefinition = {
background: function (currentPage, pageSize) {
return {
image: path.join(__dirname, '/public/img/avatars/avatar1.png'),
width: pageSize.width,
opacity: 0.1
}; //, height: pageSize.height
},
pageSize: 'a4',
/* footer: function (currentPage, pageCount) {
return {
alignment: 'center',
margin: [40, 3, 40, 3],
columns: [
{
width: 30,
margin: [10, 0, 15, 0],
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [30, 30]
},
[
{
alignment: 'justify',
italics: true,
color: 'gray',
margin: [0, 7, 0, 0],
fontSize: 8,
columns: [
{ text: 'GRUPO ELITE FINCA RAÍZ S.A.S.' },
{ text: 'info@grupoelitefincaraiz.co' },
{
text: 'https://grupoelitefincaraiz.com',
link: 'https://grupoelitefincaraiz.com'
}
]
},
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 8,
columns: [
{ text: 'Nit: 901311748-3' },
{
text: '57 300-285-1046',
link: 'https://wa.me/573007861987?text=Hola'
},
{ text: 'Mz L lt 17 Urb. la granja, Turbaco' }
]
}
],
{
width: 30,
//alignment: 'right',
margin: [10, 0, 15, 0],
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [30, 30]
}
]
};
}, */
header: function (currentPage, pageCount, pageSize) {
// you can apply any logic and return any valid pdfmake element
return [
{
width: 20,
alignment: 'right',
margin: [10, 3, 10, 3],
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [20, 20]
}
];
},
info: {
title: 'Estado de cuenta',
author: 'RedElite',
subject: 'Detallado del estado de los pagos de un producto',
keywords: 'estado de cuenta',
creator: 'Grupo Elite',
producer: 'G.E.'
},
content: [
// pageBreak: 'before',
{
columns: [
[
{ text: Proyeccion[0].proyect, style: 'header' },
{ text: 'Estado de comisiones', style: 'subheader' }
/* {
text: `Doc. ${Proyeccion[0].document} Movil ${Proyeccion[0].clu} ${Proyeccion[0].mail}`,
italics: true, color: 'gray', fontSize: 9
} */
],
{
width: 100,
image: path.join(
__dirname,
Proyeccion[0].imagenes
? '/public' + Proyeccion[0].imagenes
: '/public/img/avatars/avatar.png'
),
fit: [100, 100]
}
]
},
{
style: 'tableBody',
color: '#444',
table: {
widths: ['auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto', '*', 'auto', '*'],
headerRows: 1,
// keepWithHeaderRows: 1,
body: cuerpo
}
}
/* { text: 'A continuacion se describiran los totales de la tabla anterior', style: 'subheader' },
{
ul: [
{
text: [
{ text: 'Total Abonado: ', fontSize: 10, bold: true },
{ text: `$${Moneda(totalAbonado)}\n`, italics: true, bold: true, fontSize: 11, color: 'green' },
{ text: NumeroALetras(totalAbonado).toLowerCase(), fontSize: 8, italics: true, color: 'gray' }
]
},
{
text: [
{ text: 'Total Mora: ', fontSize: 10, bold: true },
{ text: `$${Moneda(totalMora)}\n`, italics: true, bold: true, fontSize: 11, color: 'gray' },
{ text: NumeroALetras(totalMora).toLowerCase(), fontSize: 8, italics: true, color: 'gray' }
]
},
{
text: [
{ text: 'Mora Adeudada: ', fontSize: 10, bold: true },
{ text: `$${Moneda(moraAdeudada)}\n`, italics: true, bold: true, fontSize: 11, color: 'red' },
{ text: NumeroALetras(moraAdeudada).toLowerCase(), fontSize: 8, italics: true, color: 'gray' }
]
},
{
text: [
{ text: 'Total Saldo: ', fontSize: 10, bold: true },
{ text: `$${Moneda(totalDeuda)}\n`, italics: true, bold: true, fontSize: 11, color: 'blue' },
{ text: NumeroALetras(totalDeuda).toLowerCase(), fontSize: 8, italics: true, color: 'gray' }
]
}
]
}, */
/* {
fontSize: 11,
italics: true,
text: [
'\nLos montos que se muestran de color ',
{ text: 'azul ', bold: true, color: 'blue' },
'no se suman al total ',
{ text: 'abonado, ', bold: true, color: 'green' },
'ya que estos montos aun no cuentan con la ',
{ text: 'aprobacion ', bold: true, color: 'green' },
'del area de ',
{ text: 'contabilidad. ', bold: true },
'Una ves se hallan aprobado se sumaran al saldo ',
{ text: 'abonado.\n\n', bold: true, color: 'green' },
]
} */
],
styles: {
header: {
fontSize: 13,
bold: true,
margin: [0, 0, 0, 10]
},
subheader: {
fontSize: 11,
bold: true,
margin: [0, 5, 0, 2]
},
tableBody: {
fontSize: 8,
margin: [0, 5, 0, 5]
},
tableHeader: {
bold: true,
fontSize: 9,
color: 'black'
},
small: {
fontSize: 8,
italics: true,
color: 'gray',
alignment: 'right'
}
}
};
let ruta = path.join(__dirname, `/public/uploads/facturasdecobro-${Proyeccion[0].ids}.pdf`);
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream(ruta));
pdfDoc.end();
return `/uploads/facturasdecobro-${Proyeccion[0].ids}.pdf`;
}
}
async function Facturar(numFactura) {
const [factura] = await pool.query(`SELECT * FROM facturas WHERE id = ?`, numFactura);
if (factura) {
const cuerpo = [
[
{ text: 'Producto', style: 'tableHeader', alignment: 'center' },
{ text: `Vence`, style: 'tableHeader', alignment: 'center' },
{ text: '#', style: 'tableHeader', alignment: 'center' },
{ text: 'Precio', style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' }
]
];
// fecha hasta cuando se cobrara o congelara una mora en la que el sistema dejara de cobrar mora
//let endDate = moment(acuerdos[acuerdoActual]?.end).format('YYYY-MM-DD'); // fecha fin de un acuerdo prestablecido en la que el sistema dejara de congelar la mora
JSON.parse(factura.articles).map((e, i) => {
cuerpo.push([e[1], e[2], e[3], '$' + Cifra(e[4]), '$' + Cifra(e[5])]);
});
cuerpo.push(
[
{
text: 'TOTAL',
alignment: 'center',
colSpan: 4,
fontSize: 11,
bold: true,
color: 'black'
},
{},
{},
{},
{
text: '$' + Cifra(factura.total),
alignment: 'center',
fontSize: 11,
bold: true,
color: 'black'
}
],
[{ text: NumeroALetras(factura.total), style: 'smallx', colSpan: 5 }, {}, {}, {}, {}]
);
////////////////////////* CREAR PDF *//////////////////////////////
const printer = new PdfPrinter(Roboto);
let docDefinition = {
background: function (currentPage, pageSize) {
return {
image: path.join(__dirname, '/public/img/avatars/jgelvis.png'),
width: pageSize.width,
opacity: 0.1
};
},
pageSize: 'a4',
header: function (currentPage, pageCount, pageSize) {
return {
alignment: 'right',
margin: [10, 3, 10, 3],
columns: [
{
text: moment().format('lll'),
alignment: 'left',
margin: [10, 15, 15, 0],
italics: true,
color: 'gray',
fontSize: 7
},
{
width: 20,
alignment: 'right',
margin: [10, 3, 10, 3],
image: path.join(__dirname, '/public/img/avatars/jgelvis.png'),
fit: [20, 20]
}
]
};
},
info: {
title: 'Factura',
author: 'Inmovilii',
subject: 'Factura de venta',
keywords: 'Factura de venta de medicamentos',
creator: 'Inmovilii',
producer: 'IMOVI'
},
content: [
{
columns: [
{
width: 100,
image: path.join(__dirname, '/public/img/jgelvis.qr.png'),
fit: [100, 100]
},
[
{ text: 'JGELVIS', fontSize: 11, bold: true, margin: [0, 5, 0, 5] },
{ text: 'NIT: 14317921-1', italics: true, color: 'gray', fontSize: 9 },
{
text: 'TEL: 311-345-5739',
italics: true,
color: 'gray',
fontSize: 9
},
{
text: 'EMAIL: jlombanagelvis@gmail.com',
italics: true,
color: 'gray',
fontSize: 9
},
{
text: 'DIRECCION: K21a1#29f-110 faroles',
italics: true,
color: 'gray',
fontSize: 9
},
{
text: 'SANTA MARTA D.T.C.H',
italics: true,
color: 'gray',
fontSize: 9
},
{
text: 'Magdalena, Colombia 470002',
italics: true,
color: 'gray',
fontSize: 9
}
],
{
width: 100,
image: path.join(__dirname, '/public/img/avatars/jgelvis.png'),
fit: [100, 100]
}
]
},
{
columns: [
[
{ text: factura.adreess, style: 'subheader' },
{
text: `${factura.type} ${factura.doc} Movil ${factura.phone} ${factura.name}`,
italics: true,
color: 'gray',
fontSize: 9,
margin: [0, 0, 0, 10]
} /* ,
{
fontSize: 11,
italics: true,
text: [
'\nLa siguente ',
{ text: 'tabla ', bold: true, color: 'blue' },
'muestra los detalles de cada producto a facturar'
]
} */
],
{
text: 'FACTURA DE VENTA #' + factura.id,
fontSize: 13,
bold: true,
margin: [50, -15, 0, 0]
}
]
},
{
style: 'tableBody',
color: '#444',
table: {
widths: ['*', 'auto', 'auto', 'auto', 'auto'],
//headerRows: 1,
// keepWithHeaderRows: 1,
body: cuerpo
}
}
],
styles: {
header: {
fontSize: 13,
bold: true,
margin: [0, 0, 0, 10]
},
subheader: {
fontSize: 11,
bold: true,
margin: [0, 5, 0, 2]
},
tableBody: {
fontSize: 9,
margin: [0, 5, 0, 5]
},
tableHeader: {
bold: true,
fontSize: 9,
color: 'black'
},
small: {
fontSize: 8,
italics: true,
color: 'gray',
alignment: 'right'
},
smallx: {
fontSize: 7,
italics: true,
color: 'gray',
alignment: 'right'
},
tableBody2: {
margin: [0, 5, 0, 5]
},
tableHeader2: {
bold: true,
fontSize: 13,
color: 'black'
},
small2: {
fontSize: 9,
italics: true,
color: 'gray',
alignment: 'right'
}
}
};
let ruta = path.join(__dirname, `/public/uploads/facturadeventa-${factura.id}.pdf`);
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream(ruta));
pdfDoc.end();
await pool.query('UPDATE facturas SET ? WHERE id = ?', [
{ pdf: `/uploads/facturadeventa-${factura.id}.pdf` },
factura.id
]);
/* var dataFile = {
phone: '573012673944', //Proyeccion[0].movil,
body: `https://grupoelitefincaraiz.co/uploads/estadodecuenta-${Proyeccion[0].cparacion}.pdf`,
filename: `ESTADO DE CUENTA ${Proyeccion[0].cparacion}.pdf`
};
let r = await apiChatApi('sendFile', dataFile);
r.msg = Proyeccion[0].cparacion;
await EnviarEmail(
's4m1r.5a@gmail.com', //Proyeccion[0].email
`Estado de cuenta Lt: ${Proyeccion[0].n}`,
Proyeccion[0].nombre,
false,
'Grupo Elite te da la bienvenida',
[{ fileName: `Estado de cuenta ${Proyeccion[0].cparacion}.pdf`, ruta }]
); */
console.log(ruta);
return ruta;
} else {
return { sent: false };
}
}
async function Lista() {
const lista =
await pool.query(`SELECT m.*, SUM(IF(c.cantidad, c.cantidad, 0)) - SUM(IF(v.cantidad, v.cantidad, 0)) stock,
(SELECT precioVenta FROM compras k WHERE k.droga = m.id ORDER BY k.id DESC LIMIT 1) precio
FROM medicamentos m LEFT JOIN compras c ON c.droga = m.id LEFT JOIN ventas v ON v.producto = m.id GROUP BY m.id;`);
if (lista.length) {
const cuerpo = [
[
{ text: `Id`, style: 'tableHeader', alignment: 'center' },
{ text: 'Producto', style: 'tableHeader', alignment: 'center' },
{ text: 'Laboratorio', style: 'tableHeader', alignment: 'center' },
{ text: 'Clase', style: 'tableHeader', alignment: 'center' },
{ text: 'Stock', style: 'tableHeader', alignment: 'center' },
{ text: 'Precio', style: 'tableHeader', alignment: 'center' }
]
];
lista.map(e =>
cuerpo.push([e.id, e.nombre, e.laboratorio, e.clase, e.stock, '$' + Cifra(e.precio)])
);
////////////////////////* CREAR PDF *//////////////////////////////
const printer = new PdfPrinter(Roboto);
let docDefinition = {
background: function (currentPage, pageSize) {
return {
image: path.join(__dirname, '/public/img/avatars/jgelvis.png'),
width: pageSize.width,
opacity: 0.1
};
},
pageSize: 'a4',
header: function (currentPage, pageCount, pageSize) {
return {
alignment: 'right',
margin: [10, 3, 10, 3],
columns: [
{
text: moment().format('lll'),
alignment: 'left',
margin: [10, 15, 15, 0],
italics: true,
color: 'gray',
fontSize: 7
},
{
width: 20,
alignment: 'right',
margin: [10, 3, 10, 3],
image: path.join(__dirname, '/public/img/avatars/jgelvis.png'),
fit: [20, 20]
}
]
};
},
info: {
title: 'Factura',
author: 'Inmovilii',
subject: 'Factura de venta',
keywords: 'Factura de venta de medicamentos',
creator: 'Inmovilii',
producer: 'IMOVI'
},
content: [
{
columns: [
[
{ text: 'LISTA DE PRECIOS', style: 'header' },
{
fontSize: 11,
italics: true,
text: [
'\nLa siguente ',
{ text: 'tabla ', bold: true, color: 'blue' },
'muestra los detalles de cada producto a facturar'
]
}
],
{
width: 100,
image: path.join(__dirname, '/public/img/avatars/jgelvis.png'),
fit: [100, 100]
}
]
},
{
style: 'tableBody',
color: '#444',
table: {
widths: ['auto', 'auto', 'auto', 'auto', 'auto', 'auto'],
//headerRows: 1,
// keepWithHeaderRows: 1,
body: cuerpo
}
}
],
styles: {
header: {
fontSize: 13,
bold: true,
margin: [0, 0, 0, 10]
},
subheader: {
fontSize: 11,
bold: true,
margin: [0, 5, 0, 2]
},
tableBody: {
fontSize: 9,
margin: [0, 5, 0, 5]
},
tableHeader: {
bold: true,
fontSize: 9,
color: 'black'
},
small: {
fontSize: 8,
italics: true,
color: 'gray',
alignment: 'right'
},
smallx: {
fontSize: 7,
italics: true,
color: 'gray',
alignment: 'right'
},
tableBody2: {
margin: [0, 5, 0, 5]
},
tableHeader2: {
bold: true,
fontSize: 13,
color: 'black'
},
small2: {
fontSize: 9,
italics: true,
color: 'gray',
alignment: 'right'
}
}
};
let ruta = path.join(__dirname, `/public/uploads/listaprecio.pdf`);
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream(ruta));
pdfDoc.end();
/* var dataFile = {
phone: '573012673944', //Proyeccion[0].movil,
body: `https://grupoelitefincaraiz.co/uploads/estadodecuenta-${Proyeccion[0].cparacion}.pdf`,
filename: `ESTADO DE CUENTA ${Proyeccion[0].cparacion}.pdf`
};
let r = await apiChatApi('sendFile', dataFile);
r.msg = Proyeccion[0].cparacion;
await EnviarEmail(
's4m1r.5a@gmail.com', //Proyeccion[0].email
`Estado de cuenta Lt: ${Proyeccion[0].n}`,
Proyeccion[0].nombre,
false,
'Grupo Elite te da la bienvenida',
[{ fileName: `Estado de cuenta ${Proyeccion[0].cparacion}.pdf`, ruta }]
); */
return ruta;
} else {
return { sent: false };
}
}
async function EstadoDeCuenta(Orden) {
const Proyeccion = await pool.query(
`SELECT c.id idcuota, c.tipo, c.ncuota, c.fechs, r.montocuota, r.dias, r.tasa, r.dcto, s.fecharcb, r.fechaLMT,
r.totalmora, r.montocuota + r.totalmora totalcuota, s.fech, s.monto, r.saldocuota, l.valor - p.ahorro AS total,
o.proyect, k.pin AS cupon, s.stado, p.ahorro, l.mz, l.n, l.valor, p.vrmt2, l.mtr2, p.fecha, s.ids, r.saldomora,
s.formap, s.descp, k.descuento, p.id cparacion, cl.nombre, cl.documento, cl.email, cl.movil, c.mora, c.dto, o.imagenes,
c.cuota, c.diaspagados, c.diasmora, c.tasa tasamora, c.estado FROM cuotas c LEFT JOIN relacioncuotas r ON r.cuota = c.id
LEFT JOIN solicitudes s ON r.pago = s.ids INNER JOIN preventa p ON c.separacion = p.id
INNER JOIN productosd l ON p.lote = l.id INNER JOIN productos o ON l.producto = o.id
LEFT JOIN cupones k ON k.id = p.cupon INNER JOIN clientes cl ON p.cliente = cl.idc
WHERE p.id = ? ORDER BY TIMESTAMP(c.fechs) ASC, TIMESTAMP(s.fecharcb) ASC, TIMESTAMP(s.fech) ASC, r.id DESC;`,
Orden
);
const acuerdos = await pool.query(
`SELECT * FROM acuerdos a WHERE a.orden = ? AND a.estado IN(7, 9)`,
Orden
);
if (Proyeccion.length) {
const cuerpo = [];
const bodi = [['Fecha', 'Recibo', 'Estado', 'Forma de pago', 'Tipo', 'Monto']];
let totalAbonado = 0;
let totalMora = 0;
let moraAdeudada = 0;
let totalDeuda = 0;
let totalSaldo = 0;
let p = false;
let IDs = [];
let IdCuotas = [];
let acuerdoActual = 0; // variable que determina desde que acuerdo empezara la logica del algoritmo para generar los descuentos
let totalAcuerdos = acuerdos.length - 1; // se determina el numero de acuerdo vigentes o activos que el cliente a echo con la empresa a lo largo del tiempo
let startDate = moment(acuerdos[acuerdoActual]?.start || '2017-08-31').format('YYYY-MM-DD'); // fecha en la que entra en vigencia un acuerdo desde la que el sistema empesara a cobrar mora
let stopDate = moment(acuerdos[acuerdoActual]?.stop).format('YYYY-MM-DD'); // fecha hasta cuando se cobrara o congelara una mora en la que el sistema dejara de cobrar mora
let endDate = moment(acuerdos[acuerdoActual]?.end).format('YYYY-MM-DD'); // fecha fin de un acuerdo prestablecido en la que el sistema dejara de congelar la mora
let desto = acuerdos[acuerdoActual]?.dcto || 0;
Proyeccion.map((e, i) => {
const IDs2 = IDs.some(s => s === e.ids);
const idCqt = IdCuotas.some(s => s === e.idcuota);
const actoAmora =
acuerdos[acuerdoActual]?.end === undefined
? e.estado === 3 && !idCqt
: e.estado === 3 && !idCqt && e.fechs > endDate;
//totalAbonado += IDs2 ? 0 : e.monto ? e.monto : 0;
moraAdeudada += actoAmora ? e.mora : 0;
totalMora += e.totalmora + (actoAmora ? e.mora : 0) - e.saldomora;
totalSaldo += e.estado === 3 && !idCqt ? e.cuota : 0;
totalDeuda += actoAmora ? e.cuota + e.mora : 0;
if (e.fechs > endDate && acuerdoActual < totalAcuerdos) {
acuerdoActual++;
desto = acuerdos[acuerdoActual].dcto || 0;
startDate = moment(acuerdos[acuerdoActual]?.start || '2017-08-31').format('YYYY-MM-DD'); // fecha en la que entra en vigencia un acuerdo desde la que el sistema empesara a cobrar mora
stopDate = moment(acuerdos[acuerdoActual]?.stop).format('YYYY-MM-DD'); // fecha hasta cuando se cobrara o congelara una mora en la que el sistema dejara de cobrar mora
endDate = moment(acuerdos[acuerdoActual]?.end).format('YYYY-MM-DD'); // fecha fin de un acuerdo prestablecido en la que el sistema dejara de congelar la mora
} else if (e.fechs > endDate) {
desto = 0;
startDate = '2017-08-31'; // fecha desde la que el sistema empesara a cobrar mora
stopDate = null; // fecha hasta en la que el sistema dejara de cobrar mora
endDate = moment().format('YYYY-MM-DD');
}
const cobro = e.fechs > startDate && (!stopDate || stopDate > e.fechs) && e.mora; // determinara si debe cobrar mora en la cuota siguiente a analizar
const TotalDias = cobro
? moment().diff(e.fechs > stopDate ? stopDate : e.fechs, 'days') - e.diaspagados
: 0;
const TMora = cobro ? (TotalDias * e.cuota * e.tasamora) / 365 : 0; // valor de la mora
const TotalMora = TMora - TMora * desto;
const TotalCuota = e.cuota + TotalMora;
const Ids = IDs2 && e.monto ? false : true;
if (!i) {
cuerpo.push(
[
{ text: `Tipo`, style: 'tableHeader', alignment: 'center' },
{ text: 'F.Limite', style: 'tableHeader', alignment: 'center' },
{ text: 'Cuota', style: 'tableHeader', alignment: 'center' },
{ text: 'Dias', style: 'tableHeader', alignment: 'center' },
{ text: 'T.Usr', style: 'tableHeader', alignment: 'center' },
{ text: 'Dcto.', style: 'tableHeader', alignment: 'center' },
{ text: 'Mora', style: 'tableHeader', alignment: 'center' },
{ text: 'T.Cuota', style: 'tableHeader', alignment: 'center' },
{ text: 'F.Pago', style: 'tableHeader', alignment: 'center' },
{ text: 'Monto', style: 'tableHeader', alignment: 'center' },
{ text: 'C.Saldo', style: 'tableHeader', alignment: 'center' },
{ text: 'M.Saldo', style: 'tableHeader', alignment: 'center' }
],
[
e.tipo + '-' + e.ncuota,
moment(e.fechs).format('L'),
'$' + Cifra(e.montocuota ? e.montocuota : e.cuota),
e.montocuota ? e.dias : TotalDias,
e.montocuota ? (e.tasa * 100).toFixed(2) + '%' : (e.tasamora * 100).toFixed(2) + '%',
e.montocuota ? e.dcto * 100 + '%' : e.dto * 100 + '%',
'$' + Cifra(e.montocuota ? e.totalmora : e.mora),
'$' + Cifra(e.montocuota ? e.totalcuota : e.cuota + e.mora),
e.fecharcb
? Ids
? moment(e.fecharcb).format('L')
: '--/--/----'
: e.fech && (Ids ? moment(e.fech).format('L') : '--/--/----'),
Ids ? '$' + Cifra(e.monto || 0) : '$---,---,--',
'$' + Cifra(e.montocuota ? e.saldocuota : TotalCuota),
'$' + Cifra(e.saldomora)
]
);
} else {
!e.monto &&
p &&
cuerpo.push([
p.tipo + '-' + p.ncuota,
moment(p.fechs).format('L'),
'$' + Cifra(p.cuota),
p.s.TotalDias,
(e.tasamora * 100).toFixed(2) + '%',
e.dto * 100 + '%',
'$' + Cifra(p.s.TotalMora),
'$' + Cifra(p.s.TotalCuota),
'',
'$0',
'$' + Cifra(p.s.TotalCuota),
'$' + Cifra(p.saldomora)
]);
cuerpo.push([
e.tipo + '-' + e.ncuota,
moment(e.fechaLMT ? e.fechaLMT : e.fechs).format('L'),
'$' + Cifra(e.montocuota ? e.montocuota : e.cuota),
e.montocuota ? e.dias : TotalDias,
e.montocuota ? (e.tasa * 100).toFixed(2) + '%' : (e.tasamora * 100).toFixed(2) + '%',
e.montocuota ? e.dcto * 100 + '%' : e.dto * 100 + '%',
'$' + Cifra(e.montocuota ? e.totalmora : TotalMora),
'$' + Cifra(e.montocuota ? e.totalcuota : TotalCuota),
e.fecharcb
? Ids
? moment(e.fecharcb).format('L')
: '--/--/----'
: e.fech && (Ids ? moment(e.fech).format('L') : '--/--/----'),
Ids ? '$' + Cifra(e.monto || 0) : '$---,---,--',
'$' + Cifra(e.montocuota ? e.saldocuota : TotalCuota),
'$' + Cifra(e.saldomora)
]);
}
e.ids && IDs.push(e.ids);
p = e.monto && e.saldocuota ? e : false;
e.monto && e.saldocuota && (p.s = { TotalDias, TotalMora, TotalCuota });
IdCuotas.push(e.idcuota);
});
const PagosPendientes = await pool.query(
`SELECT s.fecharcb, s.fech, s.monto, s.stado, s.ids, s.formap, s.descp
FROM solicitudes s INNER JOIN preventa p ON s.orden = p.id
WHERE s.concepto IN('PAGO', 'ABONO', 'BONO') AND p.id = ?
AND s.stado IN(3, 4) ORDER BY TIMESTAMP(s.fecharcb) ASC, TIMESTAMP(s.fech) ASC;`,
Orden
);
if (PagosPendientes.length) {
PagosPendientes.map((e, i) => {
totalAbonado += e.stado != 4 ? 0 : e.monto;
bodi.push([
e.fecharcb ? moment(e.fecharcb).format('L') : '--/--/----',
`RC${e.ids}`,
{
text: e.stado === 4 ? 'Aprobado' : 'Pendiente',
color: e.stado === 4 ? 'green' : 'blue'
},
e.formap,
'ABONO',
{
text: '$' + Cifra(e.monto),
color: e.stado === 4 ? 'green' : 'blue',
decoration: e.stado !== 4 && 'lineThrough',
decorationStyle: e.stado !== 4 && 'double'
}
]);
});
bodi.sort((a, b) => {
return new Date(a[0]).getTime() - new Date(b[0]).getTime();
});
totalDeuda = Proyeccion[0].valor - Proyeccion[0].ahorro + totalMora - totalAbonado;
/* const indx = bodi.findIndex(e => e[1] == 'RCnull');
if (indx > -1) bodi.splice(indx, 1); */
}
//console.log(cuerpo);
bodi.push(
[
{
text: 'TOTAL ABONADO',
alignment: 'center',
colSpan: 4,
fontSize: 11,
bold: true,
color: 'black'
},
{},
{},
{},
{
text: '$' + Cifra(totalAbonado),
alignment: 'center',
colSpan: 2,
fontSize: 11,
bold: true,
color: 'black'
},
{}
],
[{ text: NumeroALetras(totalAbonado), style: 'smallx', colSpan: 6 }, {}, {}, {}, {}, {}],
[
{
text: 'SALDO A LA FECHA',
alignment: 'center',
colSpan: 4,
fontSize: 11,
bold: true,
color: 'black'
},
{},
{},
{},
{
text: '$' + Cifra(totalDeuda),
alignment: 'center',
colSpan: 2,
fontSize: 11,
bold: true,
color: 'black'
},
{}
],
[{ text: NumeroALetras(totalDeuda), style: 'smallx', colSpan: 6 }, {}, {}, {}, {}, {}]
);
////////////////////////* CREAR PDF *//////////////////////////////
const printer = new PdfPrinter(Roboto);
let docDefinition = {
background: function (currentPage, pageSize) {
return {
image: path.join(__dirname, '/public/img/avatars/avatar1.png'),
width: pageSize.width,
opacity: 0.1
}; //, height: pageSize.height
},
pageSize: 'a4',
/* footer: function (currentPage, pageCount) {
return {
alignment: 'center',
margin: [40, 3, 40, 3],
columns: [
{
width: 30,
margin: [10, 0, 15, 0],
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [30, 30]
},
[
{
alignment: 'justify',
italics: true,
color: 'gray',
margin: [0, 7, 0, 0],
fontSize: 8,
columns: [
{ text: 'GRUPO ELITE FINCA RAÍZ S.A.S.' },
{ text: 'info@grupoelitefincaraiz.co' },
{
text: 'https://grupoelitefincaraiz.com',
link: 'https://grupoelitefincaraiz.com'
}
]
},
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 8,
columns: [
{ text: 'Nit: 901311748-3' },
{
text: '57 300-285-1046',
link: 'https://wa.me/573007861987?text=Hola'
},
{ text: 'Mz L lt 17 Urb. la granja, Turbaco' }
]
}
],
{
width: 30,
//alignment: 'right',
margin: [10, 0, 15, 0],
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [30, 30]
}
]
};
}, */
header: function (currentPage, pageCount, pageSize) {
// you can apply any logic and return any valid pdfmake element
return {
alignment: 'right',
margin: [10, 3, 10, 3],
columns: [
{
text: moment().format('lll'),
alignment: 'left',
margin: [10, 15, 15, 0],
italics: true,
color: 'gray',
fontSize: 7
},
{
width: 20,
alignment: 'right',
margin: [10, 3, 10, 3],
image: path.join(
__dirname,
Proyeccion[0].imagenes
? '/public' + Proyeccion[0].imagenes
: '/public/img/avatars/avatar.png'
),
fit: [20, 20]
}
]
};
},
//watermark: { text: 'Grupo Elite', color: 'blue', opacity: 0.1, bold: true, italics: false, fontSize: 200 }, //, angle: 180
//watermark: { image: path.join(__dirname, '/public/img/avatars/avatar.png'), width: 100, opacity: 0.3, fit: [100, 100] }, //, angle: 180
info: {
title: 'Estado de cuenta',
author: 'RedElite',
subject: 'Detallado del estado de los pagos de un producto',
keywords: 'estado de cuenta',
creator: 'Grupo Elite',
producer: 'G.E.'
},
content: [
// pageBreak: 'before',
{
columns: [
[
{ text: 'ESTADO DE CUENTA', style: 'header' },
'Conoce aqui el estado de tus pagos y montos',
{ text: Proyeccion[0].nombre, style: 'subheader' },
{
text: `Doc. ${Proyeccion[0].documento} Movil ${Proyeccion[0].movil} ${Proyeccion[0].email}`,
italics: true,
color: 'gray',
fontSize: 9
},
{
style: 'tableBody',
color: '#444',
table: {
widths: ['auto', 'auto', 'auto', 'auto', 'auto', 'auto', 'auto'],
body: [
[
{
text: Proyeccion[0].proyect,
bold: true,
fontSize: 10,
color: 'blue',
colSpan: 5
},
{},
{},
{},
{},
{
text: `MZ: ${Proyeccion[0].mz ? Proyeccion[0].mz : 'No aplica'}`,
bold: true,
fontSize: 10,
color: 'blue'
},
{
text: `LT: ${Proyeccion[0].n}`,
bold: true,
fontSize: 10,
color: 'blue'
}
],
['Area', 'Vr.mtr2', 'Valor', 'Cupon', 'Dcto.', 'Ahorro', 'Total'],
[
{
text: Proyeccion[0].mtr2,
style: 'tableHeader',
alignment: 'center'
},
{
text: `$${Cifra(Proyeccion[0].vrmt2)}`,
style: 'tableHeader',
alignment: 'center'
},
{
text: `$${Cifra(Proyeccion[0].valor)}`,
style: 'tableHeader',
alignment: 'center'
},
{
text: Proyeccion[0].cupon,
style: 'tableHeader',
alignment: 'center'
},
{
text: `${Proyeccion[0].descuento}%`,
style: 'tableHeader',
alignment: 'center'
},
{
text: `- $${Cifra(Proyeccion[0].ahorro)}`,
style: 'tableHeader',
alignment: 'center'
},
{
text: `$${Cifra(Proyeccion[0].total)}`,
style: 'tableHeader',
alignment: 'center'
}
]
]
}
}
],
{
width: 100,
image: path.join(
__dirname,
Proyeccion[0].imagenes
? '/public' + Proyeccion[0].imagenes
: '/public/img/avatars/avatar.png'
),
fit: [100, 100]
}
]
},
{
style: 'tableBody2',
color: '#444',
table: {
widths: ['auto', 'auto', 'auto', 'auto', 'auto', 'auto'],
//headerRows: 4,
// keepWithHeaderRows: 1,
body: bodi
}
},
{
fontSize: 11,
italics: true,
text: [
'\nLa siguente ',
{ text: 'tabla ', bold: true, color: 'blue' },
'muestra los detalles de cada cuota de la financacion con su historial de pagos y montos.'
]
},
{
style: 'tableBody',
color: '#444',
table: {
widths: [
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto'
],
headerRows: 1,
// keepWithHeaderRows: 1,
body: cuerpo
}
},
{
text: 'A continuacion se describiran los totales de la tabla anterior',
style: 'subheader'
},
{
ul: [
{
text: [
{ text: 'Total Abonado: ', fontSize: 10, bold: true },
{
text: `$${Cifra(totalAbonado)}\n`,
italics: true,
bold: true,
fontSize: 11,
color: 'green'
},
{
text: NumeroALetras(totalAbonado).toLowerCase(),
fontSize: 8,
italics: true,
color: 'gray'
}
]
},
{
text: [
{ text: 'Total Mora: ', fontSize: 10, bold: true },
{
text: `$${Cifra(totalMora)}\n`,
italics: true,
bold: true,
fontSize: 11,
color: 'gray'
},
{
text: NumeroALetras(totalMora).toLowerCase(),
fontSize: 8,
italics: true,
color: 'gray'
}
]
},
{
text: [
{ text: 'Mora Adeudada: ', fontSize: 10, bold: true },
{
text: `$${Cifra(moraAdeudada)}\n`,
italics: true,
bold: true,
fontSize: 11,
color: 'red'
},
{
text: NumeroALetras(moraAdeudada).toLowerCase(),
fontSize: 8,
italics: true,
color: 'gray'
}
]
},
{
text: [
{ text: 'Saldo Capital: ', fontSize: 10, bold: true },
{
text: `$${Cifra(totalSaldo)}\n`,
italics: true,
bold: true,
fontSize: 11,
color: 'red'
},
{
text: NumeroALetras(totalSaldo).toLowerCase(),
fontSize: 8,
italics: true,
color: 'gray'
}
]
},
{
text: [
{ text: 'Total Saldo: ', fontSize: 10, bold: true },
{
text: `$${Cifra(totalDeuda)}\n`,
italics: true,
bold: true,
fontSize: 11,
color: 'blue'
},
{
text: NumeroALetras(totalDeuda).toLowerCase(),
fontSize: 8,
italics: true,
color: 'gray'
}
]
}
]
}
/* {
fontSize: 11,
italics: true,
text: [
'\nLos montos que se muestran de color ',
{ text: 'azul ', bold: true, color: 'blue' },
'no se suman al total ',
{ text: 'abonado, ', bold: true, color: 'green' },
'ya que estos montos aun no cuentan con la ',
{ text: 'aprobacion ', bold: true, color: 'green' },
'del area de ',
{ text: 'contabilidad. ', bold: true },
'Una ves se hallan aprobado se sumaran al saldo ',
{ text: 'abonado.\n\n', bold: true, color: 'green' },
]
} */
],
styles: {
header: {
fontSize: 13,
bold: true,
margin: [0, 0, 0, 10]
},
subheader: {
fontSize: 11,
bold: true,
margin: [0, 5, 0, 2]
},
tableBody: {
fontSize: 7,
margin: [0, 5, 0, 5]
},
tableHeader: {
bold: true,
fontSize: 9,
color: 'black'
},
small: {
fontSize: 8,
italics: true,
color: 'gray',
alignment: 'right'
},
smallx: {
fontSize: 7,
italics: true,
color: 'gray',
alignment: 'right'
},
tableBody2: {
margin: [0, 5, 0, 5]
},
tableHeader2: {
bold: true,
fontSize: 13,
color: 'black'
},
small2: {
fontSize: 9,
italics: true,
color: 'gray',
alignment: 'right'
}
}
};
let ruta = path.join(
__dirname,
`/public/uploads/estadodecuenta-${Proyeccion[0].cparacion}.pdf`
);
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream(ruta));
pdfDoc.end();
/* var dataFile = {
phone: '573012673944', //Proyeccion[0].movil,
body: `https://grupoelitefincaraiz.co/uploads/estadodecuenta-${Proyeccion[0].cparacion}.pdf`,
filename: `ESTADO DE CUENTA ${Proyeccion[0].cparacion}.pdf`
};
let r = await apiChatApi('sendFile', dataFile);
r.msg = Proyeccion[0].cparacion;
await EnviarEmail(
's4m1r.5a@gmail.com', //Proyeccion[0].email
`Estado de cuenta Lt: ${Proyeccion[0].n}`,
Proyeccion[0].nombre,
false,
'Grupo Elite te da la bienvenida',
[{ fileName: `Estado de cuenta ${Proyeccion[0].cparacion}.pdf`, ruta }]
); */
console.log(ruta);
return ruta; //JSON.stringify(estado);
} else {
return { sent: false };
}
}
async function informes(data) {
// arreglar esto
const { datos, maxDateFilter, minDateFilter } = data;
const ids = datos.replace(/\[|\]/g, '');
const pagos = await pool.query(
`SELECT s.fech, c.fechs, s.monto, u.pin, c.cuota, s.img, pd.valor,
cpb.monto montoa, e.lugar, e.otro, pr.ahorro, cl.email, s.facturasvenc, cp.producto, s.pdf, s.acumulado,
u.fullname, s.aprueba, pr.descrip, cpb.producto ordenanu, cl.documento, cl.idc, cl.movil, cl.nombre,
s.recibo, c.tipo, c.ncuota, p.proyect, pd.mz, u.cel, pr.tipobsevacion, s.fecharcb, pd.n, s.stado,
cp.pin bono, cp.monto mount, cp.motivo, cp.concept, s.formap, s.concepto, pd.id, pr.lote, e.id extr,
e.consignado, e.date, e.description, s.ids, s.descp, pr.id cparacion, pd.estado, s.bonoanular, s.aprobado
FROM solicitudes s LEFT JOIN cuotas c ON s.pago = c.id LEFT JOIN preventa pr ON s.orden = pr.id
INNER JOIN productosd pd ON s.lt = pd.id LEFT JOIN extrabanco e ON s.extrato = e.id INNER JOIN productos p
ON pd.producto = p.id LEFT JOIN users u ON pr.asesor = u.id LEFT JOIN clientes cl ON pr.cliente = cl.idc
LEFT JOIN cupones cp ON s.bono = cp.id LEFT JOIN cupones cpb ON s.bonoanular = cpb.id
WHERE s.concepto IN('PAGO','ABONO') AND ids IN(${ids}) ORDER BY s.ids`
);
const minDate = moment(parseFloat(minDateFilter)).format('ll');
const maxDate = moment(parseFloat(maxDateFilter)).format('ll');
const minD = moment(parseFloat(minDateFilter)).format('YYYY-MM-DD');
const maxD = moment(parseFloat(maxDateFilter)).format('YYYY-MM-DD');
//console.log(minDateFilter, maxDateFilter, minDate, maxDate, minD, maxD);
const bank = [];
let transaccionado = 0;
let efectivo = 0;
const totalesBancos = {
totalEntrada: 0,
totalSinSoporte: 0,
totalExtSinSoporte: 0,
totalExtratos: 0,
totalConSoporte: 0,
totalExtConSoporte: 0,
bancos: {}
};
const cuerpo = [
[
{ text: `Pago`, style: 'tableHeader', alignment: 'center' },
{ text: `Proyecto`, style: 'tableHeader', alignment: 'center' },
{ text: 'Mz', style: 'tableHeader', alignment: 'center' },
{ text: 'Lt', style: 'tableHeader', alignment: 'center' },
{ text: 'Estado', style: 'tableHeader', alignment: 'center' },
{ text: 'F.Rcb.', style: 'tableHeader', alignment: 'center' },
{ text: 'Monto', style: 'tableHeader', alignment: 'center' },
{ text: 'Extrato', style: 'tableHeader', alignment: 'center' },
{ text: 'F.Extrato', style: 'tableHeader', alignment: 'center' },
{ text: 'Cuenta', style: 'tableHeader', alignment: 'center' },
{ text: 'Consignado', style: 'tableHeader', alignment: 'center' }
]
];
const extratos = await pool.query(
`SELECT e.*, COUNT(s.ids) recibos, SUM(s.monto) monto, e.consignado - SUM(s.monto) diff
FROM extrabanco e LEFT JOIN solicitudes s ON s.extrato = e.id WHERE e.consignado > 0 AND e.date
BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) GROUP BY e.id ORDER BY e.date, e.otro`,
[minD, maxD]
);
await extratos.map(e => {
totalesBancos.totalEntrada += e.consignado;
totalesBancos.totalSinSoporte += !e.recibos ? e.consignado : 0;
totalesBancos.totalExtSinSoporte += !e.recibos ? 1 : 0;
totalesBancos.totalExtratos++;
if (!bank.length || !bank.some(r => r === e.otro)) {
totalesBancos.bancos[e.otro] = {
totalEntrada: e.consignado,
totalSinSoporte: !e.recibos ? e.consignado : 0,
totalExtSinSoporte: !e.recibos ? 1 : 0,
totalConSoporte: 0,
totalExtConSoporte: 0,
totalExtratos: 1
};
bank.push(e.otro);
} else {
totalesBancos.bancos[e.otro].totalEntrada += e.consignado;
totalesBancos.bancos[e.otro].totalSinSoporte += !e.recibos ? e.consignado : 0;
totalesBancos.bancos[e.otro].totalExtSinSoporte += !e.recibos ? 1 : 0;
totalesBancos.bancos[e.otro].totalExtratos++;
//console.log(totalesBancos.bancos[e.otro].totalEntrada, e.consignado, e.otro);
}
});
const bancos = await Object.keys(totalesBancos.bancos).map((a, i) => {
return {
alignment: 'justify',
margin: [0, 0, 0, 5],
columns: [
{
text: [
{
text: 'Cuenta\n',
fontSize: 8,
italics: true,
color: 'gray'
},
{
text: a,
fontSize: 10,
bold: true,
color: 'green'
}
]
},
{
text: [
{
text: 'Total Ingreso Banco\n',
fontSize: 8,
italics: true,
color: 'gray'
},
{
text: `$${Moneda(totalesBancos.bancos[a].totalEntrada)}\n`,
fontSize: 10,
bold: true,
color: 'blue'
}
]
},
{
text: [
{
text: 'Total no soportado\n',
fontSize: 8,
italics: true,
color: 'gray'
},
{
text: `$${Moneda(totalesBancos.bancos[a].totalSinSoporte)}\n`,
fontSize: 10,
bold: true,
color: 'blue'
}
]
},
{
text: [
{
text: 'Total extratos: ',
fontSize: 8,
italics: true,
color: 'gray'
},
{
text: `${totalesBancos.bancos[a].totalExtratos}\n`,
fontSize: 9,
bold: true,
color: 'red'
},
{
text: 'Sin soporte: ',
fontSize: 8,
italics: true,
color: 'gray'
},
{
text: `${totalesBancos.bancos[a].totalExtSinSoporte}\n`,
fontSize: 9,
bold: true,
color: 'red'
}
]
}
]
};
});
await bancos.push({
alignment: 'justify',
margin: [0, 0, 0, 5],
columns: [
{
text: [
{
text: '.\n',
fontSize: 8,
italics: true,
color: 'gray'
},
{
text: 'TOTALES',
fontSize: 10,
bold: true,
color: 'green'
}
]
},
{
text: [
{
text: 'Total Ingreso Banco\n',
fontSize: 8,
italics: true,
color: 'gray'
},
{
text: `$${Moneda(totalesBancos.totalEntrada)}\n`,
fontSize: 10,
bold: true,
color: 'blue'
}
]
},
{
text: [
{
text: 'Total no soportado\n',
fontSize: 8,
italics: true,
color: 'gray'
},
{
text: `$${Moneda(totalesBancos.totalSinSoporte)}\n`,
fontSize: 10,
bold: true,
color: 'blue'
}
]
},
{
text: [
{
text: 'Total extratos: ',
fontSize: 8,
italics: true,
color: 'gray'
},
{ text: `${totalesBancos.totalExtratos}\n`, fontSize: 9, bold: true, color: 'red' },
{
text: 'Sin soporte: ',
fontSize: 8,
italics: true,
color: 'gray'
},
{ text: `${totalesBancos.totalExtSinSoporte}\n`, fontSize: 9, bold: true, color: 'red' }
]
}
]
});
await pagos.map((a, i) => {
let estado;
switch (a.stado) {
case 4:
estado = {
text: 'Aprobado',
color: 'green'
};
break;
case 3:
estado = {
text: 'Pendiente',
color: 'blue'
};
break;
case 6:
estado = {
text: 'Declinado',
color: 'red'
};
break;
}
transaccionado += a.extr ? a.monto : 0;
efectivo += !a.extr ? a.monto : 0;
if (a.otro) {
totalesBancos.bancos[a.otro].totalConSoporte += a.monto;
totalesBancos.bancos[a.otro].totalExtConSoporte++;
totalesBancos.totalConSoporte += a.monto;
totalesBancos.totalExtConSoporte++;
}
const extrato =
!a.extr && a.stado == 3
? { text: 'PENDIENTE POR APROBAR', colSpan: 4, alignment: 'center', color: 'blue' }
: !a.extr && a.stado == 4
? { text: 'EFECTIVO. SIN EXTRATO', colSpan: 4, alignment: 'center', color: 'green' }
: !a.extr && a.stado == 6
? { text: 'SIN NINGUNA INFORMACION', colSpan: 4, alignment: 'center', color: 'green' }
: a.extr && a.stado == 6
? { text: a.extr + ' DESASOCIAR EXTRATO', colSpan: 4, alignment: 'center', color: 'green' }
: a.extr;
cuerpo.push([
{ text: a.ids, link: 'https://grupoelitefincaraiz.com' + a.img, color: 'blue' },
a.proyect,
a.mz,
a.n,
estado,
a.fecharcb ? moment(a.fecharcb).format('L') : 'sin definir',
'$' + Moneda(a.monto),
extrato,
a.date ? moment(a.date).format('L') : '',
a.otro,
'$' + Moneda(a.consignado)
]);
});
//console.log(minDate, maxDate, totalesBancos, cuerpo);
const printer = new PdfPrinter(Roboto);
let docDefinition = {
background: function (currentPage, pageSize) {
return {
image: path.join(__dirname, '/public/img/avatars/avatar1.png'),
width: pageSize.width,
opacity: 0.1
}; //, height: pageSize.height
},
pageSize: 'a4',
footer: function (currentPage, pageCount) {
return {
alignment: 'center',
margin: [40, 3, 40, 3],
columns: [
{
width: 30,
margin: [10, 0, 15, 0],
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [30, 30]
},
[
{
alignment: 'justify',
italics: true,
color: 'gray',
margin: [0, 7, 0, 0],
fontSize: 8,
columns: [
{ text: 'GRUPO ELITE FINCA RAÍZ S.A.S.' },
{ text: 'info@grupoelitefincaraiz.co' },
{
text: 'https://grupoelitefincaraiz.com',
link: 'https://grupoelitefincaraiz.com'
}
]
},
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 8,
columns: [
{ text: 'Nit: 901311748-3' },
{
text: '57 300-285-1046',
link: 'https://wa.me/573007861987?text=Hola'
},
{ text: 'Mz L lt 17 Urb. la granja, Turbaco' }
]
}
],
{
width: 30,
//alignment: 'right',
margin: [10, 0, 15, 0],
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [30, 30]
}
]
};
},
header: function (currentPage, pageCount, pageSize) {
// you can apply any logic and return any valid pdfmake element
return {
alignment: 'right',
margin: [10, 3, 10, 3],
columns: [
{
text: moment().format('lll'),
alignment: 'left',
margin: [10, 15, 15, 0],
italics: true,
color: 'gray',
fontSize: 7
},
{
width: 20,
alignment: 'right',
margin: [10, 3, 10, 3],
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [30, 30]
}
]
};
},
//watermark: { text: 'Grupo Elite', color: 'blue', opacity: 0.1, bold: true, italics: false, fontSize: 200 }, //, angle: 180
//watermark: { image: path.join(__dirname, '/public/img/avatars/avatar.png'), width: 100, opacity: 0.3, fit: [100, 100] }, //, angle: 180
info: {
title: 'Reporte de ingresos',
author: 'RedElite',
subject: 'Detallado del estado de los pagos vs los extratos',
keywords: 'Pagos y Abonos',
creator: 'Red Elite',
producer: 'R.E.'
},
content: [
{
margin: [0, 0, 0, 15],
columns: [
{
width: 'auto',
text: [
{ text: 'INFORME DE INGRESOS VS EXTRATOS\n', style: 'header' },
'Relacion de pagos y extractos bancarios\n\n'
]
},
[
{ text: 'PERIODOS\n', fontSize: 8, bold: true, alignment: 'center' },
{
width: '*',
margin: [50, 0, 0, 0],
alignment: 'justify',
columns: [
{
text: [
{
text: 'Desde\n',
fontSize: 6,
italics: true,
color: 'gray'
},
{ text: minDate, fontSize: 8, bold: true }
]
},
{
text: [
{
text: 'Hasta\n',
fontSize: 6,
italics: true,
color: 'gray'
},
{ text: maxDate, fontSize: 8, bold: true }
]
}
]
}
]
]
},
bancos,
{
style: 'tableBody',
color: '#444',
table: {
widths: [
'auto',
'*',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto',
'auto'
],
headerRows: 1,
// keepWithHeaderRows: 1,
body: cuerpo
}
},
{
margin: [0, 0, 0, 15],
text: 'Todos los que no esten asociados a un extrato, se consideran dinero en efectivo',
color: 'gray',
fontSize: 9
},
{
text: 'A continuacion se describiran los totales de la tabla anterior',
style: 'subheader'
},
{
ul: [
{
text: [
{
text: totalesBancos.totalExtConSoporte + ' EXTRATOS TOTAL TRANSACCIONADO: ',
fontSize: 10,
bold: true
},
{
text: `$${Moneda(transaccionado)}\n`,
italics: true,
bold: true,
fontSize: 10,
color: 'blue'
},
{
text: NumeroALetras(transaccionado).toLowerCase(),
fontSize: 8,
italics: true,
color: 'gray'
}
]
},
{
text: [
{ text: 'TOTAL EFECTIVO: ', fontSize: 10, bold: true },
{
text: `$${Moneda(efectivo)}\n`,
italics: true,
bold: true,
fontSize: 10,
color: 'blue'
},
{
text: NumeroALetras(efectivo).toLowerCase(),
fontSize: 8,
italics: true,
color: 'gray'
}
]
},
{
text: [
{
text: 'TOTAL INGRESADO: ',
fontSize: 10,
bold: true
},
{
text: `$${Moneda(transaccionado + efectivo)}\n`,
italics: true,
bold: true,
fontSize: 10,
color: 'blue'
},
{
text: NumeroALetras(transaccionado + efectivo).toLowerCase(),
fontSize: 8,
italics: true,
color: 'gray'
}
]
}
]
}
],
styles: {
header: {
fontSize: 13,
bold: true,
margin: [0, 0, 0, 5]
},
subheader: {
fontSize: 11,
bold: true,
margin: [0, 5, 0, 2]
},
tableBody: {
fontSize: 7,
margin: [0, 5, 0, 5]
},
tableHeader: {
bold: true,
fontSize: 9,
color: 'black'
},
small: {
fontSize: 8,
italics: true,
color: 'gray',
alignment: 'right'
},
tableBody2: {
margin: [0, 5, 0, 5]
},
tableHeader2: {
bold: true,
fontSize: 13,
color: 'black'
},
small2: {
fontSize: 9,
italics: true,
color: 'gray',
alignment: 'right'
}
}
};
let ruta = path.join(__dirname, `/public/uploads/informes.pdf`);
let pdfDoc = await printer.createPdfKitDocument(docDefinition);
await pdfDoc.pipe(fs.createWriteStream(ruta));
await pdfDoc.end();
return ruta;
}
async function ReciboDeCaja(movil, nombre, author) {
const estado =
await pool.query(`SELECT pd.valor - p.ahorro AS total, pt.proyect, cu.pin AS cupon, cp.pin AS bono, s.stado,
p.ahorro, pd.mz, pd.n, pd.valor, p.vrmt2, p.fecha, s.fech, s.ids, s.formap, s.descp,s.monto, s.img, cu.descuento, p.id cparacion,
c.nombre, c.documento, c.email, c.movil, cp.monto mtb, pd.mtr2 FROM solicitudes s INNER JOIN productosd pd ON s.lt = pd.id
INNER JOIN productos pt ON pd.producto = pt.id INNER JOIN preventa p ON pd.id = p.lote
LEFT JOIN cupones cu ON cu.id = p.cupon LEFT JOIN cupones cp ON s.bono = cp.id
INNER JOIN clientes c ON p.cliente = c.idc LEFT JOIN clientes c2 ON p.cliente2 = c2.idc
LEFT JOIN clientes c3 ON p.cliente3 = c3.idc LEFT JOIN clientes c4 ON p.cliente4 = c4.idc
WHERE s.stado != 6 AND s.concepto IN('PAGO', 'ABONO') AND p.tipobsevacion IS NULL
AND (c.movil LIKE '%${cel}%' OR c.code LIKE '%${cel}%' OR c.nombre = '${nombre}'
OR c2.movil LIKE '%${cel}%' OR c2.code LIKE '%${cel}%' OR c2.nombre = '${nombre}'
OR c3.movil LIKE '%${cel}%' OR c3.code LIKE '%${cel}%' OR c3.nombre = '${nombre}'
OR c4.movil LIKE '%${cel}%' OR c4.code LIKE '%${cel}%' OR c4.nombre = '${nombre}')`);
if (estado.length) {
const cuerpo = [];
let totalAbonado = 0;
estado.map((e, i) => {
totalAbonado += e.stado === 4 ? e.monto : 0;
if (!i) {
cuerpo.push(
[
{
text: `Area: ${e.mtr2} mt2`,
style: 'tableHeader',
colSpan: 2,
alignment: 'center'
},
{},
{
text: `Vr Mt2: $${Moneda(e.vrmt2)}`,
style: 'tableHeader',
colSpan: 2,
alignment: 'center'
},
{},
{
text: '$' + Moneda(e.valor),
style: 'tableHeader',
alignment: 'center',
colSpan: 2
},
{}
],
[
'Cupon',
'Dsto',
{ text: 'Ahorro', colSpan: 2 },
{},
{ text: `Total lote`, colSpan: 2 },
{}
],
[
{ text: e.cupon, style: 'tableHeader', alignment: 'center' },
{
text: `${e.descuento}%`,
style: 'tableHeader',
alignment: 'center'
},
{
text: `-$${Moneda(e.ahorro)}`,
style: 'tableHeader',
colSpan: 2,
alignment: 'center'
},
{},
{
text: `$${Moneda(e.total)}`,
style: 'tableHeader',
colSpan: 2,
alignment: 'center'
},
{}
],
['Fecha', 'Recibo', 'Estado', 'Forma de pago', 'Tipo', 'Monto'],
[
moment(e.fech).format('L'),
`RC${e.ids}`,
{
text: e.stado === 4 ? 'Aprobado' : 'Pendiente',
color: e.stado === 4 ? 'green' : 'blue'
},
e.formap,
e.descp,
{
text: '$' + Moneda(e.monto),
color: e.stado === 4 ? 'green' : 'blue',
decoration: e.stado !== 4 && 'lineThrough',
decorationStyle: e.stado !== 4 && 'double'
}
]
);
} else {
cuerpo.push([
moment(e.fech).format('L'),
`RC${e.ids}`,
{
text: e.stado === 4 ? 'Aprobado' : 'Pendiente',
color: e.stado === 4 ? 'green' : 'blue'
},
e.formap,
e.descp,
{
text: '$' + Moneda(e.monto),
color: e.stado === 4 ? 'green' : 'blue',
decoration: e.stado !== 4 && 'lineThrough',
decorationStyle: e.stado !== 4 && 'double'
}
]);
}
});
cuerpo.push(
[
{
text: 'TOTAL ABONADO',
style: 'tableHeader',
alignment: 'center',
colSpan: 4
},
{},
{},
{},
{
text: '$' + Moneda(totalAbonado),
style: 'tableHeader',
alignment: 'center',
colSpan: 2
},
{}
],
[{ text: NumeroALetras(totalAbonado), style: 'small', colSpan: 6 }, {}, {}, {}, {}, {}],
[
{
text: 'SALDO A LA FECHA',
style: 'tableHeader',
alignment: 'center',
colSpan: 4
},
{},
{},
{},
{
text: '$' + Moneda(estado[0].total - totalAbonado),
style: 'tableHeader',
alignment: 'center',
colSpan: 2
},
{}
],
[
{
text: NumeroALetras(estado[0].total - totalAbonado),
style: 'small',
colSpan: 6
},
{},
{},
{},
{},
{}
]
);
////////////////////////* CREAR PDF *//////////////////////////////
const printer = new PdfPrinter(Roboto);
let docDefinition = {
background: function (currentPage, pageSize) {
return {
image: path.join(__dirname, '/public/img/avatars/avatar1.png'),
width: pageSize.width,
opacity: 0.1
}; //, height: pageSize.height
},
pageSize: {
width: 595.28,
height: 'auto'
},
/* footer: function (currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; },
header: function (currentPage, pageCount, pageSize) {
// you can apply any logic and return any valid pdfmake element
return [
{ text: 'simple text', alignment: (currentPage % 2) ? 'right' : 'right' },
{ canvas: [{ type: 'rect', x: 170, y: 32, w: pageSize.width - 170, h: 40 }] }
]
}, */
//watermark: { text: 'Grupo Elite', color: 'blue', opacity: 0.1, bold: true, italics: false, fontSize: 200 }, //, angle: 180
//watermark: { image: path.join(__dirname, '/public/img/avatars/avatar.png'), width: 100, opacity: 0.3, fit: [100, 100] }, //, angle: 180
info: {
title: 'Estado de cuenta',
author: 'RedElite',
subject: 'Detallado del estado de los pagos de un producto',
keywords: 'estado de cuenta',
creator: 'Grupo Elite',
producer: 'G.E.'
},
content: [
// pageBreak: 'before',
{
columns: [
[
{ text: 'ESTADO DE CUENTA', style: 'header' },
'Conoce aqui el estado el estado de tus pagos y montos',
{ text: estado[0].nombre, style: 'subheader' },
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 9,
margin: [0, 0, 0, 5],
columns: [
{ text: `Doc. ${estado[0].documento}` },
{ text: `Movil ${estado[0].movil}` },
{ text: estado[0].email }
]
},
{
alignment: 'justify',
italics: true,
columns: [
{ width: 250, text: estado[0].proyect },
{ text: `MZ: ${estado[0].mz ? estado[0].mz : 'No aplica'}` },
{ text: `LT: ${estado[0].n}` }
]
}
],
{
width: 100,
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [100, 100]
}
]
},
{
style: 'tableBody',
color: '#444',
table: {
widths: ['auto', 'auto', 'auto', 'auto', 'auto', 'auto'],
headerRows: 4,
// keepWithHeaderRows: 1,
body: cuerpo
}
},
{
fontSize: 11,
italics: true,
text: [
'\nLos montos que se muestran de color ',
{ text: 'azul ', bold: true, color: 'blue' },
'no se suman al total ',
{ text: 'abonado, ', bold: true, color: 'green' },
'ya que estos montos aun no cuentan con la ',
{ text: 'aprobacion ', bold: true, color: 'green' },
'del area de ',
{ text: 'contabilidad. ', bold: true },
'Una ves se hallan aprobado se sumaran al saldo ',
{ text: 'abonado.\n\n', bold: true, color: 'green' }
]
},
{
columns: [
{
width: 100,
qr: 'https://grupoelitefincaraiz.com',
fit: '50',
foreground: 'yellow',
background: 'black'
},
[
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 10,
columns: [
{ text: 'GRUPO ELITE FINCA RAÍZ S.A.S.' },
{
text: 'https://grupoelitefincaraiz.com',
link: 'https://grupoelitefincaraiz.com'
}
]
},
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 10,
columns: [{ text: 'Nit: 901311748-3' }, { text: 'info@grupoelitefincaraiz.co' }]
},
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 10,
columns: [
{ text: 'Mz L lt 17 Urb. la granja, Turbaco' },
{
text: '57 300-285-1046',
link: 'https://wa.me/573007861987?text=Hola'
}
]
}
]
]
}
],
styles: {
header: {
fontSize: 18,
bold: true,
margin: [0, 0, 0, 10]
},
subheader: {
fontSize: 16,
bold: true,
margin: [0, 5, 0, 2]
},
tableBody: {
margin: [0, 5, 0, 5]
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
},
small: {
fontSize: 9,
italics: true,
color: 'gray',
alignment: 'right'
}
}
};
let ruta = path.join(__dirname, `/public/uploads/estadodecuenta-${estado[0].cparacion}.pdf`);
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream(ruta));
pdfDoc.end();
var dataFile = {
phone: author,
body: `https://grupoelitefincaraiz.co/uploads/estadodecuenta-${estado[0].cparacion}.pdf`,
filename: `ESTADO DE CUENTA ${estado[0].cparacion}.pdf`
};
let r = await apiChatApi('sendFile', dataFile);
r.msg = estado[0].cparacion;
await EnviarEmail(
estado[0].email,
`Estado de cuenta Lt: ${estado[0].n}`,
estado[0].nombre,
false,
'Grupo Elite te da la bienvenida',
[{ fileName: `Estado de cuenta ${estado[0].cparacion}.pdf`, ruta }]
);
return r; //JSON.stringify(estado);
} else {
return { sent: false };
}
}
async function Saldos(lote, fecha, solicitud) {
console.log(lote, solicitud, fecha);
const u = await pool.query(`SELECT * FROM solicitudes WHERE concepto IN('PAGO', 'ABONO')
AND lt = ${lote} AND stado = 3 AND TIMESTAMP(fech) < '${fecha}' AND ids != ${solicitud}`);
//console.log(u)
if (u.length > 0) return false;
const r = await pool.query(`SELECT SUM(s.monto) AS monto1,
SUM(if (s.formap != 'BONO' AND s.bono IS NOT NULL, c.monto, 0)) AS monto
FROM solicitudes s LEFT JOIN cupones c ON s.bono = c.id
WHERE s.concepto IN('PAGO', 'ABONO') AND s.stado = 4 AND s.lt = ${lote}
AND TIMESTAMP(s.fech) < '${fecha}' AND s.ids != ${solicitud}`);
var l = r[0].monto1 || 0,
k = r[0].monto || 0;
var acumulado = l + k;
return acumulado;
}
async function RecibosCaja(movil, nombre, author, reci) {
const cel = movil.slice(-10);
let sql = `SELECT l.valor - p.ahorro AS total, d.proyect, cu.pin AS cupon, cp.pin AS bono, s.stado, p.lote, c.direccion,
p.ahorro, l.mz, l.n, l.valor, p.vrmt2, p.fecha, s.fech, s.ids, s.formap, s.descp,s.monto, s.img, cu.descuento, p.id cparacion,
c.nombre, c.documento, c.email, c.movil, cp.monto mtb, l.mtr2, k.ncuota, k.mora, s.concepto FROM solicitudes s INNER JOIN productosd l ON s.lt = l.id
INNER JOIN productos d ON l.producto = d.id INNER JOIN preventa p ON l.id = p.lote
LEFT JOIN cupones cu ON cu.id = p.cupon LEFT JOIN cupones cp ON s.bono = cp.id
LEFT JOIN cuotas k ON k.id = s.pago
INNER JOIN clientes c ON p.cliente = c.idc LEFT JOIN clientes c2 ON p.cliente2 = c2.idc
LEFT JOIN clientes c3 ON p.cliente3 = c3.idc LEFT JOIN clientes c4 ON p.cliente4 = c4.idc
WHERE s.stado != 6 AND s.concepto IN('PAGO', 'ABONO') AND p.tipobsevacion IS NULL `;
sql +=
reci !== '##'
? 'AND s.ids = ' + reci
: `AND (c.movil LIKE '%${cel}%' OR c.code LIKE '%${cel}%' OR c.nombre = '${nombre}'
OR c2.movil LIKE '%${cel}%' OR c2.code LIKE '%${cel}%' OR c2.nombre = '${nombre}'
OR c3.movil LIKE '%${cel}%' OR c3.code LIKE '%${cel}%' OR c3.nombre = '${nombre}'
OR c4.movil LIKE '%${cel}%' OR c4.code LIKE '%${cel}%' OR c4.nombre = '${nombre}')`;
sql += ' ORDER BY s.ids';
const recibos = await pool.query(sql);
let archivos = [];
console.log(recibos);
if (recibos.length) {
const printer = new PdfPrinter(Roboto);
for (i = 0; i < recibos.length; i++) {
let e = recibos[i];
//if (i === 3) { continue; } \n
const saldo = await Saldos(e.lote, e.fech, e.ids);
////////////////////////* CREAR PDF *//////////////////////////////
let docDefinition = {
background: function (currentPage, pageSize) {
return {
image: path.join(__dirname, '/public/img/avatars/avatar1.png'),
width: pageSize.width,
opacity: 0.1
};
},
header: function (currentPage, pageCount, pageSize) {
return [
{
width: 100,
margin: [20, 10, 0, 0],
image: path.join(__dirname, '/public/img/avatars/logo.png'),
fit: [100, 100]
}
];
},
footer: function (currentPage, pageCount) {
return [
{
columns: [
{
margin: [0, 0, 0, 7],
width: 50,
alignment: 'center',
image: path.join(__dirname, '/public/img/avatars/avatar.png'),
fit: [30, 30]
},
[
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 8,
margin: [0, 3, 0, 0],
columns: [
{
text: 'GRUPO ELITE FINCA RAÍZ S.A.S.',
alignment: 'center'
},
{
text: 'info@grupoelitefincaraiz.co',
alignment: 'center'
},
{
text: 'https://grupoelitefincaraiz.com',
link: 'https://grupoelitefincaraiz.com',
alignment: 'center'
}
]
},
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 8,
margin: [0, 0, 0, 7],
columns: [
{ text: 'Nit: 901311748-3', alignment: 'center' },
{
text: '57 300-285-1046',
link: 'https://wa.me/573007861987?text=Hola',
alignment: 'center'
},
{
text: 'Mz L lt 17 Urb. la granja, Turbaco',
alignment: 'center'
}
]
}
],
{
margin: [0, 0, 0, 7],
alignment: 'center',
width: 50,
qr: 'https://grupoelitefincaraiz.com',
fit: '40',
foreground: 'yellow',
background: 'black'
}
]
}
];
},
pageSize: {
width: 595.28,
height: 297.53
},
info: {
title: 'Recibo de caja',
author: 'RedElite',
subject: 'Detallado del pago abonado a un producto',
keywords: 'recibo de caja',
creator: 'Grupo Elite',
producer: 'G.E.'
},
content: [
{
text: 'RECIBO DE CAJA ' + e.ids,
style: 'header',
alignment: 'right'
},
{ text: moment(e.fech).format('lll'), style: 'small' },
{
columns: [
[
{ text: e.nombre, style: 'subheader' },
{
alignment: 'justify',
italics: true,
color: 'gray',
fontSize: 9,
margin: [0, 0, 0, 5],
columns: [
{ text: `Doc. ${e.documento}` },
{ text: `Movil ${e.movil}` },
{ text: e.email }
]
},
{
alignment: 'justify',
italics: true,
columns: [
{ width: 250, text: e.proyect },
{ text: `MZ: ${e.mz ? e.mz : 'No aplica'}` },
{ text: `LT: ${e.n}` }
]
}
]
]
},
{
style: 'tableBody',
color: '#444',
fontSize: 9,
table: {
widths: ['*', 'auto', 'auto', '*'],
body: [
[
{ text: `TIPO`, style: 'tableHeader', alignment: 'center' },
{
text: `FORMA PAGO`,
style: 'tableHeader',
alignment: 'center'
},
{
text: `CONCEPTO`,
style: 'tableHeader',
alignment: 'center'
},
{ text: `CUOTA`, style: 'tableHeader', alignment: 'center' }
],
[
e.concepto,
e.formap,
e.descp,
{ text: e.ncuota ? e.ncuota : 'AL DIA', alignment: 'center' }
],
[
{ text: `SLD. FECHA`, style: 'tableHeader' },
{
text: NumeroALetras(e.total - saldo),
colSpan: 2,
italics: true,
bold: true
},
{},
{
text: `$${Moneda(e.total - saldo)}`,
italics: true,
bold: true
}
],
[
{ text: `MONTO`, style: 'tableHeader' },
{
text: NumeroALetras(e.monto),
colSpan: 2,
italics: true,
bold: true
},
{},
{ text: `$${Moneda(e.monto)}`, italics: true, bold: true }
],
[
{ text: `TOTAL SLD.`, style: 'tableHeader' },
{
text: NumeroALetras(e.total - saldo - e.monto),
colSpan: 2,
italics: true,
bold: true
},
{},
{
text: `$${Moneda(e.total - saldo - e.monto)}`,
italics: true,
bold: true
}
]
]
}
}
],
styles: {
header: {
fontSize: 16,
bold: true,
margin: [0, 0, 0, 1]
},
subheader: {
fontSize: 14,
bold: true,
margin: [0, 5, 0, 2]
},
tableBody: {
margin: [0, 5, 0, 5]
},
tableHeader: {
bold: true,
fontSize: 10,
color: 'black'
},
small: {
fontSize: 9,
italics: true,
color: 'gray',
alignment: 'right'
}
}
};
let ruta = path.join(__dirname, `/public/uploads/recibocaja-${e.ids}.pdf`);
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream(ruta));
pdfDoc.end();
archivos.push({ fileName: `Recibo de caja-${e.ids}.pdf`, ruta });
var dataFile = {
phone: author,
body: `https://grupoelitefincaraiz.co/uploads/recibocaja-${e.ids}.pdf`,
filename: `RECIBO DE CAJA ${e.ids}.pdf`
};
let r = await apiChatApi('sendFile', dataFile);
r.msg = e.cparacion;
}
await EnviarEmail(
recibos[0].email,
`Recibo de caja ${recibos[0].n}`,
recibos[0].nombre,
false,
'Grupo Elite te da la bienvenida',
archivos
);
return true;
} else {
return false;
}
}
async function apiChatApi(method, params) {
const apiUrl = 'https://eu89.chat-api.com/instance107218';
const token = '5jn3c5dxvcj27fm0';
const options = {
method: 'POST',
url: `${apiUrl}/${method}?token=${token}`,
data: JSON.stringify(params),
headers: { 'Content-Type': 'application/json' }
};
const apiResponse = await axios(options);
//console.log(apiResponse.data)
return apiResponse.data;
}
async function consultCompany(nit, method = 1) {
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0cmFkZSI6IlNhbXlyIiwid2ViaG9vayI6Imh0dHBzOi8vYzE4YS0yODAwLTQ4NC1hYzgyLTFhMGMtMjk5Ni1iZGUyLTI4NWUtMzgyYS5uZ3Jvay5pby93dHNwL3dlYmhvb2siLCJpYXQiOjE2NDg4MjYxNTR9.o-aWCOLCowGoJdqnUQnKpNrtJFWYrNqZ8LpPycQH7U0';
var data = JSON.stringify({ nit, method });
var config = {
method: 'post',
url: 'https://querys.inmovili.com/api/query/company',
headers: {
'x-access-token':
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0cmFkZSI6IlNhbXlyIiwid2ViaG9vayI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDAwMC93ZWJob29rIiwiaWF0IjoxNjQ4NjE3ODY5fQ.m_0kgatFJ3im8Z0SJhj5KrVWeyoTOiEoEPQ4W8n5lks',
'Content-Type': 'application/json'
},
data: data
};
try {
const apiResponse = await axios(config);
return apiResponse.data;
} catch (e) {
console.log(e);
return false;
}
}
async function consultDocument(docNumber, docType = 'CC') {
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0cmFkZSI6IlNhbXlyIiwid2ViaG9vayI6Imh0dHBzOi8vYzE4YS0yODAwLTQ4NC1hYzgyLTFhMGMtMjk5Ni1iZGUyLTI4NWUtMzgyYS5uZ3Jvay5pby93dHNwL3dlYmhvb2siLCJpYXQiOjE2NDg4MjYxNTR9.o-aWCOLCowGoJdqnUQnKpNrtJFWYrNqZ8LpPycQH7U0';
var data = JSON.stringify({ docNumber, docType });
var config = {
method: 'post',
url: 'https://querys.inmovili.com/api/query/person',
headers: {
'x-access-token':
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0cmFkZSI6IlNhbXlyIiwid2ViaG9vayI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDAwMC93ZWJob29rIiwiaWF0IjoxNjQ4NjE3ODY5fQ.m_0kgatFJ3im8Z0SJhj5KrVWeyoTOiEoEPQ4W8n5lks',
'Content-Type': 'application/json'
},
data: data
};
try {
const apiResponse = await axios(config);
return apiResponse.data;
} catch (e) {
console.log(e);
return false;
}
}
module.exports = {
NumeroALetras,
EstadoCuenta,
apiChatApi,
QuienEs,
EnviarEmail,
RecibosCaja,
EstadoDeCuenta,
FacturaDeCobro,
informes,
Facturar,
consultCompany,
consultDocument,
Lista
};
|
var waifus = [{
name: "Rias",
image: "https://lh3.googleusercontent.com/-GxK9YeFYha8/VX-SwHH3grI/AAAAAAAAC2w/HgS1JP8-qyE/w1920-h1080/Rias-Gremory-04.png",
scores: [5,3,4,5,5,2,3,5,1,1]
}, {
name: "Yoko",
image: "http://fastfrag.ru/uploads/imgs/pre_1440404720__ajzzjsly7ww.jpg",
scores: [5,1,2,1,1,2,5,5,4,1]
}, {
name: "Rem",
image: "http://i.imgur.com/sGwXxVx.jpg",
scores: [3,3,,1,3,5,1,2,2,2,1]
}, {
name: "Camillia",
image: "http://cdn.idigitaltimes.com/sites/idigitaltimes.com/files/styles/embed/public/2016/02/24/fire-emblem-fates-camilla-character.jpg",
scores: [3,5,5,4,4,1,2,5,1,]
}, {
name: "Master Raven",
image: "https://pbs.twimg.com/media/Cnr7dS0UMAQ3cp9.jpg",
scores: [2,1,2,3,2,1,1,4,2,3]
}, {
name: "Ako",
image: "http://scontent.cdninstagram.com/t51.2885-15/e35/13725704_937661959676598_1921365451_n.jpg?ig_cache_key=MTMwNzg0NjQ4ODMzNjczOTg5Ng%3D%3D.2",
scores: [1,3,3,1,2,5,4,4,1,5]
}];
module.exports = waifus;
|
const backEndLogos = [
{
img: './public/assets/images/icons/npm-1.png',
name: 'Node Package Manager'
},
{
img: './public/assets/images/icons/nodejs-1.svg',
name: 'NodeJS'
},
{
img: './public/assets/images/icons/expressJS.png',
name: 'ExpressJS'
},
{
img: './public/assets/images/icons/mongodb.svg',
name: 'MongoDB'
},
{
img: './public/assets/images/icons/mysql-5.svg',
name: 'MySQL'
},
{
img: './public/assets/images/icons/passport.png',
name: 'PassportJS'
},
{
img: './public/assets/images/icons/firebase_logo.png',
name: 'Google Firebase'
},
];
|
$(document).ready(function(){
// Объект с проектами. для которых нужно будет делать элементы
var projects = {
'employers': {
"name": "employers",
"verb": "Работодатели"
},
"applicants": {
"name": "applicants",
"verb": "Соискатели"
},
"students": {
"name": "students",
"verb": "Студенты"
}
};
// Путь до файла со структурой элементов
var elementsGroupingPath = 'json/' + 'elements_grouping.json';
// Достаем файл с описанием структуры элементов
var elementsGrouping = $.get(elementsGroupingPath, function(data){
render(JSON.parse(JSON.minify(data)));
});
/* Разборка и рендер элементов */
function render(data){
var elementsGroups = data;
var elementsGroupsNavTabsWrapper = $('#ElementsGroups_tabs_nav');
var elementsGroupsTabsWrapper = $('#ElementsGroups_tabs');
var elementsGroupsTabItemHTML;
// Прроходимся по группам элементов
for(var key in elementsGroups){
if(elementsGroups.hasOwnProperty(key)){
if(elementsGroups[key] != ''){
var elementsType = elementsGroups[key];
var elements = elementsType.elements;
// Если группа элементов не пустая
if(elements != ''){
var elementsSet = $('');
// Проходимся по всем элементам в группе
for(var keyEl in elements){
if(elements.hasOwnProperty(keyEl)){
// Если элемент не пустой - рендерим
if(elements[keyEl] != ''){
var element = elements[keyEl];
elementsSet = elementsSet.add(renderElement(element,elementsGroups[key].id));
//renderProjectExamples(element);
}
// Если элемент пустой - говорим, что элемент еще не описан сам по себе
else{
}
}
}
elementsGroupsTabItemHTML = elementsSet;
}
// Если группа элементов пустая - говорим, что нет в группе ничего
else{
elementsGroupsTabItemHTML = elementsGroups[key].verb + '<br><p>Нет ничего</p>';
}
tabsGenerator(
elementsGroups[key].id,
elementsGroups[key].verb,
elementsGroups[key].verb,
elementsGroupsTabItemHTML,
elementsGroupsNavTabsWrapper,
elementsGroupsTabsWrapper,
'gr_row'
);
}
}
}
}
function tabsGenerator(id, title, text, tabContent, tabsNavWrapper, tabsWrapper, addTabItemClass){
var elementsGroupsNavTabItem = $('<li><a></a></li>');
var elementsGroupsTabItem = $('<div></div>');
elementsGroupsNavTabItem.children('a')
.attr('href','#' + id + '_tab')
.attr('title',title)
.text(text)
elementsGroupsNavTabItem
.appendTo(tabsNavWrapper);
elementsGroupsTabItem
.attr('id', id + '_tab')
.addClass('t_item ' + addTabItemClass)
.append(tabContent)
.appendTo(tabsWrapper);
tabsNavWrapper.children('li:first-child').addClass('m_active');
tabsWrapper.children('.t_item:first-child').addClass('m_active');
};
function renderElement(element,groupId){
var elementTpl = $('<div class="el_block"><h1 class="el_block_header"></h1><p class="el_block_desc"></p></div>');
elementTpl.attr('id',groupId + '_' + element.name).addClass('el_block_level_' + element.level);
elementTpl.find('.el_block_header').text(element.verb);
elementTpl.find('.el_block_desc').text(element.desc);
elementTpl.append(renderProjectsExample(groupId, element));
return elementTpl;
};
function renderProjectsExample(groupId, element){
var elBlockExample = $('<div class="el_block_example"><div class="el_block_example_header"><nav class="el_block_example_menu js_t_nav"></div><div class="el_block_example_tabs_wrapper t_wrapper"></div>');
elBlockExample.find('.el_block_example_menu').attr('data-tab-wrapper', groupId + '_' + element.name);
elBlockExample.find('.el_block_example_tabs_wrapper').attr('id', groupId + '_' + element.name);
for(var key in projects){
if(projects.hasOwnProperty(key)){
// Если проект не пустой - рендерим
if(projects[key] != ''){
var infos = new renderExampleInfo(projects[key].name, element);
console.log(infos.exampleBlock);
tabsGenerator(
projects[key].name + '_' + groupId + '_' + element.name,
projects[key].verb,
projects[key].verb,
infos.exampleBlock,
elBlockExample.find('.el_block_example_menu'),
elBlockExample.find('.el_block_example_tabs_wrapper'),
''
);
}
}
}
return elBlockExample;
};
function renderExampleInfo(project, element){
this.project = project;
this.element = element;
this.srcPath = 'elements/' + project + '/blocks/' + element.element + '/sources/';
this.exampleBlock = $('');
this.info = {
"desc": {
"path": this.srcPath + element.name + '_desc.html',
"tpl": $('<div class="el_block_example_desc">'),
"content": "",
"name": "description",
"verb": "Описание"
},
"tpl": {
"path": this.srcPath + element.name + '.html',
"tpl": $('<div class="el_block_example_body">'),
"content": "",
"name": "template",
"verb": "Шаблон"
},
"code": {
"path": this.srcPath + element.name + '_code.html',
"tpl": $('<div class="el_block_example_code">'),
"content": "",
"name": "code",
"verb": "Код"
},
"note": {
"path": this.srcPath + element.name + '_note.html',
"tpl": $('<div class="el_block_example_note">'),
"content": "",
"name": "note",
"verb": "Заметка"
}
};
this.paths = {
"tpl": this.srcPath + element.name + '.html',
"desc": this.srcPath + element.name + '_desc.html',
"note": this.srcPath + element.name + '_note.html',
"code": this.srcPath + element.name + '_code.html',
};
this.setInfos = function(){
for(var key in this.info){
var self = this;
$.ajax({
url: self.info[key].path,
success: function(data) {
self.info[key].content = data;
},
error: function(data){
self.info[key].content = '';
},
async: false
});
if(this.info[key].content != ''){
this.exampleBlock = this.exampleBlock.add(this.info[key].tpl.html(this.info[key].content)) ;
}
}
};
this.init = function(){
this.setInfos();
this.renderInfos
}
this.init();
/*
elSrcPath = 'elements/' + project + '/blocks/' + element.element + '/sources/';
elTplPath = elSrcPath + element.name + '.html';
var elTpl
elTpl = $.get(elTplPath, function(data){})
.done(function(data){
console.log('Шаблон для: ' + project + ' / ' + element.verb);
console.log(data);
})
.fail(function(){
console.log('Шаблон для: ' + project + ' / ' + element.verb + ' ОТСУТСТВУЕТ');
})
*/
};
Singletone = (function () {
var instance;
return function Construct_singletone () {
if (instance) {
return instance;
}
if (this && this.constructor === Construct_singletone) {
instance = this;
} else {
return new Construct_singletone();
}
}
}());
});
|
npm install -g @aws-amplify/cli
amplify configure
|
import {get, post} from "jquery";
let API = {
saveBookmark(newBookmark) {
return post("/graphql", {
query: `
mutation {
createLink(title: "${newBookmark.title}", url: "${newBookmark.url}") {
id
title
url
safe
}
}
`
})
},
getAllBookmarks() {
return post("/graphql", {
query: `
{
bookmarks: allLinks {
id: _id
title
url
}
}
`
})
}
};
export default API;
|
const range = 20;
const lib = require("blib");
const IN = extendContent(ExtendingItemBridge, "i-node", {
drawPlace(x, y, rotation, valid){
Drawf.dashCircle(x * Vars.tilesize, y * Vars.tilesize, (range + 1) * Vars.tilesize, Pal.accent);
},
linkValid(tile, other, checkDouble){
if(other == null || tile == null || other == tile) return false;
if(Math.pow(other.x - tile.x, 2) + Math.pow(other.y - tile.y, 2) > Math.pow(range + 0.5, 2)) return false;
return ((other.block() == tile.block() && tile.block() == this) || (!(tile.block() instanceof ItemBridge) && other.block() == this))
&& (other.team == tile.team || tile.block() != this)
&& (!checkDouble || other.build.link != tile.pos());
},
});
lib.setBuildingSimple(IN, ExtendingItemBridge.ExtendingItemBridgeBuild, {
drawConfigure() {
const sin = Mathf.absin(Time.time, 6, 1);
Draw.color(Pal.accent);
Lines.stroke(1);
Drawf.circles(this.x, this.y, (this.block.size / 2 + 1) * Vars.tilesize + sin - 2, Pal.accent);
const other = Vars.world.build(this.link);
if(other != null){
Drawf.circles(other.x, other.y, (this.block.size / 3 + 1) * Vars.tilesize + sin - 2, Pal.place);
Drawf.arrow(this.x, this.y, other.x, other.y, this.block.size * Vars.tilesize + sin, 4 + sin, Pal.accent);
}
Drawf.dashCircle(this.x, this.y, range * Vars.tilesize, Pal.accent);
},
draw(){
//this.super$draw();
Draw.rect(Core.atlas.find("btm-i-node"),this.x,this.y);
Draw.z(Layer.power);
var bridgeRegion = Core.atlas.find("btm-in-b");
var endRegion = Core.atlas.find("btm-in-e");
var other = Vars.world.build(this.link);
if(other == null) return;
var op = Core.settings.getInt("bridgeopacity") / 100;
if(Mathf.zero(op)) return;
Draw.color(Color.white);
Draw.alpha(Math.max(this.power.status, 0.25) * op);
Draw.rect(endRegion, this.x, this.y);
Draw.rect(endRegion, other.x, other.y);
Lines.stroke(8);
Tmp.v1.set(this.x, this.y).sub(other.x, other.y).setLength(Vars.tilesize/2).scl(-1);
Lines.line(bridgeRegion,
this.x,
this.y,
other.x,
other.y, false);
Draw.reset();
},
});
IN.hasPower = true;
IN.consumes.power(1.5);
IN.size = 1;
IN.requirements = ItemStack.with(
Items.copper, 150,
Items.lead, 80,
Items.silicon, 110,
Items.graphite, 85,
Items.titanium, 45,
Items.thorium, 40,
Items.phaseFabric, 25
);
IN.buildVisibility = BuildVisibility.shown;
IN.category = Category.distribution;
exports.IN = IN;
|
/* eslint-disable camelcase */
const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
const PRIVATE_KEY = fs.readFileSync(
path.join(__dirname, '/key/private.pem'),
'utf8'
);
const PUBLIC_KEY = fs.readFileSync(
path.join(__dirname, '/key/public.pem'),
'utf8'
);
const ISSUER = 'sample_issuer';
const LIFE_SPAN = 1800;
exports.generateAccessToken = function() {
const payload = {
iss: ISSUER,
exp: Date.now() + LIFE_SPAN
};
const access_token = jwt.sign(payload, PRIVATE_KEY, { algorithm: 'RS256' });
return access_token;
};
exports.verifyToken = function(token) {
try {
jwt.verify(token, PUBLIC_KEY, { issuer: ISSUER, algorithms: ['RS256'] });
} catch (error) {
return false;
}
return true;
};
|
import {setError} from "./actions/actions";
const getGoogleUser = () => window.auth2['currentUser'].get();
export const get = () => {};
export const post = ( props ) => {
const googleUser = getGoogleUser();
const data = {
googleIdToken : googleUser.getAuthResponse()['id_token'],
...props
};
// f= just to see the name in Network panel during debug
return fetch('https://klesun-productions.com:8086/?f=' + data.func, {
method : "POST",
headers : {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body : JSON.stringify( data ),
})
.then( resp => {
if (resp)
{
return resp.json();
}
throw Error("Something bad is happening with server.");
} )
.then( resp => {
if (resp.error || !resp.hasOwnProperty('message'))
{
if (props.hasOwnProperty('componentDispatch'))
{
const error = {
isError: true,
errorMsg: resp.error || "Something went wrong :/"
};
props.componentDispatch(setError(error));
return Promise.reject(resp.error);
}
}
return resp;
} )
.catch(e => {
console.error(e);
});
};
|
const horizontalStepperIndexCopy =
{
"en": {
"INDEX": {
"TYPOGRAPHY": {
"TEXT": [
"All steps completed - you're finished",
"Back",
"Close",
"Back",
"Next",
"Next"
]
},
"BUTTON": {
"TEXT": [
"Reset"
]
}
}
},
"kr": {
"INDEX": {
"TYPOGRAPHY": {
"TEXT": [
"모든 단계 완료",
"이전",
"종료",
"이전",
"다음",
"다음"
]
},
"BUTTON": {
"TEXT": [
"초기화"
]
}
}
},
"ch": {
"INDEX": {
"TYPOGRAPHY": {
"TEXT": [
"所有步骤完成",
"上一个",
"关闭 结束?",
"上一个",
"下一个",
"下一个"
]
},
"BUTTON": {
"TEXT": [
"重启"
]
}
}
},
"jp": {
"INDEX": {
"TYPOGRAPHY": {
"TEXT": [
"All steps completed - you're finished",
"Back",
"Close",
"Back",
"Next",
"Next"
]
},
"BUTTON": {
"TEXT": [
"Reset"
]
}
}
},
"ru": {
"INDEX": {
"TYPOGRAPHY": {
"TEXT": [
"Все шаги выполнены - you're завершён",
"Назад",
"Закрыть",
"Назад",
"Следующий",
"Следующий"
]
},
"BUTTON": {
"TEXT": [
"Сброс"
]
}
}
}
}
export default horizontalStepperIndexCopy;
|
// nav下拉tab栏切换
//banner左侧内容栏
$(function () {
var thisTime;
//鼠标离开左侧内容栏
$('.cat_wrap .cat_list .float').mouseleave(function (even) {
thisTime = setTimeout(thisMouseOut, 1000);
});
//鼠标点击左侧内容栏 滑动出弹层
$('.cat_wrap .cat_list .float').mouseenter(function () {
$(this).addClass("active").siblings().removeClass("active");
clearTimeout(thisTime);
var thisUB = $('.cat_wrap .cat_list .float').index($(this));
if ($.trim($('.cat_subcont .cat_sublist').eq(thisUB).html()) != "") {
$('.cat_subcont').addClass('active');
$('.cat_sublist').hide();
$('.cat_sublist').eq(thisUB).show();
} else {
$('.cat_subcont').removeClass('active');
}
});
//函数——执行鼠标离开左侧内容栏的动作
function thisMouseOut() {
$('.cat_subcont').removeClass('active');
$('.cat_wrap .cat_list .float').removeClass('active');
}
$('.cat_subcont').mouseenter(function () {
clearTimeout(thisTime);
$('.cat_subcont').addClass('active');
});
$('.cat_subcont').mouseleave(function () {
$('.cat_subcont').removeClass('active');
$('.cat_wrap .cat_list .float').removeClass('active');
});
});
//轮播图 普通
var swiper = (function () {
let $imageBox,
$imageBoxItem,
$imageWidth,
$el,
showImageIndex = 0;
return {
init($ele) {
$el = $($ele);
$imageBox = $('.cont_ul');
$imageBoxItem = $imageBox.children('li');
const $first = $imageBoxItem.first();
const $last = $imageBoxItem.last();
$imageBox.append($first.clone());
$imageBox.prepend($last.clone());
$imageWidth = parseInt($el.css('width'));
$imageBox.css('left', -$imageWidth);
this.showImage(showImageIndex);
this.event();
},
event() {
let _this = this;
$('.cont_a_left').on('click', function () {
showImageIndex--;
_this.showImage(showImageIndex);
})
$('.cont_a_right').on('click', function () {
showImageIndex++;
_this.showImage(showImageIndex);
})
},
showImage(index) {
var maxIndex = $imageBoxItem.length - 1
if (index < 0) {
index = maxIndex;
$imageBox.css('left', -$imageWidth * (index + 2))
} else if (index > maxIndex) {
index = 0;
$imageBox.css('left', 0);
}
showImageIndex = index;
$imageBox.stop().animate({
left: -(index + 1) * $imageWidth
})
}
}
}())
//轮播图 无限 小原点
var swiper_show = (function () {
let $imageBox,
$imageBoxItem,
$imageWidth,
$tipsBox,
$tipsItem,
$el,
showImageIndex = 0;
return {
init($ele) {
$el = $($ele);
$imageBox = $('.right_show');
$imageBoxItem = $imageBox.children('li');
$tipsBox = $('.right_list');
$tipsItem = $tipsBox.children('li');
const $first = $imageBoxItem.first();
const $last = $imageBoxItem.last();
$imageBox.append($first.clone());
$imageBox.prepend($last.clone());
$imageWidth = parseInt($el.css('width'));
$imageBox.css('left', -$imageWidth);
this.showImage(showImageIndex);
this.event();
},
event() {
var _this = this;
$tipsBox.on('click', 'li', function () {
var index = $(this).index();
_this.showImage(index);
})
$('.right_left').on('click', function () {
showImageIndex--;
_this.showImage(showImageIndex);
})
$('.right_right').on('click', function () {
showImageIndex++;
_this.showImage(showImageIndex);
})
},
showImage(index) {
var maxIndex = $imageBoxItem.length - 1;
if (index < 0) {
index = maxIndex;
$imageBox.css('left', -$imageWidth * (index + 2))
} else if (index > maxIndex) {
index = 0;
$imageBox.css('left', 0);
}
showImageIndex = index;
$tipsItem.removeClass('lihover').eq(index).addClass('lihover');
$imageBox.stop().animate({
left: -(index + 1) * $imageWidth
})
}
}
}())
//轮播图 小圆点 自动轮播
var four = (function () {
let $imageBox,
$imageBoxItem,
$imageWidth,
$tipsBox,
$tipsItem,
$el,
showImageIndex = 0,
timer = null;
return {
init($ele) {
$el = $($ele);
$imageBox = $('.four_ul');
$imageBoxItem = $imageBox.children('li');
$tipsBox = $('.main_four_tip');
$tipsItem = $tipsBox.children('li');
const $first = $imageBoxItem.first();
const $last = $imageBoxItem.last();
$imageBox.append($first.clone());
$imageBox.prepend($last.clone());
$imageWidth = parseInt($el.css('width'));
$imageBox.css('left', -$imageWidth);
this.showImage(showImageIndex);
this.autoPlay();
this.event();
},
event() {
var _this = this;
$tipsBox.on('click', 'li', function () {
var index = $(this).index();
_this.showImage(index);
_this.autoPlay()
})
$('.four_show_left').on('click', function () {
showImageIndex--;
_this.showImage(showImageIndex);
_this.autoPlay()
})
$('.four_show_right').on('click', function () {
showImageIndex++;
_this.showImage(showImageIndex);
_this.autoPlay()
})
},
showImage(index) {
var maxIndex = $imageBoxItem.length - 1
if (index < 0) {
index = maxIndex;
$imageBox.css('left', -$imageWidth * (index + 2))
} else if (index > maxIndex) {
index = 0;
$imageBox.css('left', 0);
}
showImageIndex = index;
$tipsItem.children('i').removeClass('ion').eq(index).addClass('ion');
$tipsItem.removeClass('lion').eq(index).addClass('lion');
$imageBox.stop().animate({
left: -(index + 1) * $imageWidth
})
},
autoPlay() {
clearInterval(timer);
timer = setInterval(_ => {
showImageIndex++;
this.showImage(showImageIndex);
}, 3000)
}
}
}())
var five = (function () {
let $imageBox,
$imageBoxItem,
$imageWidth,
$tipsBox,
$tipsItem,
$el,
showImageIndex = 0,
timer = null;
return {
init($ele) {
$el = $($ele);
$imageBox = $('.five_ul');
$imageBoxItem = $imageBox.children('li');
$tipsBox = $('.five_tip');
$tipsItem = $tipsBox.children('li');
const $first = $imageBoxItem.first();
const $last = $imageBoxItem.last();
$imageBox.append($first.clone());
$imageBox.prepend($last.clone());
$imageWidth = parseInt($el.css('width'));
$imageBox.css('left', -$imageWidth);
this.showImage(showImageIndex);
this.autoPlay();
this.event();
},
event() {
var _this = this;
$tipsBox.on('click', 'li', function () {
var index = $(this).index();
_this.showImage(index);
_this.autoPlay()
})
$('.five_show_left').on('click', function () {
showImageIndex--;
_this.showImage(showImageIndex);
_this.autoPlay()
})
$('.five_show_right').on('click', function () {
showImageIndex++;
_this.showImage(showImageIndex);
_this.autoPlay()
})
},
showImage(index) {
var maxIndex = $imageBoxItem.length - 1
if (index < 0) {
index = maxIndex;
$imageBox.css('left', -$imageWidth * (index + 2))
} else if (index > maxIndex) {
index = 0;
$imageBox.css('left', 0);
}
showImageIndex = index;
$tipsItem.children('i').removeClass('ion').eq(index).addClass('ion');
$tipsItem.removeClass('lion').eq(index).addClass('lion');
$imageBox.stop().animate({
left: -(index + 1) * $imageWidth
})
},
autoPlay() {
clearInterval(timer);
timer = setInterval(_ => {
showImageIndex++;
this.showImage(showImageIndex);
}, 3000)
}
}
}())
var nine = (function () {
let $imageBox,
$imageBoxItem,
$imageWidth,
$tipsBox,
$tipsItem,
$el,
showImageIndex = 0,
timer = null;
return {
init($ele) {
$el = $($ele);
$imageBox = $('.nine_show_ul');
$imageBoxItem = $imageBox.children('li');
$tipsBox = $('.nine_list');
$tipsItem = $tipsBox.children('li');
const $first = $imageBoxItem.first();
const $last = $imageBoxItem.last();
$imageBox.append($first.clone());
$imageBox.prepend($last.clone());
$imageWidth = parseInt($el.css('width'));
$imageBox.css('left', -$imageWidth);
this.showImage(showImageIndex);
this.autoPlay();
this.event();
},
event() {
var _this = this;
$tipsBox.on('click', 'li', function () {
var index = $(this).index();
_this.showImage(index);
_this.autoPlay()
})
$('.nine_show_left').on('click', function () {
showImageIndex--;
_this.showImage(showImageIndex);
_this.autoPlay();
})
$('.nine_show_right').on('click', function () {
showImageIndex++;
_this.showImage(showImageIndex);
_this.autoPlay();
})
},
showImage(index) {
var maxIndex = $imageBoxItem.length - 1
if (index < 0) {
index = maxIndex;
$imageBox.css('left', -$imageWidth * (index + 2))
} else if (index > maxIndex) {
index = 0;
$imageBox.css('left', 0);
}
showImageIndex = index;
$tipsItem.removeClass('lihover').eq(index).addClass('lihover');
$imageBox.stop().animate({
left: -(index + 1) * $imageWidth
})
},
autoPlay() {
clearInterval(timer);
timer = setInterval(_ => {
showImageIndex++;
this.showImage(showImageIndex);
}, 3000)
}
}
}())
var three = (function () {
let $imageBox,
$imageBoxItem,
$imageWidth,
$tipsBox,
$tipsItem,
$el,
showImageIndex = 0,
timer = null;
return {
init($ele) {
$el = $($ele);
$imageBox = $('.three_ul');
$imageBoxItem = $imageBox.children('li');
$tipsBox = $('.tree_top_list');
$tipsItem = $tipsBox.children('li');
const $first = $imageBoxItem.first();
const $last = $imageBoxItem.last();
$imageBox.append($first.clone());
$imageBox.prepend($last.clone());
$imageWidth = parseInt($el.css('width'));
$imageBox.css('left', -$imageWidth);
this.showImage(showImageIndex);
this.autoPlay();
this.event();
},
event() {
var _this = this;
$tipsBox.on('click', 'li', function () {
var index = $(this).index();
_this.showImage(index);
_this.autoPlay()
})
$('.main_show_left').on('click', function () {
showImageIndex--;
_this.showImage(showImageIndex);
_this.autoPlay()
})
$('.main_show_right').on('click', function () {
showImageIndex++;
_this.showImage(showImageIndex);
_this.autoPlay()
})
},
showImage(index) {
var maxIndex = $imageBoxItem.length - 1
if (index < 0) {
index = maxIndex;
$imageBox.css('left', -$imageWidth * (index + 2))
} else if (index > maxIndex) {
index = 0;
$imageBox.css('left', 0);
}
showImageIndex = index;
$tipsItem.children('i').removeClass('ion').eq(index).addClass('ion');
$tipsItem.removeClass('lion').eq(index).addClass('lion');
$imageBox.stop().animate({
left: -(index + 1) * $imageWidth
})
},
autoPlay() {
clearInterval(timer);
timer = setInterval(_ => {
showImageIndex++;
this.showImage(showImageIndex);
}, 3000)
}
}
}())
var bannerShow = (function () {
let $imageBox,
$imageBoxItem,
$imageWidth,
$tipsBox,
$tipsItem,
$el,
showImageIndex = 0,
timer = null;
return {
init($ele) {
$el = $($ele);
$imageBox = $('.banner-show');
$imageBoxItem = $imageBox.children('li');
$tipsBox = $('.banner_list');
this.createTips($imageBoxItem.length);
$tipsItem = $tipsBox.children('li');
const $first = $imageBoxItem.first();
const $last = $imageBoxItem.last();
$imageBox.append($first.clone());
$imageBox.prepend($last.clone());
$imageWidth = parseInt($el.css('width'));
$imageBox.css('left', -$imageWidth);
this.showImage(showImageIndex);
this.autoPlay();
this.event();
},
event() {
var _this = this;
$tipsBox.on('click', 'li', function () {
var index = $(this).index();
_this.showImage(index);
_this.autoPlay()
})
$('.a_left_show').on('click', function () {
showImageIndex--;
_this.showImage(showImageIndex);
_this.autoPlay()
})
$('.a_right_show').on('click', function () {
showImageIndex++;
_this.showImage(showImageIndex);
_this.autoPlay()
})
},
// 自动生成小圆点
createTips(num) {
for (var i = 0; i < num; i++) {
$tipsBox.append('<li><i></i></li>');
}
},
showImage(index) {
var maxIndex = $imageBoxItem.length - 1
if (index < 0) {
index = maxIndex;
$imageBox.css('left', -$imageWidth * (index + 2))
} else if (index > maxIndex) {
index = 0;
$imageBox.css('left', 0);
}
showImageIndex = index;
$tipsItem.children('i').removeClass('list_show').eq(index).addClass('list_show');
$imageBox.stop().animate({
left: -(index + 1) * $imageWidth
})
},
autoPlay() {
clearInterval(timer);
timer = setInterval(_ => {
showImageIndex++;
this.showImage(showImageIndex);
}, 2000)
}
}
}())
//图片放大阴影
var show_img = function () {
let $tow_bottom_left, $on_img, $on_i, $four_left, $six_show_left, $show_left;
return {
init($el) {
$tow_bottom_left = $('.tow_bottom_left'); // 第二个
$four_left = $('.four_left');
$six_show_left = $('.six_show_left');
$show_left = $('.show_left');
this.event($six_show_left, $four_left, $tow_bottom_left, $show_left);
},
event($el, $ea, $eb, $es) {
$es.hover(
function () {
$on_img = $es.children('.on_img');
$on_i = $es.children('.on_i');
$on_img.addClass('imgtransform');
$on_i.css('opacity', '0.9');
},
function () {
$on_img.removeClass('imgtransform');
$on_i.css('opacity', '0.6');
}
);
$el.hover(
function () {
$on_img = $el.children('.on_img');
$on_i = $el.children('.on_i');
$on_img.addClass('imgtransform');
$on_i.css('opacity', '0.9');
},
function () {
$on_img.removeClass('imgtransform');
$on_i.css('opacity', '0.6');
}
);
$ea.hover(
function () {
$on_img = $ea.children('.on_img');
$on_i = $ea.children('.on_i');
$on_img.addClass('imgtransform');
$on_i.css('opacity', '0.9');
},
function () {
$on_img.removeClass('imgtransform');
$on_i.css('opacity', '0.6');
}
);
$eb.hover(
function () {
$on_img = $eb.children('.on_img');
$on_i = $eb.children('.on_i');
$on_img.addClass('imgtransform');
$on_i.css('opacity', '0.9');
},
function () {
$on_img.removeClass('imgtransform');
$on_i.css('opacity', '0.6');
}
);
}
}
}()
//倒计时
var timer=(function(){
let $timerBox,$day,$when,$points,$sec,time=0;
return{
init($el){
time = $el;
$timerBox = $('.flash_span');
$day = $('.flash_day');
$when = $('.flash_when');
$points =$('.flash_points');
$sec = $('.flash_sec');
this.event();
},
event(){
let _this=this;
// 搜索框聚焦js
var $search_txt = $('.search_txt');
var $head_em = $('.head_em');
var $search_wrap = $('.search_wrap');
$search_txt.bind({
focus:function() {
$head_em.text('');
$search_wrap.css('display','block');
},
blur:function() {
$head_em.text('机械男表');
$search_wrap.css('display','none');
}
});
$(document).ready(function (){
setInterval(function(){
time--;
var day = Math.floor(time / (60 * 60 * 24));
var hour = Math.floor(time / (60 * 60)) - (day * 24);
var minute = Math.floor(time / 60) - (day * 24 * 60) - (hour * 60);
var second = Math.floor(time) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
var hour_=_this.zero(hour);
var minute_=_this.zero(minute);
var second_=_this.zero(second);
$day.text(day);
$when.text(hour_);
$points.text(minute_);
$sec.text(second_);
},1000)
});
},
zero(sum){
if(sum<10){
sum='0'+sum;
}
return sum;
}
}
}())
//页面滚动 显示nav
var sollHeader=(function(){
let $webscroll,$nav;
return{
init(){
$nav = $('.soll_box');
this.event();
this.topgg();
},
event(){
$(window).scroll(function(){
//nav
var top = $(window).scrollTop();// 保存当前 滚动高度
if(top >= 140){ // 大于140 nav 显示 改变定位
$nav.css({"display":"block","position":"fixed","top":"0"});
}else if(top <= 140){//小于 140 nav隐藏
$nav.css({"display":"none","position":"absolute","top":"140px"});
}
});
},
topgg(){
let $topgg=$('#top_gg');
let timer,navtop;
$topgg.on('click',function(){
navtop = $(window).scrollTop();
timer = setInterval(function(){
navtop -= 40;
$(window).scrollTop(navtop);
if(navtop <= 0){
clearInterval(timer);
}
},10)
})
}
}
}())
//调用
//轮播图
three.init('.main_show_box');
four.init('.four_show_box');
five.init('.five_show_box');
nine.init('.nine_show_box');
swiper_show.init('.right_show_box');
swiper.init('.tow_bottom_cont');
$(document).ready(function(){
bannerShow.init('.banner_box');
});
//图片放大和阴影
show_img.init();
//倒计时调用
timer.init(559974);
//页面滚动nav滚动
sollHeader.init();
|
/* eslint-disable */
const fs = require('fs');
const lines = fs.readFileSync('.git/COMMIT_EDITMSG').toString().split('\n');
try {
checkLineLength(lines, 100);
checkEmptyLine(lines);
checkHeader(lines[0]);
} catch (err) {
console.error(`\nInvalid commit message: ${err.message}.\n\nSee details in README.md.\n`);
process.exit(1);
}
function checkLineLength(lines, length) {
const error = lines
.map((line, i) => line.length > length ? numeral(i + 1) : '')
.filter(line => !!line)
.join(', ')
.replace(/,(?=[^,]*$)/, ' and');
const plural = error.indexOf(' and ' ) > -1;
if (error) {
throw new Error(`${error} line${plural ? 's' : ''} exceeds ${length} characters`);
}
}
function checkEmptyLine(lines) {
if (lines.length > 1 && !/^$/.test(lines[1])) {
throw new Error(`2nd line has to be empty`);
}
}
function checkHeader(header) {
const readme = fs.readFileSync('README.md', 'utf8');
const types = extractList(readme, 'Type');
const scopes = extractList(readme, 'Scope');
const regex = new RegExp(`^(?:${types.join('|')})(?:\\((?:${scopes.join('|')})\\))?: [a-z]`);
if (!regex.test(header)) {
throw new Error(`1st line doesn't follow "type(scope): subject" format`);
}
}
function numeral(i) {
switch (i) {
case 1:
return '1st';
case 2:
return '2nd';
case 3:
return '3rd';
default:
return `${i}th`
}
}
function extractList(readme, type) {
const start = readme.indexOf(`# ${type}`);
const chunk = readme.substring(readme.indexOf('*', start), readme.indexOf('#', start + 1));
return chunk.match(/\*\*.*\*\*/g).map(res => res.replace(/\*\*/g, ''));
}
|
var config = require('../../config.json');
var _ = require('lodash');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
var Q = require('q');
var mongo = require('mongoskin');
var db = mongo.db(config.connectionString, { native_parser: true });
db.bind('companies');
db.bind('users');
var service = {};
// service.verify = verify;
service.getAll = getAll;
// service.getById = getById;
service.create = create;
service.update = update;
service.delete = _delete;
module.exports = service;
function create(companyParam) {
var deferred = Q.defer();
// validation
db.users.findOne(
{ email: companyParam.email },
function (err, company) {
if (err) deferred.reject(err.email + ': ' + err.message);
if (company) {
// email already exists
deferred.reject('Email "' + companyParam.email + '" is already taken');
} else {
createuser();
}
});
function createuser(){
// set company object to companyParam without the cleartext password
var user = _.omit(companyParam, ['name','type','email','traderegnumber','ownername','ownersurname','ownerphone','ownedBy','ownerpass','timetable']);;
user.name = companyParam.ownername;
user.surname = companyParam.ownersurname;
user.active = true;
user.phone = companyParam.ownerphone;
// add hashed password to company object
user.hash = bcrypt.hashSync(companyParam.ownerpass, 10);
user.role = 'owner';
db.users.insert(
user,
function (err, user) {
if (err) deferred.reject(err.name + ': ' + err.message);
createcompany(user);
});
}
function createcompany(user) {
// set company object to companyParam without the cleartext password
var company = _.omit(companyParam, ['ownerpass','ownername','ownersurname','ownerphone']);
company.ownedBy = user.ops._id;
db.companies.insert(
company,
function (err, doc) {
if (err) deferred.reject(err.name + ': ' + err.message);
deferred.resolve();
});
}
return deferred.promise;
}
function getAll() {
var deferred = Q.defer();
db.companies.find().toArray(function (err, companies) {
if (err) deferred.reject(err.name + ': ' + err.message);
// return companies (without hashed passwords)
companies = _.map(companies, function (company) {
return _.omit(company, 'hash');
});
deferred.resolve(companies);
});
return deferred.promise;
}
// function getById(_id) {
// var deferred = Q.defer();
// db.companies.findById(_id, function (err, company) {
// if (err) deferred.reject(err.name + ': ' + err.message);
// if (company) {
// // return company (without hashed password)
// deferred.resolve(_.omit(company, 'hash'));
// } else {
// // company not found
// deferred.resolve();
// }
// });
// return deferred.promise;
// }
function update(_id, companyParam) {
var deferred = Q.defer();
// validation
db.companies.findById(_id, function (err, company) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (company.email !== companyParam.email) {
// mobile has changed so check if the new mobile is already taken
db.companies.findOne(
{ email: companyParam.email },
function (err, company) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (company) {
// mobile already exists
deferred.reject('Email "' + req.body.email + '" is already taken')
} else {
updatecompany();
}
});
} else {
updatecompany();
}
});
function updatecompany() {
// fields to update
var set = {
name:companyParam.name,
role: companyParam.role,
surname: companyParam.surname,
email: companyParam.email,
address: companyParam.address,
phone: companyParam.phone,
whatsapp: companyParam.whatsapp,
assignedColor: companyParam.assignedColor,
workingHour: companyParam.workingHour,
vacation: companyParam.vacation,
updated: companyParam.updated,
};
// update password if it was entered
if (companyParam.password) {
set.hash = bcrypt.hashSync(companyParam.password, 10);
}
db.companies.update(
{ _id: mongo.helper.toObjectID(_id) },
{ $set: set },
function (err, doc) {
if (err) deferred.reject(err.name + ': ' + err.message);
deferred.resolve();
});
}
return deferred.promise;
}
function _delete(_id) {
var deferred = Q.defer();
db.companies.remove(
{ _id: mongo.helper.toObjectID(_id) },
function (err) {
if (err) deferred.reject(err.name + ': ' + err.message);
deferred.resolve();
});
return deferred.promise;
}
|
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import { routes } from './routes'
import "bootstrap/dist/css/bootstrap.min.css"
import "bootstrap/dist/js/bootstrap.bundle"
import VueAlertify from 'vue-alertify'
export const eventBus = new Vue()
export const RouterLink = "http://127.0.0.1:8000/api"
Vue.use(VueAlertify)
Vue.use(VueRouter)
const router = new VueRouter({
routes, // short for `routes: routes
mode: "history"
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
|
import React from "react";
import PubSub from "pubsub-js";
import { browserHistory } from './react-router';
import { AppStore } from "./../../Store/Store";
import { connect } from "react-redux";
import {GetSearchResults} from "./../../api/companyAPI";
import "./Search.scss";
const Search = React.createClass({
getInitialState () {
return {
name: "",
country: ""
};
},
componentWillMount() {
this.state.name = localStorage.getItem("searchText");
this.state.country = localStorage.getItem("searchCountry");
this.submitForm();
},
componentWillUnmount: function() {
// PubSub.unsubscribe(this.pubsub_token);
},
submitForm: function() {
//const text = this.state.SearchInputState.text;
localStorage.setItem('searchText', this.state.name);
localStorage.setItem('searchCountry', this.state.country);
GetSearchResults(this.state);
browserHistory.transitionTo('/');
},
handleInput: function(e){
this.state.name = e.target.value;
//AppStore.dispatch(ActionSetSearchText(e.target.value));
},
handleCountry: function(e){
this.state.country = e.target.options[e.target.selectedIndex].value;
},
render: function() {
let name = this.state.name;
let country = this.state.country;
return (
<div className="wrapper">
<div className="search">
<div className="search__bar">
<input className="search__input" type="text" name="q" value={name} placeholder="Company name" onChange={this.handleInput}/>
<select className="search__select" name="countryCode" defaultValue={country} onChange={this.handleCountry}>
<option value="">Select a Country</option>
<option value="BE">Belgium</option>
<option value="FR">France</option>
<option value="IT">Italy</option>
<option value="IR">Ireland</option>
<option value="UK">Great Britain</option>
<option value="FI">Finland</option>
<option value="NO">Norway</option>
<option value="SE">Sweden</option>
<option value="CH">Switzerland</option>
</select>
<button className="search__button" onClick={this.submitForm}>Search</button>
</div>
</div>
</div>
);
}
});
const mapStateToProps = (state) => {
return {
SearchInputState: state.SearchInputState
};
};
export default connect(mapStateToProps)(Search);
|
/* Clase 4 - Manipulacion de Objetos */
var auto = {
nombre: 'Mustang',
motor: 5.5,
color: 'azul',
clasico: true,
anio: 1965,
};
// Cambio de un atributo dentro del objeto
auto.nombre = 'Camaro';
console.log(auto);
console.log(auto.nombre);
// Borrar un atributo de un objeto
delete auto.anio
console.log(auto);
// Objetos con metodos
var persona = {
nombre: 'Luis',
edad: 27,
color_ojos: 'cafe',
peso = 69,
// Creamos un metodo dentro del objeto
mensajeNombreOjos: function(){
console.log(`Mi nombre es ${this.nombre} y tengo un color de ojos ${this.color_ojos}`)
}
}
persona.mensajeNombreOjos()
|
/**
* Created by mac on 12/6/16.
*/
const user = require('./User');
const Friend = require('./Friend');
//adds friend object to friends array
function addFriend(user, name, publicKey) {
friend = new Friend(name, publicKey);
user.friends.push(friend);
}
module.exports = addFriend;
|
import React from 'react';
import { Link } from 'react-router-dom';
import { makeStyles } from "@material-ui/core/styles";
import { Typography } from '@material-ui/core';
import Avatar from '@material-ui/core/Avatar';
import avatar from '../../assets/avatar.svg';
import trophy1 from '../../assets/trophy1.svg';
import trophy2 from '../../assets/trophy2.svg';
import trophy3 from '../../assets/trophy3.svg';
import trophy4 from '../../assets/trophy4.svg';
import trophy5 from '../../assets/trophy5.svg';
const useStyles = makeStyles(() => ({
root: {
margin: '2rem 2rem 1rem 2rem',
},
title: {
display: 'flex',
placeItems: 'center',
justifyContent: 'center',
borderRadius: '5px 5px 0px 0px',
width: '15.875rem',
height: '2.5rem',
backgroundColor: '#0088D7',
marginBottom: '0.4rem',
boxShadow: '4px 6px 6px rgba(0, 0, 0, 0.25)',
},
list: {
borderRadius: '0px 0px 5px 5px',
width: '15.875rem',
height: '19.75rem',
backgroundColor: '#FFFFFF',
boxShadow: '4px 6px 6px rgba(0, 0, 0, 0.25)',
},
listItem: {
display: 'grid',
gridTemplateColumns: '1fr 3fr 1fr',
padding: '1rem 1.5rem 0 1.5rem',
flexWrap: 'wrap',
justifyContent: 'center',
},
avatar: {
height: '1.9rem',
width: '1.9rem',
marginRight: '1rem',
},
line: {
width: '100%',
color: '#E5E5E5',
margin: '1rem 0 0 0',
gridColumnStart: '1',
gridColumnEnd: '5',
}
}));
function KarmaLeaderboard ({ title, users }) {
const classes = useStyles();
const trophies = [trophy1, trophy2, trophy3, trophy4, trophy5]
const listUsers = users.map((user, i) =>
<div className={classes.listItem}>
<Avatar className={classes.avatar} src={avatar} />
<div style={{marginRight: '1rem'}}>
<Typography variant="h3">{users[i]}</Typography>
<Typography variant="h4">10,598 Points</Typography>
</div>
<img src={trophies[i]} />
{i != users.length - 1 &&
<hr className={classes.line} />
}
</div>
);
return (
<div className={classes.root}>
<div className={classes.title}>
<Typography variant="h2">{title}</Typography>
</div>
<div className={classes.list}>
{listUsers}
</div>
</div>
)
}
export default KarmaLeaderboard;
|
var gulp = require('gulp');
var watch = require('gulp-watch');
var webpack = require('webpack');
var config = require('./webpack.config.js');
gulp.task('build', function (done) {
webpack(config).run(function (err, stats) {
if (err) {
console.log('GulpWebpackError', err);
} else {
console.log(stats.toString());
}
});
});
|
/* eslint-disable */
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
class SideBar extends Component {
state = {
leftMenu : [
{ id: 1 , text: "Quisioner", link:"/", icon: "book", liclass: "nav-tem"},
{ id: 2 , text: "Hasil", link:"/hasil", icon: "poll", liclass: "nav-tem"},
]
}
componentDidMount = () =>{
this.setState({ idNav: this.props.active })
}
render() {
return (
<div className="sidebar" data-color="purple" data-background-color="white" data-image="../assets/img/sidebar-1.jpg">
<div className="logo">
<a href="#" className="simple-text logo-normal">
<b>Fuzzy Apps</b>
</a>
</div>
<div className="sidebar-wrapper">
<ul className="nav">
{this.state.leftMenu.map(items=>(
<li key={items.id} className={items.liClass, this.state.idNav === items.id ? 'active' : ''} >
<Link className="nav-link" to={items.link}>
<i className="material-icons">{items.icon}</i>
<p>{items.text}</p>
</Link>
</li>
))}
</ul>
</div>
</div>
);
}
}
export default SideBar;
|
import React from 'react';
import {
createFragmentContainer,
graphql,
commitMutation
} from 'react-relay';
import environment from '../../Environment';
import {
ConnectionHandler
} from 'relay-runtime';
import {
Link
} from 'react-router-dom';
import {
Popover, Button, Menu, MenuItem, MenuDivider,
Position
} from "@blueprintjs/core";
const mutation = graphql`
mutation RestaurantDeleteMutation (
$input: DeleteRestaurantInput!
) {
deleteRestaurant(input: $input) {
deletedId
}
}
`;
class Restaurant extends React.Component {
handleDelete() {
const {id} = this.props.restaurant;
// const confirmed = window.confirm('Are you sure?');
// if(!confirmed) return;
const variables = {
input: {
id,
clientMutationId: "",
}
};
commitMutation(
environment,
{
mutation,
variables,
updater: (store) => {
const userProxy = store.get(this.props.viewer.id);
const payload = store.getRootField('deleteRestaurant');
var deletedId = payload.getValue('deletedId');
var conn = ConnectionHandler.getConnection(
userProxy,
'Restaurants_allRestaurants'
);
ConnectionHandler.deleteNode(
conn,
deletedId
);
}
}
)
}
render() {
const {restaurant} = this.props;
const dropdownMenu = (
<Menu>
<MenuItem
iconName="trash"
onClick={this.handleDelete.bind(this)}
text="Delete"
/>
</Menu>
)
return (
<tr>
<td><Link to={'restaurants/edit/' + restaurant.id}>{restaurant.name}</Link></td>
<td>{restaurant.cuisine ? restaurant.cuisine.name : 'N/A'}</td>
<td>
<Button iconName="trash" onClick={this.handleDelete.bind(this)} />
<Popover content={dropdownMenu} position={Position.BOTTOM}>
<Button iconName="more" />
</Popover>
</td>
</tr>
)
}
}
export default createFragmentContainer(Restaurant, graphql`
fragment Restaurant_restaurant on Restaurant {
id
name
cuisine {
name
}
}
`);
|
import React from 'react';
import {NavLink} from "react-router-dom";
export function Header() {
return(
<header>
<div id='today' > WeatherApp</div>
<nav>
<ul>
<li id='index'><NavLink exact activeClassName="active" to="/">Home</NavLink></li>
<li id='forecast'><NavLink exact activeClassName="active" to="/forecast">Forecast</NavLink></li>
<li id='list'><NavLink exact activeClassName="active" to="/list">Cities List</NavLink></li>
<li id='about'><NavLink exact activeClassName="active" to="/about">About</NavLink></li>
</ul>
</nav>
</header>
);
}
|
'use strict';
angular.module('frontApp')
.factory('ConfigAPI',
function (config, $http, $q) {
var create = function(data){
var deferred = $q.defer();
$http.post(config.baseURL + '/config', data)
.success(function(data, status){
deferred.resolve(data);
})
.error(function(error, status){
deferred.reject(error);
})
return deferred.promise;
}
var update = function(id, data){
var deferred = $q.defer();
$http.post(config.baseURL + '/config/' + id, data)
.success(function(data, status){
deferred.resolve(data);
})
.error(function(error, status){
deferred.reject(error);
})
return deferred.promise;
}
var list = function(){
var deferred = $q.defer();
$http.get(config.baseURL + '/config')
.success(function(data, status){
deferred.resolve(data);
})
.error(function(error, status){
deferred.reject(error);
})
return deferred.promise;
}
var read = function(id){
var deferred = $q.defer();
$http.get(config.baseURL + '/config/' + id)
.success(function(data, status){
deferred.resolve(data);
})
.error(function(error, status){
deferred.reject(error);
})
return deferred.promise;
}
var read_by_host_id = function(id){
var deferred = $q.defer();
$http.get(config.baseURL + '/config/' + id + '?host=1')
.success(function(data, status){
deferred.resolve(data, status);
})
.error(function(error, status){
deferred.reject(error, status);
})
return deferred.promise;
}
return {
create: create,
update: update,
list: list,
read: read,
read_by_host_id: read_by_host_id
}
});
|
let furnitureTableBody = document.querySelector('tbody');
Array.from(furnitureTableBody.children)
.forEach(c => c.remove());
document.getElementById('name-span')
.textContent = '';
document.getElementById('price-span')
.textContent = ``;
fetch('http://localhost:3030/data/furniture')
.then(res => res.json())
.then(res => res.forEach(f => furnitureTableBody.appendChild(createFurnitureHtml(f))));
let form = document.querySelector('.col-md-12 form');
let createbuttonElement = form.querySelector('button');
let buyButtonElement = document.querySelector('#buy');
let ordersButtonElement = document.querySelector('#orders');
let logoutButtonElement = document.querySelector('#logoutBtn');
createbuttonElement.addEventListener('click', createFurniture);
buyButtonElement.addEventListener('click', buyFurniture);
ordersButtonElement.addEventListener('click', getOrders);
logoutButtonElement.addEventListener('click', () => {
localStorage.clear();
location.assign('./home.html');
})
function createFurniture(e) {
e.preventDefault();
let formData = new FormData(form);
let imageLink = formData.get('img');
let name = formData.get('name');
let price = Number(formData.get('price'));
let factor = Number(formData.get('factor'));
if (!formData || !name
|| !price
|| !factor) {
console.error('Invalid data!');
return;
}
if (isNaN(price) || isNaN(factor)) {
console.error('Invalid data!');
return;
}
Array.from(document.querySelectorAll('.col-md-12 form input'))
.forEach(i => i.value = '');
fetch('http://localhost:3030/data/furniture', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Authorization': localStorage.getItem('auth_token')
},
body: JSON.stringify({
imageLink,
name,
price,
factor
})
})
.then(res => res.json())
.then(res => furnitureTableBody.appendChild(createFurnitureHtml(res)));
}
function buyFurniture() {
let markedFurniture = Array.from(document.querySelectorAll('input[type="checkbox"]:checked'))
.map(c => c.parentElement
.parentElement);
markedFurniture.forEach(f => {
let paragraphs = Array.from(f.querySelectorAll('td p'));
let name = paragraphs[0]
.textContent;
let price = Number(paragraphs[1]
.textContent);
fetch('http://localhost:3030/data/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Authorization': localStorage.getItem('auth_token')
},
body: JSON.stringify({
name,
price
})
})
.then(res => res.json())
.then(res => console.log(res));
})
}
function getOrders() {
let url = `http://localhost:3030/data/orders?where=_ownerId%3D"${localStorage.getItem('userId')}"`;
fetch(url)
.then(res => res.json())
.then(res => {
if (res.length == 0) {
document.getElementById('name-span')
.textContent = 'none';
document.getElementById('price-span')
.textContent = '0 $';
} else {
let names = [];
res.forEach(f => names.push(f.name));
let totalSum = res.reduce((acc, x) => acc += x.price, 0);
document.getElementById('name-span')
.textContent = names.join(', ');
document.getElementById('price-span')
.textContent = `${totalSum} $`;
}
})
.catch(err => console.error(err))
}
function createFurnitureHtml(f) {
let currentTr = document.createElement('tr');
let imageTh = document.createElement('td');
let imageElement = document.createElement('img');
imageElement.src = f.imageLink;
imageTh.appendChild(imageElement);
let nameTh = document.createElement('td');
let nameParagraph = document.createElement('p');
nameParagraph.textContent = f.name;
nameTh.appendChild(nameParagraph);
let priceTh = document.createElement('td');
let priceParagraph = document.createElement('p');
priceParagraph.textContent = f.price;
priceTh.appendChild(priceParagraph);
let decorationFactorTh = document.createElement('td');
let decorationParagraph = document.createElement('p');
decorationParagraph.textContent = f.factor;
decorationFactorTh.appendChild(decorationParagraph);
let checkboxTh = document.createElement('td');
let checkboxElement = document.createElement('input');
checkboxElement.type = 'checkbox';
checkboxTh.appendChild(checkboxElement);
currentTr.appendChild(imageTh);
currentTr.appendChild(nameTh);
currentTr.appendChild(priceTh);
currentTr.appendChild(decorationFactorTh);
currentTr.appendChild(checkboxTh);
return currentTr;
}
|
import React, { Component } from 'react';
import Spinner from '../../services/spinner';
import './item-details.css';
export const ItemRow = ({ item, field, label }) => {
return (
<li key={item.id} className="list-group-item">
<span className="term">{label}</span>
<span>{item[field]}</span>
</li>
);
};
export class ItemDetails extends Component {
state = {
item: null,
isLoading: false,
url: null
};
componentDidMount() {
this.updateItem();
}
componentDidUpdate(prevProps) {
if (prevProps.itemId !== this.props.itemId) {
this.updateItem();
}
}
updateItem() {
const { itemId, getData, getImg } = this.props;
if (!itemId) {
return;
}
this.setState({ isLoading: true });
getData(itemId).then(item =>
this.setState({
item,
isLoading: false,
url: getImg(itemId).then(res => {
this.setState({ url: res });
})
})
);
}
render() {
if (!this.state.item) {
return null;
}
const { name } = this.state.item;
const { item } = this.state;
const { isLoading, url } = this.state;
return (
<div className="item-details card">
{isLoading ? (
<Spinner />
) : (
<>
<img className="item-image" src={url} alt={name} />
<div className="card-body">
<h4>{name}</h4>
<ul className="list-group list-group-flush">
{React.Children.map(
this.props.children,
child => {
return React.cloneElement(child, {
item
});
}
)}
</ul>
</div>
</>
)}
</div>
);
}
}
|
Component({
properties: {
shadowFlag: {
type: Number,
value: 0,
},
index:{
type: Number,
value: 0
}
},
data: {
icons: [
['../../asset/images/tabBar-index.png', '../../asset/images/tabBar-index-active.png'],
['../../asset/images/tabBar-message.png', '../../asset/images/tabBar-message-active.png'],
['../../asset/images/tabBar-mine.png','../../asset/images/tabBar-mine-active.png']
]
},
methods: {
turnToPage (e) {
let url = e.currentTarget.dataset.url
url = "/pages/" + url + "/" + url;
wx.redirectTo({
url: url
})
}
}
})
|
import React from "react";
import "./style.scss";
function CalendarScreen() {
return (
<div className="calendar-root">
<div className="directories">
<div className="dir">1</div>
<div className="dir">2</div>
<div className="dir">3</div>
<div className="dir">4</div>
</div>
</div>
);
}
export default CalendarScreen;
|
import userIndex from "./index/index.js";
import reduce from "lodash/reduce";
const state = {
user: {
details: {},
contacts: [],
tokens: []
}
};
const getters = {
userDetails(state) {
return state.user.details;
},
accountContacts(state) {
return state.user.contacts;
},
anyContacts(state) {
// Contacts, if exist, are grouped by "usage policy" (their related JWT id)
const nbUsagePolicies = Object.keys(state.user.contacts).length;
return nbUsagePolicies > 0;
},
activeTokens(state) {
let tokens = state.user.tokens.filter(item => {
return item.archived === false && item.blacklisted === false;
});
return tokens.sort(
(token1, token2) => new Date(token2.iat) - new Date(token1.iat)
);
},
blacklistedTokens(state) {
let blacklistedTokens = state.user.tokens.filter(item => item.blacklisted);
return blacklistedTokens.sort(
(token1, token2) => new Date(token2.iat) - new Date(token1.iat)
);
},
archivedTokens(state) {
let archivedTokens = state.user.tokens.filter(item => item.archived);
return archivedTokens.sort(
(token1, token2) => new Date(token2.iat) - new Date(token1.iat)
);
}
};
const mutations = {
setUserDetails(state, details) {
state.user.details = details;
},
setContacts(state, contacts) {
// As the name points is we are regrouping the received contact's data by
// their related JWT. This is because we want to regroup contacts by their
// token's usage policy (see issue #68).
// Data received from API : [{id, email, phone_number, jwt_id, jwt_usage_policy, contact_type}, {...}]
// Data grouped by JWT : { jwt_id: { usage_policy: jwt_usage_policy, contacts_data: [{ id, email, ...}, ...] }, jwt_id: { ...} }
const jwtGroupedContacts = reduce(
contacts,
function(result, contact) {
const relatedJwtId = contact.jwt_id;
const relatedUsagePolicy = contact.jwt_usage_policy;
const contact_data = {
id: contact.id,
email: contact.email,
phone_number: contact.phone_number,
contact_type: contact.contact_type
};
if (result[relatedJwtId] === undefined) {
result[relatedJwtId] = {
usage_policy: relatedUsagePolicy,
contacts_data: []
};
}
result[relatedJwtId].contacts_data.push(contact_data);
return result;
},
{}
);
state.user.contacts = jwtGroupedContacts;
},
setTokens(state, tokens) {
state.user.tokens = tokens;
}
};
const actions = {
get({ dispatch, rootGetters }, { userId } = {}) {
const uid = userId || rootGetters["auth/currentUser"].id;
dispatch("role/index", null, { root: true })
.then(() =>
dispatch("api/admin/get", { url: `/users/${uid}` }, { root: true })
)
.then(data => dispatch("fillUserData", data));
},
update({ dispatch }, { params, userId }) {
return dispatch(
"api/admin/patch",
{ url: `/users/${userId}`, params },
{ root: true }
).then(() => dispatch("get", { userId }));
},
fillUserData({ commit }, data) {
commit("setUserDetails", {
id: data.id,
email: data.email,
context: data.context,
note: data.note
});
commit("setContacts", data.contacts);
commit("setTokens", data.tokens);
},
createToken({ dispatch, getters }, payload) {
const userId = getters.userDetails.id;
//TODO not RESTFull here since a post on the resource URL is already
//a "create" action. Authorizations (here checking this is an admin
//making the request) needs to be done server side.
//The URL should be /users/${userId}/jwt_api_entreprise
let url = `/users/${userId}/jwt_api_entreprise`;
dispatch(
"api/admin/post",
{ url: url, params: payload },
{ root: true }
).then(() => dispatch("get", { userId }));
},
transferAccount({ dispatch, getters }, payload) {
const userId = getters.userDetails.id;
let url = `/users/${userId}/transfer_ownership`;
return dispatch(
"api/admin/post",
{ url: url, params: payload },
{ root: true }
).then(data => dispatch("fillUserData", data));
},
blacklistToken({ dispatch, getters }, jwtId) {
const userId = getters.userDetails.id;
let url = `jwt_api_entreprise/${jwtId}`;
dispatch(
"api/admin/patch",
{ url: url, params: { blacklisted: true } },
{ root: true }
).then(() => dispatch("get", { userId }));
},
archiveToken({ dispatch, getters }, jwtId) {
const userId = getters.userDetails.id;
let url = `jwt_api_entreprise/${jwtId}`;
dispatch(
"api/admin/patch",
{ url: url, params: { archived: true } },
{ root: true }
).then(() => dispatch("get", { userId }));
},
create({ dispatch }, payload) {
return dispatch(
"api/admin/post",
{ url: "/users", params: payload },
{ root: true }
);
}
};
export default {
namespaced: true,
state,
mutations,
getters,
actions,
modules: {
index: userIndex
}
};
|
const React = require('react');
const {Route} = require('react-router');
// import Home from './views/Home';
import Landing from './views/Landing';
import JobCreator from './components/JobCreator';
const routes = (
<Route path="/" component={Landing}>
<Route path="jobs" component={JobCreator} />
</Route>
);
export default routes;
|
export { default as Comment } from './Comment'
export { default as Like } from './Like';
export { default as PaperPlane } from './PaperPlane';
|
import React from 'react'
import Header from '../components/Header'
import Footer from '../components/Footer'
import '../static/style/style.scss'
import Head from './../components/Head'
import CreateArticle from '../components/createArticlePage/create-article'
const adminPanel = () => {
return (
<>
<Head title="Admin Panel" />
<Header />
<CreateArticle />
<Footer />
</>
)
}
export default adminPanel
|
import React from 'react';
import { StyleSheet, Dimensions, Animated, PanResponder } from 'react-native';
import GoalCard from './GoalCard';
const SCREEN_WIDTH = Dimensions.get('window').width;
const SWIPE_TRIGGER = 250;
const SWIPE_LEFT = 0,
SWIPE_RIGHT = 1;
class SwipeableCard extends React.Component {
panResponder = null;
state = {
delta: new Animated.ValueXY(),
opacity: new Animated.Value(1),
swipeRight: false,
swipeLeft: false,
mediaIndex: 0,
};
gestureDirection(gestureState) {
if (Math.abs(gestureState.vx) > 1) {
return gestureState.vx > 0 ? SWIPE_RIGHT : SWIPE_LEFT;
}
if (Math.abs(gestureState.dx) > SCREEN_WIDTH - SWIPE_TRIGGER) {
return gestureState.dx > SCREEN_WIDTH - SWIPE_TRIGGER
? SWIPE_RIGHT
: SWIPE_LEFT;
}
return null;
}
componentWillMount() {
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => false,
onMoveShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: () => false,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderMove: (evt, gestureState) => {
this.state.delta.setValue({ x: gestureState.dx, y: gestureState.dy });
this.setState({
swipeRight: gestureState.dx > SCREEN_WIDTH - SWIPE_TRIGGER,
swipeLeft: gestureState.dx < -SCREEN_WIDTH + SWIPE_TRIGGER,
});
},
onPanResponderRelease: (evt, gestureState) => {
const direction = this.gestureDirection(gestureState);
if (direction !== null) {
Animated.parallel(
[
Animated.timing(this.state.delta.x, {
toValue:
direction === SWIPE_RIGHT ? SCREEN_WIDTH : -SCREEN_WIDTH,
duration: 200,
}),
Animated.timing(this.state.opacity, {
toValue: 0,
duration: 200,
}),
],
{ useNativeDriver: true }
).start(() => {
this.setState({ swipeLeft: false, swipeRight: false }, () => {
this.props.removeCard(direction === SWIPE_LEFT);
});
});
} else {
this.setState({
swipeLeft: false,
swipeRight: false,
});
Animated.spring(
this.state.delta,
{
toValue: { x: 0, y: 0 },
speed: 10,
bounciness: 8,
},
{ useNativeDriver: true }
).start();
}
},
});
}
render() {
const rotateCard = this.state.delta.x.interpolate({
inputRange: [-200, 0, 200],
outputRange: ['-20deg', '0deg', '20deg'],
});
return (
<Animated.View
{...this.panResponder.panHandlers}
style={[
styles.card,
{
opacity: this.state.opacity,
transform: [
{ translateX: this.state.delta.x },
{ translateY: this.state.delta.y },
{ rotate: rotateCard },
],
},
this.state.delta.x > 0 ? styles.cardShadow : {},
]}
>
<GoalCard
item={this.props.item}
swipeRight={this.state.swipeRight}
swipeLeft={this.state.swipeLeft}
/>
</Animated.View>
);
}
}
const styles = StyleSheet.create({
card: {
width: '85%',
height: '80%',
position: 'absolute',
borderRadius: 10,
backgroundColor: '#333',
overflow: 'hidden',
},
cardShadow: {
shadowColor: '#000',
shadowOffset: { width: 5, height: 5 },
shadowOpacity: 0.8,
shadowRadius: 20,
},
});
export default SwipeableCard;
|
import Moment from 'moment'
import Database from '../../server'
class Errors extends Database.Model
{
get tableName ()
{
return 'admin_errors'
}
toJSON ()
{
let values = Database.Model.prototype.toJSON.apply(this)
values.created_at = Moment(values.created_at).format('MMM D, YYYY (h:mm A)')
return values
}
}
export default Errors
|
'use strict';
// hash password
const Crypto = require('crypto');
module.exports = function(sequelize, DataTypes) {
var LocalUser = sequelize.define('LocalUser', {
uuid: { type: DataTypes.UUID, unique: true, defaultValue: DataTypes.UUIDV4 },
username: DataTypes.STRING,
email: DataTypes.STRING,
salt: DataTypes.STRING,
hash: DataTypes.STRING,
resetPasswordToken: DataTypes.STRING,
resetPasswordExpires: DataTypes.INTEGER,
admin: { type: DataTypes.BOOLEAN, defaultValue: false }
}, {
getterMethods: {
validPassword: function(password) {
var hash = Crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
return hash;
}
},
setterMethods: {
setPassword: function(password) {
this.setDataValue('salt', Crypto.randomBytes(16).toString('hex'));
this.setDataValue('hash', Crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex'));
}
}
});
LocalUser.associate = (models) => {
// associations can be defined here
LocalUser.belongsTo(models.User, {
foreignKey: 'userId',
otherKey: 'uuid',
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
});
};
return LocalUser;
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { configureStore } from '@reduxjs/toolkit'
import { setupListeners } from '@reduxjs/toolkit/query'
import {Provider} from 'react-redux'
import { authApi } from './features/authApi';
import reducer from './features/appSlice'
const store = configureStore({
reducer:{
[authApi.reducerPath]:authApi.reducer,
app: reducer
},
middleware: getDefaultMiddleware => getDefaultMiddleware().concat(authApi.middleware)
})
setupListeners(store.dispatch)
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
|
import React, { useState, useEffect } from "react";
import Countdown from "components/Counter/Countdown";
import StopGame from "components/StopGame";
import { TIME_TO_SUBMIT } from "graphQL/subscriptions";
import { useSubscription } from "@apollo/react-hooks";
import { useParams } from "react-router-dom";
import "./CountDown.css";
const applyCountdown = (WrappedComponent) => {
const HOC = (props) => {
const { gameId } = useParams();
const [finished, setFinished] = useState(false);
const timeToSubmit = useSubscription(TIME_TO_SUBMIT, {
variables: { gameId },
onSubscriptionData: ({ client, subscriptionData }) => {
console.log("TIME TO SUBMIT");
setFinished(true);
},
});
useEffect(() => {
const header = document.getElementById("CountDown");
const sticky = header.offsetTop;
const scrollCallBack = window.addEventListener("scroll", () => {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
});
return () => {
window.removeEventListener("scroll", scrollCallBack);
};
}, []);
const renderCounter = () => {
return !finished ? (
<Countdown
setTime={props.setTime}
submiter={() => setFinished(true)}
/>
) : (
<StopGame isGameMaster={props.isGameMaster} />
);
};
return (
<>
<div className="center" id="CountDown">
{renderCounter()}
</div>
<WrappedComponent {...props} finished={finished} />
</>
);
};
return HOC;
};
export default applyCountdown;
|
import React from "react";
import { Container, ItemLink, ItemsContainer, ItemText } from "./styles/header";
import { SiThemoviedatabase } from "react-icons/si";
import { BsDoorClosedFill } from "react-icons/bs";
import { IconContext } from "react-icons";
import { Link } from "react-router-dom";
import DropdownFavorites from "../../components/Dropdown";
import { useFirebase } from "../../context/firebase";
import { auth } from "../../utils/firebase";
function Header() {
const { currentUser } = useFirebase();
const signOut = async (e) => {
e.preventDefault();
try {
await auth.signOut();
} catch (error) {
console.log(error);
}
};
return (
<Container>
<Link to="/" data-testid="home-link">
<IconContext.Provider
value={{ style: { color: "#fff", fontSize: 60 } }}
>
<SiThemoviedatabase />
</IconContext.Provider>
</Link>
<ItemsContainer>
{currentUser ? (
<ItemText>
Seja bem vindo {currentUser.displayName}{" "}
<IconContext.Provider value={{ style: { fontSize: 25 } }}>
<BsDoorClosedFill onClick={signOut} data-testid="logout" />
</IconContext.Provider>{" "}
</ItemText>
) : (
<ItemLink to="/signin">Login</ItemLink>
)}
<DropdownFavorites />
</ItemsContainer>
</Container>
);
}
export default Header;
|
let personInfoFunction={
//控制sidebar开启和关闭
toggleSidebar:(state)=>{
state.sidebar.opened=!state.sidebar.opened;
},
//设置当前高亮的路由
setCurrentRoute:(state,path)=>{
state.headerCurRouter=path[0].path;
},
setCurrentSiderbarHighLight(state,path){
state.sidebarCurrentRouter=path
},
//控制用户修改密码的安全等级
safelyLevel:(state,level)=>{
state.level =level;
},
//获取所有用户的信息列表
user:(state,data)=>{
state.userList=data.user;
},
//获取用户的登录信息
userLoginMsg:(state,data)=>{
console.log(data);
state.user_msg=data;
},
//用户修改登录信息
editUserINfo:(state,userinfo)=>{
state.loginMsg=Object.assign({},userinfo)
},
//包管理列表
handlePackList:(state,pack)=>{
pack.map((item,key)=>{
item.editAble= false;
if(key===0) item.cho=true;
else item.cho=false;
if(item.groBusPackagesList)
item.groBusPackagesList.map((item1,key1)=>{
item1.edit=false;
item1.editAble= false;
})
})
state.packList=pack;
},
//商品管理列表
handleGoodsList:(state,goods)=>{
let temp_arr=[];
goods.map((item,key)=>{
if(item.parentId==1){
temp_arr.push(item)
}
});
function translate(old_arr,temp_i){
temp_i.child=[];
old_arr.map((item,key)=>{
if(item.parentId== temp_i.id){
temp_i.child.push(item)
}
})
if(!temp_i.child.length){return true}
else{
temp_i.child.map((item_arr)=>{
translate(old_arr,item_arr)
})
}
}
temp_arr.map((item)=>{
translate(goods,item)
})
console.log(temp_arr);
state.goodsList=temp_arr
},
getBusinessTableList:(state,list)=>{
state.BusinessTableList=list;
},
getFormList:(state,list)=>{
state.formList=list;
},
submitFormList:(state,msg)=>{
state.addFormListMsg=msg;
},
AddFormList:(state,msg)=>{
let trans =(obj,key)=>{
if(obj[key]==='1'){
obj[key]=true;
}
if(obj[key]==='0'){
obj[key]=false;
}
}
msg.genTable.columnList.map(function(item,key){
for(let i in item){trans(item,i)};
})
if(!msg.genTable.parentTable) msg.genTable.parentTable='';
if(!msg.genTable.parentTableFk) msg.genTable.parentTableFk='';
state.addFormList=msg;
},
deleFormListMsg:(state)=>{
state.addFormListMsg='';
},
//保存添加业务包信息
addChooseTableList:(state,data)=>{
state.chooseTableList=data
},
removeChooseTableList:(state)=>{
state.chooseTableList={
name:'',
id:'',
list:[]
}
}
}
export {personInfoFunction}
|
jQuery(document).ready(function () {
$('#fullpage').fullpage({
afterLoad: function () {
$('#video')[0].play();
this.addClass('anim');
}
, anchors: ['home', 'catalog', 'textures', 'tutorials', 'support', 'download']
, // scrollOverflow: true,
loopBottom: true
,
onLeave: function (link, index) {
this.addClass('leaveAnim');
if (index != 1) {
$('.top-menu').css('visibility', 'hidden');
if ($('.top-menu').hasClass('nextMenu')) {}
else {
$('.top-menu').addClass('nextMenu');
}
}
else {
$('.top-menu').css('visibility', 'visible');
if ($('.top-menu').hasClass('nextMenu')) {
$('.top-menu').removeClass('nextMenu');
}
}
}
});
//header
var heigth = $('.head-contant').css('height');
var margin = parseInt(heigth) / 2;
var newMargin = margin + 'px';
$('.head-contant').css('margin-top', -margin);
$(window).resize(function () {
var heigth = $('.head-contant').css('height');
var margin = parseInt(heigth) / 2;
var newMargin = margin + 'px';
$('.head-contant').css('margin-top', -margin);
});
});
|
'use strict';
const validate = require('../shared/validate');
const utils = require('../shared/utils');
const loadTemplates = require('./lib/loadTemplates');
const setupService = require('./lib/setupService');
const uploadArtifacts = require('./lib/uploadArtifacts');
const setupFunctions = require('./lib/setupFunctions');
const setupEvents = require('./lib/setupEvents');
const setupRole = require('./lib/setupRole');
const { hooksWrap } = require('../shared/visitor');
class AliyunDeploy {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.provider = this.serverless.getProvider('aliyun');
Object.assign(
this,
validate,
utils,
loadTemplates,
setupService,
uploadArtifacts,
setupFunctions,
setupEvents,
setupRole);
this.hooks = hooksWrap({
'before:deploy:deploy': async () => {
await this.validate();
this.setDefaults();
await this.loadTemplates();
},
'deploy:deploy': async () => {
await this.setupService();
await this.uploadArtifacts();
await this.setupFunctions();
await this.setupEvents();
}
}, 'deploy');
}
}
module.exports = AliyunDeploy;
|
// // var val1 = "var変数";
// // console.log(val1);
// // // var変数は上書き、再宣言可能
// // val1 = "var変数を上書き";
// // console.log(val1);
// // let val2 = "let変数";
// // console.log(val2);
// // val2 = "let変数を上書き";
// // console.log(val2);
// // // let val2 = "let変数を再宣言";
// // const val3 = "const変数";
// // val3 = "const";
// // const name = "じゃけぇ";
// // const age = 28;
// // const message1 = "私の名前は" + name + "です。年齢は" + age + "です。";
// // console.log(message1);
// // //テンプレート文字列を利用
// // const message2 = `私の名前は${name}です。年齢は${age}です`;
// // console.log(message2);
// // function func1(str) {
// // return str;
// // }
// // const func1 = function (str) {
// // return str;
// // };
// // console.log(func1("func1です"));
// // const func2 = (str) => {
// // return str;
// // };
// // const func3 = (num1, num2) => {
// // return num1 + num2;
// // };
// // console.log(func3(10, 30));
// // const myProfile = {
// // name: "ジャケぇ",
// // age: 28
// // };
// // const message1 = `名前は${myProfile.name}です。${myProfile.age}です。`;
// // console.log(message1);
// // const { name, age } = myProfile;
// // const message2 = `名前は${name}です。${age}です。`;
// // console.log(message2);
// // const myProfile = ["ジャケ", 28];
// // const message3 = `名前は${myProfile[0]}`;
// //デフォルト値
// // const sayHello = (name = "ゲスト") => console.log(`こんにちは${name}`);
// // sayHello();
// //スポレッド構文...
// // const arr1 = [1, 2];
// // // console.log(...arr1);
// // const sumFunc = (num1, num2) => console.log(num1 + num2);
// // sumFunc(arr1[0], arr1[1]);
// // sumFunc(...arr1);
// //まとめる
// // const arr2 = [1, 2, 3, 4, 5];
// // const [num1, num2, ...arr3] = arr2;
// // console.log(num1);
// // console.log(arr3);
// //配列のコピー、結合
// // const arr4 = [10, 20];
// // const arr5 = [30, 40];
// // console.log([...arr4, ...arr5]);
// //map,filterを利用
// const nameArr = ["たなか", "山田", "aa"];
// // for (let index = 0; index < nameArr.length; index++) {
// // console.log(nameArr[index]);
// // }
// // const nameArr2 = nameArr.map((name) => {
// // return name + "くん";
// // });
// // console.log(nameArr2);
// // const numArr = [1, 2, 3, 4, 5];
// // const newNumArr = numArr.filter((num) => {
// // return num % 2 === 1;
// // });
// // console.log(newNumArr);
// const newNameArr = nameArr.map((name) => {
// if (name === "aa") {
// return name;
// } else {
// return name + "さん";
// }
// });
// console.log(newNameArr);
//三項演算子
// const val1 = 1 > 0 ? "trueです" : "falseです";
// console.log(val1);
const num = 1300;
// console.log(num.toLocaleString());
const formattedNum =
typeof num === "number" ? num.toLocaleString() : "数値を入力してください";
console.log(formattedNum);
|
import React from 'react';
import { connect } from 'react-redux';
import './finalPage.css';
const PaymentPage = (props) => {
return (
<div className="finalPageContainer">
<div className="flex-container-row justify-center">
{props.shipmentPaid === true ?
<div>
<h2>Vei! Greiðsla fór í gegn og sending hefur verið búin til!</h2>
<p>
<span>Heimildarnúmer: {props.paymentResponse.authNumber}</span>
<br />
<span>Færslunúmer: {props.paymentResponse.transactionNumber}</span>
<br />
<span>Dagsetning: {props.paymentResponse.payDate}</span>
<br />
<span>Tími: {props.paymentResponse.payTime}</span>
<br />
<span>Kortanúmer: {props.paymentResponse.starredCcNumber}</span>
<br />
<span>Upphæð: {props.paymentResponse.amount} kr.</span>
</p>
</div> :
<h2>Eitthvað skrítið gerðist :(</h2>
}
</div>
</div>
);
};
function mapStateToProps(state) {
return {
shipmentPaid: state.transactionDetails.shipmentPaid,
paymentResponse: state.transactionDetails.chargeResponse,
};
}
export default connect(mapStateToProps)(PaymentPage);
|
var express = require('express');
var app = express();
app.set('port', process.env.IMDB_SERVER_PORT);
var server = app.listen(app.get('port'));
var handler = function() {
server.close();
};
|
import { addItem } from '../../utils/AddItem';
import CareScale from '../CareScale/CareScale';
import './styles.css';
function PlantItem({ id, name, description, price, image, light, carbon, setCart, cart }) {
return (
<li className="plant-item" onClick={() => addItem(name, id, price, setCart, 1, cart)}>
<img className="plant-item__image" src={`./assets/${image}`} alt={`${name}`} />
<div className="plant-item__info">
<div className="plant-item__name">{name}</div>
<div className="plant-item__description">{description}</div>
<CareScale light={light} carbon={carbon} />
</div>
<div className="plant-item__price">{price}€</div>
</li>
);
}
export default PlantItem;
|
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import actions from './actions'
import mutations from './mutations'
export default new Vuex.Store({
state: {
// shopIndex: 0,
// reLoading: false,
docEle: null,
maitKey: Number,
// i: 0,
carList: [],
// AllSel: false,
totalPrice: 0,
isActive: ''
},
actions,
mutations,
getters: {
totalPrice: state => {
let AllTotal = 0
state.carList.forEach((item) => {
if (item.isCheck) {
AllTotal += item.count * item.price
}
// console.log(AllTotal)
})
return AllTotal.toFixed(2)
},
// 计算是否全选
AllSel(state) {
let flag = ''
state.carList.forEach(item => {
if (item.isCheck === false) {
flag = false
console.log('出现false')
} else {
flag = true
console.log('出现true')
}
})
return flag
}
},
// mutations: {
// // 点击减少特定index商品数量
// inCrement(state, index) {
// state.CarList[index].sum--
// },
// // 点击增加特定index商品数量
// deCrement(state, index) {
// state.CarList[index].sum++
// },
// changeShopIndex(state, index, loading) {
// state.shopIndex = index
// state.reLoading = loading
// },
// // 如果选中,接收该商品的总价
// childCheck(state, newV) {
// state.totalPrice += newV
// },
// // 是否全选
// selectAll(state, flag) {
// state.cheSelectAll = !state.cheSelectAll
// console.log('提交了')
// // 全选的时候把各个商品都选中
// for (let i = 0; i < state.CarList.length; i++) {
// console.log('进来了')
// state.CarList[i].ischeck = !state.CarList[i].ischeck
// }
// // console.log(state.cheSelectAll)
// // console.log(flag)
// },
// // 如果有单选选中,就判断全选状态
// allSelState(state) {
// this.selectAll()
// },
// // 购物车总数
// incrementItem(state, payload) {
// let ListLength = state.CarList.length
// // let sum = payload.sum
// if (ListLength === 0) {
// state.CarList.push(payload)
// // return
// } else {
// // console.log('进入else--长度大于0')
// // let option = { iid: payload.iid }
// let result = state.CarList.some(function (item, index) {
// if (item.iid == payload.iid) {
// this[index].sum++
// // console.log('this是谁---', this)
// return true
// }
// }, state.CarList)
// if (result) {
// // console.log('里面有这个iid了')
// } else {
// // console.log('false ,里面没有找到这个iid,push进去')
// state.CarList.push(payload)
// }
// // 循环里面没有一样的iid的话
// }
// }
// },
modules: {
}
})
|
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const root = require('app-root-path');
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
entry: {
bundle: __dirname + '/main',
worker: __dirname + '/worker',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Development',
}),
],
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
loader: 'ts-loader',
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
fallback: {
assert: require.resolve('assert'),
buffer: require.resolve('buffer'),
path: require.resolve('path-browserify'),
process: require.resolve('process/browser'),
stream: require.resolve('readable-stream'),
url: require.resolve('url'),
util: require.resolve('util'),
},
},
externals: {
fs: 'window.fs',
},
output: {
filename: '[name].js',
path: path.resolve(root.path, 'dist'),
},
devServer: {
// HTTPS is required for SharedArrayBuffer to work.
https: true,
headers: {
// These two headers are required for SharedArrayBuffer to work.
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp",
},
port: 9876,
hot: false,
},
};
|
import React from 'react';
import { Link, withRouter, Redirect } from 'react-router-dom';
class RecentActivity extends React.Component {
constructor(props){
super(props);
}
componentDidMount(){
this.props.getTrades();
}
componentWillReceiveProps(newProps){
if(this.props.transactions.length !== newProps.transactions.length){
this.props.getTrades();
}
}
getImage(transaction){
if(transaction.coin === "Bitcoin"){
return window.images.bitcoin_tran;
} else if(transaction.coin === "Bitcoin Cash"){
return window.images.bitcoincash_tran;
} else if(transaction.coin === "Ethereum"){
return window.images.ethereum_tran;
} else if(transaction.coin === "Litecoin"){
return window.images.litecoin_tran;
}
}
getWords(transaction){
let answer = "";
if(transaction.buy) answer += "Bought "
else answer += "Sold "
answer += transaction.coin
return answer;
}
getAmount(transaction){
let answer = "";
if(transaction.buy) answer += "+";
else answer += "=";
answer += transaction.size.toFixed(6);
switch (transaction.coin) {
case "Bitcoin":
answer += " BTC";
break;
case "Ethereum":
answer += " ETH";
break;
case "Bitcoin Cash":
answer += " BCH";
break;
case "Litecoin":
answer += " LTC";
break;
}
return answer;
}
getMoney(transaction){
let answer = "";
if(transaction.buy) answer += "+$";
else answer += "-$";
answer += transaction.price;
return answer;
}
buildTradeItem(transaction){
if(transaction === undefined){
return (<div></div>)
} else {
let date = new Date();
if(transaction.created_at) date = new Date(transaction.created_at)
let monthHelper = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return (
<div className="tran-sum-tran-container">
<div className='port-sum-date'>
<div>{monthHelper[date.getMonth()]}</div>
<div>{date.getDate()}</div>
</div>
<div>
<img src={this.getImage(transaction)} className="tran-sum-img"></img>
</div>
<div>
<p>{this.getWords(transaction)}</p>
</div>
<div className='tran-sum-amount'>
<div>{this.getAmount(transaction)}</div>
<div className='tran-sum-money-amount'>{this.getMoney(transaction)}</div>
</div>
</div>
);
}
}
render(){
let keys = Object.keys(this.props.transactions);
let firstTransaction = this.props.transactions[keys[keys.length-1]];
let secondTransaction = this.props.transactions[keys[keys.length-2]];
let thirdTransaction = this.props.transactions[keys[keys.length-3]];
let fourthTransaction = this.props.transactions[keys[keys.length-4]];
return (
<div className="tran-sum-main-container">
<div className='tran-recent-items'>
<p className='tran-recent-act-words-ra'>Recent Activity</p>
{this.buildTradeItem(firstTransaction)}
{this.buildTradeItem(secondTransaction)}
{this.buildTradeItem(thirdTransaction)}
{this.buildTradeItem(fourthTransaction)}
</div>
</div>
);
}
}
export default withRouter(RecentActivity);
|
/**
* Created by benben on 17/3/4.
*/
/**
* Created by benben on 17/3/4.
*/
/**
* Created by benben on 17/3/3.
*/
import React from 'react'
import AddrOption from './AddrOption'
class AddrSelect extends React.Component {
constructor(props) {
super(props);
}
Selected = (e) => {
this.props.selteddiqu(e.target.value)
}
render() {
var options = [];
if (this.props.diqu.diqu != undefined && this.props.diqu.diqu.length != 0) {
this.props.diqu.diqu.forEach(function (data) {
options.push(<AddrOption name={data.name} id={data.id}/>)
}.bind(this));
}
return (
<div>
<select
name="province"
id="province"
onChange={this.Selected}
defaultValue={'请选择'}
>
{options}
</select>
</div>
)
}
}
export default AddrSelect
|
import "./css/App.css";
import React from "react";
import axios from "axios";
import Profile from "./Profile.js";
import HomePage from "./home_page";
import {BrowserRouter as Router, Route} from 'react-router-dom';
import {Redirect} from 'react-router-dom'
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap-css-only/css/bootstrap.min.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
repos: [], // array of all the user repos
user: null, // user information
first_visit: true, // used for redirect the user to the home page in case you activate it in the routes
loading: false, // to display the spin while loading data
};
}
//function responsible for searching the user github account and get his repositories
async search(term) {
this.setState({loading: true, first_visit: false });
await axios
.post(`${process.env.REACT_APP_URL}api/repos`, { term })
.then((response) => {
console.log(response);
if (response.data.name === "Error") {
this.setState({ repos: [], user: null, loading: false });
} else {
this.setState({
repos: response.data.repos,
user: response.data.user,
loading: false,
});
document.getElementsByClassName("search-input")[0].value = "";
}
});
}
render() {
return (
// at first there was HomePage lack of time I did'nt get the chance to work on some details to make it perfect. you still can activate it
// by disabling the comments inside the router and comment the last Route tag
<Router>
{/*<Route exact path='/' component={() => !this.state.user ? <HomePage user={this.state.user} found={this.state.found} search={this.search.bind(this)}/> :*/}
{/* <Redirect to='/profile'/>}/>*/}
{/*<Route path='/profile' component={() => this.state.first_visit ? <Redirect to='/'/> : */}
<Route exact path='/' component={() => <Profile loading = {this.state.loading} user={this.state.user} repos={this.state.repos} onSearch={this.search.bind(this)}/>}
/>
</Router>
);
}
}
export default App;
|
'use strict'
const expect = require('chai').expect
const sinon = require('sinon')
const semver = require('semver')
const INTERVAL = 60 * 1000
if (!semver.satisfies(process.version, '>=10.12')) {
describe = describe.skip // eslint-disable-line no-global-assign
}
describe('profiler', () => {
let Profiler
let profiler
let cpuProfiler
let cpuProfile
let cpuPromise
let heapProfiler
let heapProfile
let heapPromise
let clock
let exporter
let exporters
let profilers
let consoleLogger
let logger
beforeEach(() => {
clock = sinon.useFakeTimers()
exporter = {
export: sinon.stub().resolves()
}
consoleLogger = {
error: sinon.spy()
}
cpuProfile = {}
cpuPromise = Promise.resolve(cpuProfile)
cpuProfiler = {
type: 'cpu',
start: sinon.stub(),
stop: sinon.stub(),
profile: sinon.stub().resolves(cpuPromise)
}
heapProfile = {}
heapPromise = Promise.resolve(heapProfile)
heapProfiler = {
type: 'heap',
start: sinon.stub(),
stop: sinon.stub(),
profile: sinon.stub().returns(heapPromise)
}
logger = consoleLogger
exporters = [exporter]
profilers = [cpuProfiler, heapProfiler]
Profiler = require('../../src/profiling/profiler').Profiler
profiler = new Profiler()
})
afterEach(() => {
profiler.stop()
clock.restore()
})
it('should start the internal time profilers', () => {
profiler.start({ profilers, exporters })
sinon.assert.calledOnce(cpuProfiler.start)
sinon.assert.calledOnce(heapProfiler.start)
})
it('should start only once', () => {
profiler.start({ profilers, exporters })
profiler.start({ profilers, exporters })
sinon.assert.calledOnce(cpuProfiler.start)
sinon.assert.calledOnce(heapProfiler.start)
})
it('should stop the internal profilers', () => {
profiler.start({ profilers, exporters })
profiler.stop()
sinon.assert.calledOnce(cpuProfiler.stop)
sinon.assert.calledOnce(heapProfiler.stop)
})
it('should stop when starting failed', () => {
cpuProfiler.start.throws()
profiler.start({ profilers, exporters, logger })
sinon.assert.calledOnce(cpuProfiler.stop)
sinon.assert.calledOnce(heapProfiler.stop)
sinon.assert.calledOnce(consoleLogger.error)
})
it('should stop when capturing failed', () => {
cpuProfiler.profile.throws()
profiler.start({ profilers, exporters, logger })
clock.tick(INTERVAL)
sinon.assert.calledOnce(cpuProfiler.stop)
sinon.assert.calledOnce(heapProfiler.stop)
sinon.assert.calledOnce(consoleLogger.error)
})
it('should flush when the interval is reached', async () => {
profiler.start({ profilers, exporters })
clock.tick(INTERVAL)
await cpuPromise
await heapPromise
sinon.assert.calledOnce(exporter.export)
})
it('should export profiles', async () => {
profiler.start({ profilers, exporters, tags: { foo: 'foo' } })
clock.tick(INTERVAL)
await cpuPromise
await heapPromise
const { profiles, start, end, tags } = exporter.export.args[0][0]
expect(profiles).to.have.property('cpu', cpuProfile)
expect(profiles).to.have.property('heap', heapProfile)
expect(start).to.be.a('date')
expect(end).to.be.a('date')
expect(end - start).to.equal(60000)
expect(tags).to.have.property('foo', 'foo')
})
it('should not start when disabled', () => {
profiler.start({ profilers, exporters, enabled: false })
sinon.assert.notCalled(cpuProfiler.start)
sinon.assert.notCalled(heapProfiler.start)
})
it('should log exporter errors', async () => {
exporter.export.rejects()
profiler.start({ profilers, exporters, logger })
clock.tick(INTERVAL)
await cpuPromise
await heapPromise
await Promise.resolve() // wait for internal promise
sinon.assert.calledOnce(consoleLogger.error)
})
})
|
// @flow
/* **********************************************************
* File: UpdateModal.js
*
* Brief: Modal that indicates to a user that an new version
* of the app is available and will be installed shortly
*
* Authors: Craig Cheney
*
* 2017.09.18 CC - Document created
*
********************************************************* */
import React, { Component } from 'react';
import { Modal } from 'react-bootstrap';
type PropsType = {
pending: boolean,
version: string
};
export default class UpdateModal extends Component<PropsType> {
render() {
return (
<div>
<Modal show={this.props.pending}>
<Modal.Header>
<Modal.Title className='text-center'>Version {this.props.version} Available</Modal.Title>
</Modal.Header>
<Modal.Body>
<h4 className='text-center'>
A newer version of MICA Desktop is available. It will be
automatically downloaded and installed.
</h4>
<p />
<h4 className='text-center'>The Application will restart shortly</h4>
</Modal.Body>
</Modal>
</div>
);
}
}
/* [] - END OF FILE */
|
var WsPreviewController = function($viewContainer, model) {
var self = this;
var view = null;
var pageView = null;
var pageBgView = null;
var pageIView = null;
var scale = 1;
var page = 0;
var runningTitles = null;
self.getViewContainer = function() {
return $viewContainer;
};
self.getView = function() {
return view;
};
self.getPageView = function() {
return pageView;
};
self.getPageBgView = function() {
return pageBgView;
};
function initItem(item) {
var factory = WsItemFactory.forType(item.type);
var itemView = factory.createView(item);
factory.render(itemView);
return item;
};
function addItems(price, level) {
var menuModel = model.get();
var page = level === 1 ? 0 : menuModel.pages.push([]) - 1;
for (var key in price) {
if (key === 'category') {
continue;
}
if (typeof price[key] === 'object' && !Array.isArray(price[key])) {
if (typeof price[key].media === 'undefined') {
menuModel.pages[page].push(initItem({
type : 'template',
config : {
template : 'link' + (level > 2 ? 2 : level),
price : key
}
}));
addItems(price[key], level + 1);
} else {
var template = null;
if (price[key].template) {
var event = $.Event('message', {
id : 'gettemplate',
template : price[key].template
});
$(window).triggerHandler(event);
template = (event.template && event.template.name) ?
event.template.name : 'default';
}
menuModel.pages[page].push(initItem({
type : 'template',
config : {
template : template ? template : 'default',
price : key
}
}));
}
}
}
menuModel.pages[page].push(initItem({
type : 'ps'
}));
}
$viewContainer.data('wsController', self);
$viewContainer.addClass('pd-ws');
view = new Kinetic.Stage({
container: $viewContainer.get(0)
});
view.setSize({
width : $viewContainer.innerWidth(),
height : $viewContainer.innerHeight()
});
pageIView = new Kinetic.Layer();
view.add(pageIView);
pageIView.setSize(view.getSize());
var scaleBoard = new Kinetic.Group({
height : 72,
width : 196,
x : 20,
y : view.getHeight() - 92
});
scaleBoard.on('mouseover', function(evt) {
this.find('.scalesRect').setOpacity(0.5);
pageIView.batchDraw();
});
scaleBoard.on('mouseout', function(evt) {
this.find('.scalesRect').setOpacity(0.3);
pageIView.batchDraw();
});
var scalesRect = new Kinetic.Rect({
name : 'scalesRect',
height : 72,
width : 196,
fill : 'white',
cornerRadius : 13,
opacity : 0.3
});
scaleBoard.add(scalesRect);
var zoomInButton = new Kinetic.Image({
height : 48,
width : 48,
x : 136,
y : 12,
opacity : 1
});
zoomInButton.on('click', function(evt) {
self.setScale(scale + 0.1);
}).on('mouseover', function(evt) {
document.body.style.cursor = 'pointer';
}).on('mouseout', function(evt) {
document.body.style.cursor = 'default';
});
scaleBoard.add(zoomInButton);
var zoomInButtonImage = new Image();
zoomInButtonImage.onload = function() {
zoomInButton.setImage(this);
pageIView.draw();
};
zoomInButtonImage.src = 'public/images/zoomIn.png';
var zoomOutButton = new Kinetic.Image({
height : 48,
width : 48,
x : 12,
y : 12,
opacity : 1
});
zoomOutButton.on('click', function(evt) {
self.setScale(scale - 0.1);
}).on('mouseover', function(evt) {
document.body.style.cursor = 'pointer';
}).on('mouseout', function(evt) {
document.body.style.cursor = 'default';
});
scaleBoard.add(zoomOutButton);
var zoomOutButtonImage = new Image();
zoomOutButtonImage.onload = function() {
zoomOutButton.setImage(this);
pageIView.draw();
};
zoomOutButtonImage.src = 'public/images/zoomOut.png';
var scaleValue = new Kinetic.Text({
fontSize : 32,
text : '100',
fontFamily : 'Arial',
fill : 'black'
});
scaleValue.on('click', function(evt) {
self.setScale(1);
});
var percent = new Kinetic.Text({
fontSize : 16,
text : '%',
fontFamily : 'Georgia',
fill : 'black',
fontStyle : 'bold'
});
percent.setPosition({
x : 124 - percent.width() / 2,
y : 36 - percent.height() / 2
});
scaleBoard.add(percent);
scaleValue.setPosition({
x : 88 - scaleValue.width() / 2,
y : 36 - scaleValue.height() / 2
});
scaleBoard.add(scaleValue);
pageIView.add(scaleBoard);
var pageBoard = new Kinetic.Group({
height : 72,
width : 176,
x : view.getWidth() - 196,
y : view.getHeight() - 92
});
pageBoard.on('mouseover', function(evt) {
this.find('.pagesRect').setOpacity(0.5);
pageIView.batchDraw();
}).on('mouseout', function(evt) {
this.find('.pagesRect').setOpacity(0.3);
pageIView.batchDraw();
});
var pagesRect = new Kinetic.Rect({
name : 'pagesRect',
height : 72,
width : 176,
fill : 'white',
cornerRadius : 13,
opacity : 0.3
});
pageBoard.add(pagesRect);
var pageNumber = new Kinetic.Text({
fontSize : 32,
text : '1',
fontFamily: 'Arial',
fill : 'black',
width : pageBoard.getWidth(),
align : 'center'
});
pageNumber.setY(36 - pageNumber.height() / 2);
//pageNumber.setPosition({
//x : 88 - pageNumber.width() / 2,
//y : 36 - pageNumber.height() / 2
//});
pageBoard.add(pageNumber);
var leftArrow = new Kinetic.Image({
height : 48,
width : 48,
x : 12,
y : 12,
opacity : 1
});
leftArrow.on('click', function(evt) {
if (page > 0) {
self.onPageSelect(--page);
}
}).on('mouseover', function(evt) {
document.body.style.cursor = 'pointer';
}).on('mouseout', function(evt) {
document.body.style.cursor = 'default';
});
pageBoard.add(leftArrow);
var leftArrowImage = new Image();
leftArrowImage.onload = function() {
leftArrow.setImage(this);
pageIView.draw();
};
leftArrowImage.src = 'public/images/left.png';
var rightArrow = new Kinetic.Image({
height : 48,
width : 48,
x : 116,
y : 12,
opacity : 1
});
rightArrow.on('click', function(evt) {
if (page < model.get().pages.length - 1) {
self.onPageSelect(++page);
}
}).on('mouseover', function(evt) {
document.body.style.cursor = 'pointer';
}).on('mouseout', function(evt) {
document.body.style.cursor = 'default';
});
pageBoard.add(rightArrow);
var rightArrowImage = new Image();
rightArrowImage.onload = function() {
rightArrow.setImage(this);
pageIView.draw();
};
rightArrowImage.src = 'public/images/right.png';
pageIView.add(pageBoard);
pageIView.draw();
pageView = new Kinetic.Layer();
view.add(pageView);
pageBgView = new Kinetic.Layer();
var localPosition = null;
view.on('mousedown', function(evt) {
if (evt.evt.button === 1) {
document.body.style.cursor = 'pointer';
localPosition = {
x : view.pointerPos.x - pageView.getPosition().x,
y : view.pointerPos.y - pageView.getPosition().y
};
}
}).on('mouseup', function(){
document.body.style.cursor = 'default';
localPosition = null;
}).on('mousemove', function(evt) {
if (evt.evt.button === 1) {
if (pageView.getHeight() * scale > view.getHeight() && (pageView.getPosition().y < view.getPosition().y + 8)) {
self.setPagePosition({
//x : evt.evt.offsetX - localPosition.x,
y : evt.evt.offsetY - localPosition.y
});
}
pageBgView.batchDraw();
pageView.batchDraw();
}
});
var pageBg = new Kinetic.Image({
name : 'bg',
stroke : '#222',
strokeWidth : 1
});
pageBgView.add(pageBg);
view.add(pageBgView);
pageBgView.draw();
pageBgView.moveToBottom();
pageIView.moveToTop();
self.generate = function(price) {
var menuModel = model.get();
menuModel.pages = [[]];
menuModel.pages[0].push(initItem({
type : 'template',
config : {
template : 'cover',
price : null
}
}));
addItems(price, 1);
model.update();
$(window).triggerHandler($.Event('message', {
id : 'store',
ns : 'wscontroller',
state : model.get()
}));
};
self.getPage = function() {
return page;
};
self.setBgColor = function(color) {
if (typeof color === 'undefined' || color === null) {
color = 'transparent';
}
pageBg.fill(color);
pageBgView.draw();
};
self.setBgImage = function(src) {
if (typeof src === 'undefined' || src === null) {
pageBg.setImage(new Image());
return;
}
var imageObject = new Image();
imageObject.onload = function() {
pageBg.setImage(imageObject);
pageBgView.draw();
};
imageObject.onerror = function() {
pageBg.setImage(null);
pageBgView.draw();
};
imageObject.src = src;
};
self.onPageSelect = function(selectedPage) {
page = selectedPage;
pageNumber.setText(page + 1);
if (!self.isFocused()) {
return;
}
self.render();
pageIView.batchDraw();
self.firePagesChangeEvent();
};
var windowResizeEventTimerId = 0;
self.onWindowResize = function() {
clearTimeout(windowResizeEventTimerId);
windowResizeEventTimerId = setTimeout(function() {
self.updateViewGeometry();
}, 250);
};
self.setScale = function(newScale) {
if (newScale < 0.01) {
scale = scale < 0.1 ? scale : 0.1;
} else {
scale = newScale;
}
if (newScale > 4) {
scale = 4;
}
scaleObject = {
x : scale,
y : scale
};
scaleValue.setText(Math.round(scale * 100));
scaleValue.setPosition({
x : 88 - scaleValue.width() / 2,
y : 36 - scaleValue.height() / 2
});
pageView.setScale(scaleObject);
pageBgView.setScale(scaleObject);
self.updateViewGeometry();
};
self.getScale = function() {
return scale;
};
self.setPagePosition = function(position) {
pageView.setPosition(position);
pageBgView.setPosition(position);
};
self.setPageSize = function(size) {
pageView.setSize(size);
pageBgView.setSize(size);
pageBgView.getChildren().setSize(size);
};
self.updateViewGeometry = function() {
view.setSize({
width : $viewContainer.width(),
height : $viewContainer.height()
});
var safeScale = scale === 0 ? 1 : scale;
self.setPagePosition({
x : (view.getWidth() - pageView.getWidth() * safeScale) / 2,
y : (view.getHeight() - pageView.getHeight() * safeScale) / 2
});
view.draw();
};
var selectEventListeners = [];
self.fireSelectEvent = function(selected) {
for (var i in selectEventListeners) {
selectEventListeners[i].onSelect(selected);
}
};
self.addSelectEventListener = function(listener) {
selectEventListeners.push(listener);
};
self.removeSelectEventListener = function(listener) {
var index = selectEventListeners.indexOf(listener);
if (index == -1) {
return;
}
selectEventListeners.splice(index, 1);
};
var focused = false;
self.isFocused = function() {
return focused;
};
self.focus = function() {
var $focusedWsController = $('.pd-ws-focused');
if ($focusedWsController.length !== 0) {
var focusedWsController = $focusedWsController.data('wsController');
if (focusedWsController === self) {
return;
}
focusedWsController.blur();
}
$viewContainer.addClass('pd-ws-focused');
self.updateViewGeometry();
focused = true;
};
self.blur = function(passOnFocus) {
if (!self.isFocused()) {
return;
}
if (passOnFocus) {
var $unfocusedWsControllers = $('.pd-ws:not(.pd-ws-focused)');
if ($unfocusedWsControllers.length !== 0) {
var unfocusedWsController = $unfocusedWsControllers.eq(0)
.data('wsController');
unfocusedWsController.focus();
return;
}
}
$viewContainer.removeClass('pd-ws-focused');
self.fireSelectEvent();
focused = false;
};
var pagesChangeEventListeners = [];
self.firePagesChangeEvent = function() {
for (var i in pagesChangeEventListeners) {
pagesChangeEventListeners[i].onPagesChange(page,
model.get().pages.length);
}
};
self.addPagesChangeEventListener = function(listener) {
pagesChangeEventListeners.push(listener);
};
self.removePagesChangeEventListener = function(listener) {
var index = pagesChangeEventListeners.indexOf(listener);
if (index == -1) {
return;
}
pagesChangeEventListeners.splice(index, 1);
};
self.updateRunningTitles = function() {
if (runningTitles !== null) {
runningTitles.header.remove();
runningTitles.footer.remove();
runningTitles = null;
}
var itemViews = pageView.getChildren(function(node) {
return node.getAttr('model');
});
if (itemViews.length === 0
|| itemViews[0].getY() !== 0) {
var headerItem = {
p : page,
x : 0,
y : 0,
config : {
template : 'header'
}
};
var wsItemFactory = WsItemFactory.forType('template');
var headerItemView = wsItemFactory.createView(headerItem);
pageView.add(headerItemView);
wsItemFactory.render(headerItemView);
var footerItem = {
p : page,
x : 0,
y : 0,
config : {
template : 'footer'
}
};
var footerItemView = wsItemFactory.createView(footerItem);
footerItemView.setY(model.get().height - footerItem.h);
pageView.add(footerItemView);
wsItemFactory.render(footerItemView);
runningTitles = {
header : headerItemView,
footer : footerItemView
};
}
pageView.batchDraw();
};
self.render = function() {
pageView.getChildren(function(node) {
return node.getAttr('model');
}).remove();
var items = model.get(page);
var renderedItemCount = 0;
var itemCount = items.length;
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.type === 'ps' || item.type === 'ls') {
if (++renderedItemCount === itemCount) {
self.updateRunningTitles();
}
continue;
}
var wsItemFactory = WsItemFactory.forType(item.type);
itemView = wsItemFactory.createView(item);
pageView.add(itemView);
itemView.setZIndex(item.zIndex);
itemView.setAttr('index', item.i);
itemView.on('render', function() {
if (++renderedItemCount === itemCount) {
self.updateRunningTitles();
}
});
wsItemFactory.render(itemView);
}
};
self.setPageSize({
width : model.getWidth(),
height : model.getHeight()
});
$(window).on('resize.pdWsPreviewController', self.onWindowResize);
};
|
import verify from '../../http/requests/verify';
export default {
// eslint-disable-next-line no-unused-vars
check({ commit }, payload) {
const { secret } = payload;
return new Promise((resolve, reject) => {
verify
.check(secret)
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
},
// eslint-disable-next-line no-unused-vars
send({ commit }, payload) {
const { dbid, secret } = payload;
return new Promise((resolve, reject) => {
verify
.send(dbid, secret)
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
},
// eslint-disable-next-line no-unused-vars
login({ commit }, payload) {
const { token, dbid, secret } = payload;
return new Promise((resolve, reject) => {
verify
.login(token, dbid, secret)
.then((response) => {
resolve(response);
})
.catch((error) => {
reject(error);
});
});
}
};
|
import React from 'react'
import {Redirect, Route} from "react-router-dom";
import {connect} from 'react-redux'
import MainAdmin from "../../../container/template-parts/main/MainAdmin";
const AdminRoute = ({component: Component, rest}) => (
<Route
{...rest}
render={(props) => {
return (
<MainAdmin>
<Component {...props}/>
</MainAdmin>
)
}}
/>
)
const mapStateToProps = state => ({
is_admin: state.Admin.is_admin
})
export default connect(mapStateToProps, {})(AdminRoute)
|
import React, { Component } from 'react'
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
import { faCcApplePay } from '@fortawesome/free-brands-svg-icons';
export default class FooterItem extends Component {
render() {
return (
<div className='footer__item'>
<FontAwesomeIcon icon={faQuestionCircle}/>
{/* {this.props.item.title} */}
</div>
)
}
}
|
const NeteaseMusic = require('simple-netease-cloud-music');
const songsMapper = require('./songs_mapper');
const nm = new NeteaseMusic();
const getPlaylist = (playlistId) => {
return new Promise((resolve, reject) => {
nm.playlist(playlistId).then(data => {
if (data.code === 200 && data.playlist) {
// console.log(data.playlist);
const { playlist } = data;
resolve({
name: playlist.name,
songs: songsMapper(playlist.tracks),
});
} else {
reject({
message: '',
});
}
});
});
};
// getPlaylist('5092808871')
module.exports = getPlaylist;
|
var gulp = require( 'gulp' ),
deploy = require( 'gulp-gh-pages' );
gulp.task( 'deploy', function() {
return gulp.src( './public_html/**/*' ).pipe(
deploy({
remoteUrl:
'https://github.com/GlisseLisbeth/landing_sodimac_web.git',
branch: 'master'
})
);
});
|
import { LightningElement, wire, track, api } from 'lwc';
import retrieveNBAContentFields from '@salesforce/apex/TaskService.retrieveNBAContentFields';
import updateTask from '@salesforce/apex/TaskService.updateTaskRecord';
import { getRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
export default class TaskNBADocumentListComp extends LightningElement {
@api recordId; // required for record pages. Automatically populated by lightning app builder.
@track contents;
@track displayList;
@track tskId;
@api tskURL;
wiredAccountsResult;
// this method is called when the component is loaded
connectedCallback(){
this.handleLoad();
}
// do an apex method call via imperative method (JS promise)
handleLoad(){
retrieveNBAContentFields({recordIds : [ this.recordId ] })
.then(data => {
this.contents = new Array();
this.displayList = false;
for(var x=0;x<data.length;x++){
var iconVal;
// blank field is not added as part of the returned data so check if field is undefined
if(data[x].NBA_Content_URL1__c!=undefined){
this.displayList = true;
iconVal = this.getIconType(data[x].NBA_Content_URL1__c);
this.contents.push({
key : 'NBA_Content_URL1__c',
iconName : iconVal,
docURL : data[x].NBA_Content_URL1__c,
docDesc : data[x].NBA_Content_Desc1__c
});
}
if(data[x].NBA_Content_URL2__c!=undefined){
this.displayList = true;
iconVal = this.getIconType(data[x].NBA_Content_URL2__c);
this.contents.push({
key : 'NBA_Content_URL2__c',
iconName : iconVal,
docURL : data[x].NBA_Content_URL2__c,
docDesc : data[x].NBA_Content_Desc2__c
});
}
if(data[x].NBA_Content_URL3__c!=undefined){
this.displayList = true;
iconVal = this.getIconType(data[x].NBA_Content_URL3__c);
this.contents.push({
key : 'NBA_Content_URL3__c',
iconName : iconVal,
docURL : data[x].NBA_Content_URL3__c,
docDesc : data[x].NBA_Content_Desc3__c
});
}
if(data[x].NBA_Content_URL4__c!=undefined){
this.displayList = true;
iconVal = this.getIconType(data[x].NBA_Content_URL4__c);
this.contents.push({
key : 'NBA_Content_URL4__c',
iconName : iconVal,
docURL : data[x].NBA_Content_URL4__c,
docDesc : data[x].NBA_Content_Desc4__c
});
}
if(data[x].NBA_Content_URL5__c!=undefined) {
this.displayList = true;
iconVal = this.getIconType(data[x].NBA_Content_URL5__c);
this.contents.push({
key: 'NBA_Content_URL5__c',
iconName : iconVal,
docURL: data[x].NBA_Content_URL5__c,
docDesc: data[x].NBA_Content_Desc5__c
});
}
}
})
.catch(error => {
console.log(error);
});
}
getIconType(docUrl){
// retun default value if null
console.log(docUrl);
if(docUrl==undefined){
return "doctype:unknown";
}
// get the file type via file extension
var ext = docUrl.substr(docUrl.lastIndexOf(".")+1,docUrl.length);
if(ext.toLowerCase()==="pdf"){
return "doctype:pdf";
}else if(ext.toLowerCase()==="xls" || ext.toLowerCase()==="xlsx"){
return "doctype:excel";
}else if(ext.toLowerCase()==="ppt"){
return "doctype:ppt";
}else if(ext.toLowerCase()==="rtf"){
return "doctype:rtf";
}else if(ext.toLowerCase()==="txt"){
return "doctype:txt";
}else if(ext.toLowerCase()==="doc"){
return "doctype:word";
}else if(ext.toLowerCase()==="xml"){
return "doctype:xml";
}else if(ext.toLowerCase()==="zip"){
return "doctype:zip";
}else if(ext.toLowerCase()==="csv"){
return "doctype:csv";
}else{
return "doctype:unknown";
}
}
get displayListTable(){
this.displayList;
}
countLink(event){
// this.tskId = 'Value = ' + event.currentTarget.dataset.valu;
this.tskURL = event.currentTarget.dataset.value;
updateTask({recordForUpdate: this.recordId, strURL: this.tskURL})
.then(result => {
// Clear the user enter values
// Show success messsage
this.dispatchEvent(new ShowToastEvent({
title: 'Success!!',
message: 'Account Created Successfully!!',
variant: 'success'
}),);
})
.catch(error => {
this.error = error.message;
});
}
}
|
module.exports.ADD_TODO = 'ADD_TODO';
module.exports.DELETE_TODO = 'DELETE_TODO';
module.exports.EDIT_TODO = 'EDIT_TODO';
module.exports.COMPLETE_TODO = 'COMPLETE_TODO';
module.exports.COMPLETE_ALL = 'COMPLETE_ALL';
module.exports.CLEAR_COMPLETED = 'CLEAR_COMPLETED';
|
import React from 'react'
import Steps from 'rc-steps'
import 'rc-steps/assets/index.css'
const { Step } = Steps
export const RegisterSteps = ({props, currentStep, setCurrentStep}) => {
return (
<Steps type="navigation" current={currentStep}
onChange={current => {
if(current === 0) return props.history.push('/registration')
if(current === 1) return props.history.push('/registration/personal-details')
if(current === 2) return props.history.push('/registration/employment-details')
if(current === 3) return props.history.push('/registration/nip-bureau')
if(current === 4) return props.history.push('/registration/identity')
if(current === 5) return props.history.push('/registration-complete')
if(current === 6) return props.history.push('/registration/questionary')
// setCurrentStep(current)
}}>
<Step disabled={currentStep > 2} title='Registro'/>
<Step disabled={currentStep < 1 || currentStep > 2} title='Datos personales y Dirección'/>
<Step disabled={currentStep < 2 || currentStep > 2} title='Detalles de Empleo'/>
<Step disabled={true} title='Preguntas de Verificación'/>
<Step disabled={true} title='Revisión de Identidad'/>
<Step disabled={true} title='Finalizada'/>
</Steps>
)
}
|
$('.toggle').click(function(){
$('.formulario').animate({
height:"toggle",
'padding-top': 'toggle',
'padding-bottom':'toggle',
opacity: 'toggle'
}, "slow");
})
document.getElementById('formTask').addEventListener('submit', guardarUsuario);
function guardarUsuario(e){
let usuario = (document.getElementById('usuario').value);
let contraseña = (document.getElementById('contraseña').value);
let correo = (document.getElementById('correo').value);
let telefono = (document.getElementById('telefono').value);
const registro ={
usuario,
contraseña,
correo,
telefono
};
if (localStorage.getItem('registros') === null) {
let registros = [];
registros.push(registro);
localStorage.setItem('registros', JSON.stringify(registros));
}else{
window.location.assign('listaDeTareas.html')
}
e.preventDefault();
}
|
//var config = require('../src/config');
var path = require('path');
var yargs = require('yargs');
var argv = yargs.argv;
var srcPath = 'src';
module.exports = {
sprite : {
iconsPathSvg: srcPath + '/assets/private/icons/svg',
iconsPathPng: srcPath + '/assets/private/icons/png',
out: srcPath + '/assets/public/sprite/generated',
scssPath: '', // Relative path to the out path
cssSpritePath: '/assets/public/sprite/generated', // Relative path from the compiled css file to the sprite file
spritePath: 'sprite', // Relative path to the scss Path + the filename prefix
},
paths: {
src: srcPath,
dist: 'dist',
tmp: 'tmp',
root: '..'
}
}
|
/*global beforeEach, afterEach, expect*/
'use strict';
const sinon = require('sinon');
const path = require('path');
const _ = require('lodash');
const fs = require('fs');
const AliyunProvider = require('../provider/aliyunProvider');
const AliyunPackage = require('./aliyunPackage');
const Serverless = require('../test/serverless');
const { ramRoleStatements, functionDefs, directory } = require('../test/data');
describe('AliyunPackage', () => {
let serverless;
let options;
let aliyunPackage;
let consoleLogStub;
const servicePath = path.join(__dirname, '..', 'test', 'project');
beforeEach(() => {
serverless = new Serverless();
serverless.service.service = 'my-service';
serverless.service.functions = _.cloneDeep(functionDefs);
serverless.service.package = {
artifact: '/tmp/my-service.zip'
};
serverless.config = {
servicePath: servicePath
};
serverless.service.provider = {
name: 'aliyun',
credentials: path.join(__dirname, '..', 'test', 'credentials'),
runtime: 'nodejs6',
ramRoleStatements
};
options = {
stage: 'dev',
region: 'cn-shanghai',
};
serverless.setProvider('aliyun', new AliyunProvider(serverless, options));
serverless.pluginManager.setCliOptions(options);
aliyunPackage = new AliyunPackage(serverless, options);
consoleLogStub = sinon.stub(aliyunPackage.serverless.cli, 'log').returns();
sinon.stub(aliyunPackage.provider, 'getArtifactDirectoryName').returns(directory);
});
afterEach(() => {
aliyunPackage.serverless.cli.log.restore();
aliyunPackage.provider.getArtifactDirectoryName.restore();
});
xdescribe('#constructor()', () => {
it('should set the serverless instance', () => {
expect(aliyunPackage.serverless).toEqual(serverless);
});
it('should set options if provided', () => {
expect(aliyunPackage.options).toEqual(options);
});
it('should make the provider accessible', () => {
expect(aliyunPackage.provider).toBeInstanceOf(AliyunProvider);
});
describe('hooks', () => {
let cleanupServerlessDirStub;
let validateStub;
let setDefaultsStub;
let prepareDeploymentStub;
let saveCreateTemplateFileStub;
let compileFunctionsStub;
let mergeServiceResourcesStub;
let saveUpdateTemplateFileStub;
beforeEach(() => {
cleanupServerlessDirStub = sinon.stub(aliyunPackage, 'cleanupServerlessDir')
.returns();
validateStub = sinon.stub(aliyunPackage, 'validate')
.returns(Promise.resolve());
setDefaultsStub = sinon.stub(aliyunPackage, 'setDefaults')
.returns();
prepareDeploymentStub = sinon.stub(aliyunPackage, 'prepareDeployment')
.returns();
saveCreateTemplateFileStub = sinon.stub(aliyunPackage, 'saveCreateTemplateFile')
.returns();
compileFunctionsStub = sinon.stub(aliyunPackage, 'compileFunctions')
.returns(Promise.resolve());
mergeServiceResourcesStub = sinon.stub(aliyunPackage, 'mergeServiceResources')
.returns();
saveUpdateTemplateFileStub = sinon.stub(aliyunPackage, 'saveUpdateTemplateFile')
.returns();
});
afterEach(() => {
aliyunPackage.cleanupServerlessDir.restore();
aliyunPackage.validate.restore();
aliyunPackage.setDefaults.restore();
aliyunPackage.prepareDeployment.restore();
aliyunPackage.saveCreateTemplateFile.restore();
aliyunPackage.compileFunctions.restore();
aliyunPackage.mergeServiceResources.restore();
aliyunPackage.saveUpdateTemplateFile.restore();
});
it('should run "package:cleanup" promise chain', () => aliyunPackage
.hooks['package:cleanup']().then(() => {
expect(cleanupServerlessDirStub.calledOnce).toEqual(true);
}));
it('should run "before:package:initialize" promise chain', () => aliyunPackage
.hooks['before:package:initialize']().then(() => {
expect(validateStub.calledOnce).toEqual(true);
expect(setDefaultsStub.calledAfter(validateStub)).toEqual(true);
}));
it('should run "package:initialize" promise chain', () => aliyunPackage
.hooks['package:initialize']().then(() => {
expect(prepareDeploymentStub.calledOnce).toEqual(true);
expect(saveCreateTemplateFileStub.calledAfter(prepareDeploymentStub)).toEqual(true);
}));
it('should run "package:compileFunctions" promise chain', () => aliyunPackage
.hooks['package:compileFunctions']().then(() => {
expect(compileFunctionsStub.calledOnce).toEqual(true);
}));
it('should run "package:finalize" promise chain', () => aliyunPackage
.hooks['package:finalize']().then(() => {
expect(mergeServiceResourcesStub.calledOnce).toEqual(true);
expect(saveUpdateTemplateFileStub.calledAfter(mergeServiceResourcesStub)).toEqual(true);
}));
});
});
describe('#package()', () => {
beforeEach(() => {
aliyunPackage.serverless.utils.writeFileSync = (filename, data) => {
const dir = path.dirname(filename);
if (!fs.existsSync(dir)) { fs.mkdirSync(dir); }
fs.writeFileSync(filename, JSON.stringify(data, null, 2), 'utf8');
};
});
afterEach(() => {
aliyunPackage.serverless.utils.writeFileSync = () => {};
});
it('should output proper templates', () => {
const serverlessPath = path.join(servicePath, '.serverless');
return aliyunPackage.hooks['package:cleanup']()
.then(() => {
expect(fs.existsSync(serverlessPath)).toBe(false);
})
.then(() => aliyunPackage.hooks['before:package:initialize']())
.then(() => aliyunPackage.hooks['package:initialize']())
.then(() => {
expect(fs.existsSync(serverlessPath)).toBe(true);
})
.then(() => aliyunPackage.hooks['before:package:initialize']())
.then(() => aliyunPackage.hooks['package:compileFunctions']())
.then(() => aliyunPackage.hooks['package:finalize']())
.then(() => {
const files = fs.readdirSync(serverlessPath);
const createName = 'configuration-template-create.json';
const updateName = 'configuration-template-update.json';
expect(files).toContain(createName);
expect(files).toContain(updateName);
const createTmpl = JSON.parse(
fs.readFileSync(path.join(serverlessPath, createName), 'utf8')
);
const updateTmpl = JSON.parse(
fs.readFileSync(path.join(serverlessPath, updateName), 'utf8')
);
const testSlsPath = path.join(__dirname, '..', 'test', '.serverless');
const createExpected = JSON.parse(
fs.readFileSync(path.join(testSlsPath, createName), 'utf8')
);
const updateExpected = JSON.parse(
fs.readFileSync(path.join(testSlsPath, updateName), 'utf8')
);
updateExpected.Resources['sls-storage-object'].Properties.LocalPath = path.join(serverlessPath, 'my-service.zip');
expect(createTmpl).toEqual(createExpected);
expect(updateTmpl).toEqual(updateExpected);
const logs = [
'Compiling function "postTest"...',
'Compiling function "getTest"...',
'Compiling function "ossTriggerTest"...',
'Finished Packaging.'
];
for (var i = 0; i < consoleLogStub.callCount; ++i) {
expect(consoleLogStub.getCall(i).args[0]).toEqual(logs[i]);
}
});
});
});
});
|
import React, { Component } from 'react'
import Scroll from 'react-scroll'
import TypingMessage from './TypingMessage'
import QnA from './QnA'
import Conclusion from './Conclusion'
export default class Conversation extends Component {
constructor({ props }) {
super(props)
this.scrollToBottom = this.scrollToBottom.bind(this)
}
scrollToBottom() {
Scroll.animateScroll.scrollToBottom({
duration: 1500,
delay: 100,
smooth: "linear"
})
};
componentDidMount() {
}
componentDidUpdate() {
this.scrollToBottom()
}
render() {
// need to change 'this' to something else
// when mapping(loop) this prop is out of scope
let _that = this
return (
<div className='container'>
{
this.props.context.map((qna) => {
if (qna.choices[0].text === 'RedStop' || qna.choices[0].text === 'GreenStop') {
return <Conclusion key={qna.questionText}
text={qna.questionText}
url={qna.choices[0].url}
stop={qna.choices[0].text}/>
} else {
return (
<div key={qna.questionText}>
{<QnA qna={qna}
onChoiceClick={_that.props.onChoiceClick}
onMultipleChoiceClick={_that.props.onMultipleChoiceClick}
onMultipleChoiceSubmit={_that.props.onMultipleChoiceSubmit} />}
</div>
)
}
})
}
{this.props.isLoading ? <TypingMessage /> : null}
</div>
)
}
}
|
const {
getPostsByCategory, getSinglePost, getPostComments, getManyPosts,
} = require('utilities/operations').post;
const validators = require('controllers/validators');
exports.show = async (req, res, next) => {
const value = validators.validate({
author: req.params.author,
permlink: req.params.permlink,
}, validators.post.showSchema, next);
if (!value) {
return;
}
const { post, error } = await getSinglePost(value.author, value.permlink);
if (error) {
return next(error);
}
res.result = { status: 200, json: post };
next();
};
exports.getByCategory = async (req, res, next) => {
const value = validators.validate({
category: req.body.category,
limit: req.body.limit,
skip: req.body.skip,
user_languages: req.body.user_languages,
}, validators.post.getPostsByCategorySchema, next);
if (!value) {
return;
}
const { posts, error } = await getPostsByCategory(value);
if (error) {
return next(error);
}
res.result = { status: 200, json: posts };
next();
};
exports.getPostComments = async (req, res, next) => {
const value = validators.validate({ ...req.query }, validators.post.getPostComments, next);
if (!value) return;
const { result, error } = await getPostComments(value);
if (error) return next(error);
res.result = { status: 200, json: result };
next();
};
exports.getManyPosts = async (req, res, next) => {
const value = validators.validate(req.body, validators.post.getManyPosts, next);
if (!value) return;
const { posts, error } = await getManyPosts(value);
if (error) return next(error);
res.result = { status: 200, json: posts };
next();
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.