merge plus #167 error en el id al crear item task

This commit is contained in:
Carlos Jimenez 2018-03-13 14:46:39 +01:00
commit 0e8fe7fead
40 changed files with 248 additions and 136 deletions

2
Jenkinsfile vendored
View File

@ -8,6 +8,8 @@ env.BRANCH_NAME = branchName;
env.TAG = "${env.BUILD_NUMBER}";
env.salixUser="${env.salixUser}";
env.salixPassword="${env.salixPassword}";
env.salixHost = "${env.productionSalixHost}";
env.salixPort = "${env.productionSalixPort}";
switch (branchName){
case branchTest:

View File

@ -5,7 +5,7 @@
"validations" : true,
"routes": [
{
"url": "/clients",
"url": "/clients?q",
"state": "clients",
"component": "vn-client-index",
"acl": ["employee"]
@ -30,7 +30,7 @@
},
"menu": {
"description": "Basic data",
"icon": "person"
"icon": "settings"
}
},
{
@ -54,7 +54,7 @@
},
"menu": {
"description": "Pay method",
"icon": "assignment"
"icon": "icon-payment"
}
},
{
@ -94,7 +94,7 @@
},
"menu": {
"description": "Web access",
"icon": "language"
"icon": "cloud"
}
},
{
@ -186,7 +186,7 @@
"component": "vn-client-invoices",
"menu": {
"description": "Invoices",
"icon": "insert_drive_file"
"icon": "icon-invoices"
}
},
{
@ -204,7 +204,7 @@
},
"menu": {
"description": "Recovery",
"icon": "credit_card"
"icon": "icon-recovery"
}
}, {
"url": "/create",

View File

@ -59,9 +59,7 @@
field="observation.observationTypeFk"
data="observationsTypes.model"
show-field="description"
label="Observation type"
order="description ASC"
filter-search="{where: {description: {regexp: 'search'}}}">
label="Observation type">
<tpl-item>{{$parent.$parent.item.description}}</tpl-item>
</vn-autocomplete>
<vn-textfield

View File

@ -30,7 +30,7 @@
value-field="id"
select-fields="name"
label="Salesperson"
filter-search="{where: {or: [{name: {regexp: 'search'}}, {name: {regexp: 'search'}}]}}">
where="{or: [{firstName: {regexp: 'search'}}, {name: {regexp: 'search'}}]}">
</vn-autocomplete>
<vn-autocomplete vn-one
initial-data="$ctrl.client.contactChannel"

View File

@ -15,7 +15,7 @@
</vn-horizontal>
<vn-horizontal>
<vn-textfield vn-one label="Business name" field="$ctrl.client.socialName"></vn-textfield>
<vn-textfield vn-one label="User name" field="$ctrl.client.userName"></vn-textfield>
<vn-textfield vn-one label="Web user" field="$ctrl.client.userName"></vn-textfield>
</vn-horizontal>
<vn-horizontal>
<vn-textfield vn-one label="Email" field="$ctrl.client.email" info="You can save multiple emails"></vn-textfield>
@ -26,7 +26,7 @@
value-field="id"
select-fields="name"
label="Salesperson"
filter-search="{where: {or: [{name: {regexp: 'search'}}, {name: {regexp: 'search'}}]}}">
where="{or: [{firstName: {regexp: 'search'}}, {name: {regexp: 'search'}}]}">
</vn-autocomplete>
</vn-horizontal>
</vn-card>

View File

@ -1,7 +1,7 @@
Name: Nombre
Tax number: NIF/CIF
Business name: Razón social
User name: Nombre de usuario
Web user: Usuario Web
Email: Correo electrónico
Create and edit: Crear y editar
Create: Crear

View File

@ -25,6 +25,7 @@ class ClientDescriptor {
}
}
}
ClientDescriptor.$inject = ['$http'];
ngModule.component('vnClientDescriptor', {
template: require('./descriptor.html'),

View File

@ -1,4 +1,4 @@
<mg-ajax path="/client/api/Clients/filter" options="mgIndex"></mg-ajax>
<mg-ajax path="/client/api/Clients/filter" options="vnIndexNonAuto"></mg-ajax>
<div margin-medium>
<div class="vn-list">
<vn-card>

View File

@ -14,7 +14,7 @@
<vn-icon
ng-click="$ctrl.preview($event)"
vn-tooltip="Preview"
icon="icon-preview">
icon="desktop_windows">
</vn-icon>
</vn-horizontal>
</vn-horizontal>

View File

@ -312,7 +312,7 @@ export default class DropDown extends Component {
this.ul.appendChild(fragment);
this.activateOption(this._activeOption);
this.$.popover.relocate();
this.$.$applyAsync(() => this.$.popover.relocate());
}
destroyList() {

View File

@ -30,6 +30,8 @@ describe('Component vnDropDown', () => {
let popoverTemplate = require('../popover/popover.html');
let $popover = angular.element(`<div>${popoverTemplate}</div>`);
$scope.popover = $componentController('vnPopover', {$element: $popover, $scope, $timeout, $transitions});
$scope.popover.$postLink();
$scope.model = $componentController('vnModel', {$httpBackend, $q, $filter});
controller = $componentController('vnDropDown', {$element, $scope, $transclude: null, $timeout, $httpBackend, $translate: null});
controller.$postLink();

View File

@ -2,8 +2,6 @@ import './textfield/textfield';
import './watcher/watcher';
import './paging/paging';
import './icon/icon';
import './autocomplete/autocomplete';
import './popover/popover';
import './dialog/dialog';
import './confirm/confirm';
import './title/title';
@ -12,7 +10,10 @@ import './spinner/spinner';
import './snackbar/snackbar';
import './tooltip/tooltip';
import './icon-menu/icon-menu';
import './popover/popover';
import './autocomplete/autocomplete';
import './drop-down/drop-down';
import './menu/menu';
import './column-header/column-header';
import './grid-header/grid-header';
import './multi-check/multi-check';

View File

@ -0,0 +1,24 @@
import ngModule from '../../module';
import Popover from '../popover/popover';
export default class Menu extends Popover {
$postLink() {
super.$postLink();
this.element.addEventListener('click',
() => this.onClick());
}
onClick() {
this.hide();
}
}
ngModule.component('vnMenu', {
template: require('../popover/popover.html'),
controller: Menu,
transclude: true,
bindings: {
onOpen: '&?',
onClose: '&?'
}
});

View File

@ -11,6 +11,10 @@ export default class Popover extends Component {
this.$timeout = $timeout;
this.$transitions = $transitions;
this._shown = false;
}
$postLink() {
this.$element.addClass('vn-popover');
this.docKeyDownHandler = e => this.onDocKeyDown(e);
this.docFocusInHandler = e => this.onDocFocusIn(e);
@ -153,7 +157,6 @@ export default class Popover extends Component {
if (event.keyCode == 27) { // Esc
event.preventDefault();
this.hide();
this.$.$applyAsync();
}
}

View File

@ -1,4 +1,4 @@
vn-popover {
.vn-popover {
display: none;
z-index: 10;
position: fixed;

View File

@ -0,0 +1,6 @@
vn-textarea {
& > .mdl-textfield {
width: initial;
display: block;
}
}

View File

@ -1,5 +1,6 @@
import ngModule from '../../module';
import template from './textarea.html';
import './style.scss';
directive.$inject = ['vnTemplate'];
export function directive(vnTemplate) {

View File

@ -1,6 +1,18 @@
.icon-tags:before { content: '\e800'; }
.icon-tree:before { content: '\e801'; }
.icon-clone2:before { content: '\e802'; }
.icon-preview:before { content: '\e803'; }
.icon-history:before { content: '\f1da'; }
.icon-barcode:before { content: '\e800'; } /* '' */
.icon-volume:before { content: '\e801'; } /* '' */
.icon-bucket:before { content: '\e802'; } /* '' */
.icon-disabled:before { content: '\e80b'; } /* '' */
.icon-invoices:before { content: '\e80c'; } /* '' */
.icon-noweb:before { content: '\e812'; } /* '' */
.icon-payment:before { content: '\e813'; } /* '' */
.icon-recovery:before { content: '\e815'; } /* '' */
.icon-risk:before { content: '\e816'; } /* '' */
.icon-lines:before { content: '\e819'; } /* '' */
.icon-volum:before { content: '\e81b'; } /* '' */
.icon-components:before { content: '\e81c'; } /* '' */
.icon-clone:before { content: '\e81d'; } /* '' */
.icon-addperson:before { content: '\e81e'; } /* '' */
.icon-bin:before { content: '\e81f'; } /* '' */
.icon-sms:before { content: '\e820'; } /* '' */
.icon-tags:before { content: '\e821'; } /* '' */

View File

@ -11,7 +11,7 @@
"component": "ui-view"
},
{
"url": "/list",
"url": "/list?q",
"state": "item.index",
"component": "vn-item-list"
},
@ -35,7 +35,7 @@
},
"menu": {
"description": "Basic data",
"icon": "folder"
"icon": "settings"
},
"acl": ["buyer"]
},
@ -48,7 +48,7 @@
},
"menu": {
"description": "Tags",
"icon": "folder"
"icon": "icon-tags"
},
"acl": ["buyer"]
},
@ -70,7 +70,7 @@
},
"menu": {
"description": "History",
"icon": "folder"
"icon": "history"
}
},
{
@ -107,7 +107,7 @@
},
"menu": {
"description": "Barcode",
"icon": "folder"
"icon": "icon-barcode"
},
"acl": ["buyer","replenisher"]
},{

View File

@ -23,11 +23,9 @@
<vn-autocomplete vn-one
url="/item/api/Intrastats"
label="Intrastat"
show-field="description"
value-field="id"
field="$ctrl.item.intrastatFk"
order="description ASC"
filter-search="{where: {description: {regexp: 'search'}} }">
show-field="description"
field="$ctrl.item.intrastatFk">
</vn-autocomplete>
</vn-horizontal>
<vn-horizontal>

View File

@ -30,10 +30,9 @@
show-field="description"
value-field="id"
field="$ctrl.item.intrastatFk"
order="description ASC"
filter-search= "{where: {or: [{id: {regexp: 'search'}}, {description: {regexp: 'search'}}]}}"
where="{or: [{id: {regexp: 'search'}}, {description: {regexp: 'search'}}]}"
initial-data="$ctrl.item.intrastat">
<tpl-item>{{$parent.$parent.item.id}} : {{$parent.$parent.item.description}}</tpl-item>
<tpl-item>{{id}} : {{description}}</tpl-item>
</vn-autocomplete>
<vn-textfield vn-one label="Relevancy" field="$ctrl.item.relevancy" type="number"></vn-textfield>
</vn-horizontal>

View File

@ -20,12 +20,12 @@
<vn-icon
ng-click="$ctrl.clone($event)"
vn-tooltip="Clone"
icon="icon-clone2">
icon="icon-clone">
</vn-icon>
<vn-icon
ng-click="$ctrl.preview($event)"
vn-tooltip="Preview"
icon="icon-preview">
icon="desktop_windows">
</vn-icon>
</vn-horizontal>
</vn-horizontal>

View File

@ -1,4 +1,4 @@
<mg-ajax path="/item/api/Items/filter" options="mgIndex"></mg-ajax>
<mg-ajax path="/item/api/Items/filter" options="vnIndexNonAuto"></mg-ajax>
<div margin-medium>
<div class="vn-list">
<vn-card>

View File

@ -1,7 +1,7 @@
<vn-watcher
vn-id="watcher"
data="$ctrl.item"
form = "form">
form="form">
</vn-watcher>
<form name="form" ng-submit="$ctrl.submit()">
<vn-card pad-large>
@ -9,13 +9,12 @@
<vn-horizontal ng-repeat="itemNiche in $ctrl.niches track by $index">
<vn-autocomplete
vn-three
initial-data = "itemNiche.warehouse"
field = "itemNiche.warehouseFk"
data = "$ctrl.warehouses"
show-field = "name"
value-field = "id"
label = "Warehouse"
order = "name ASC"
data="$ctrl.warehouses"
show-field="name"
value-field="id"
initial-data="itemNiche.warehouse"
field="itemNiche.warehouseFk"
label="Warehouse"
vn-acl="buyer,replenisher">
</vn-autocomplete>
<vn-textfield
@ -39,7 +38,7 @@
margin-medium-left
orange
icon="add_circle"
ng-if = "itemNiche.showAddIcon"
ng-if="itemNiche.showAddIcon"
ng-click="$ctrl.addNiche()">
</vn-icon>
</vn-one>

View File

@ -14,7 +14,6 @@
data="tags.model"
show-field="name"
label="Tag"
order="name ASC"
vn-acl="buyer">
</vn-autocomplete>
<vn-textfield

View File

@ -9,22 +9,22 @@
vn-popover="apps-menu"
translate-attr="{title: 'Applications'}">
</vn-icon>
<vn-popover vn-id="apps-menu" ng-click="appsMenu.hide()">
<ul id="apps-menu" pad-small>
<vn-menu vn-id="apps-menu">
<ul pad-small>
<li ng-repeat="mod in ::$ctrl.modules" ui-sref="{{::mod.route.state}}">
<vn-icon icon="{{::mod.icon}}"></vn-icon>
<span translate>{{::mod.name}}</span>
</li>
</ul>
</vn-popover>
</vn-menu>
<vn-icon
id="lang"
icon="language"
vn-popover="langs-menu"
translate-attr="{title: 'Change language'}">
</vn-icon>
<vn-popover vn-id="langs-menu">
<ul id="langs-menu" pad-small>
<vn-menu vn-id="langs-menu">
<ul pad-small>
<li
ng-repeat="lang in ::$ctrl.langs"
name="{{::lang}}"
@ -32,7 +32,7 @@
<span>{{::lang}}</span>
</li>
</ul>
</vn-popover>
</vn-menu>
<vn-icon
id="logout"
icon="exit_to_app"

View File

@ -14,7 +14,7 @@ vn-main-menu {
color: #FF9300;
}
}
vn-popover ul {
.vn-popover ul {
list-style-type: none;
margin: 0;
color: white;
@ -25,7 +25,7 @@ vn-main-menu {
cursor: pointer;
padding: .8em;
border-radius: .1em;
min-width: 4em;
min-width: 8em;
& > vn-icon {
padding-right: .3em;

View File

@ -1,7 +1,7 @@
import ngModule from '../../module';
export default class Controller {
constructor($element, $scope, $document, $compile, vnPopover, $timeout) {
constructor($element, $scope, $document, $compile, vnPopover, $timeout, $state, $transitions) {
this.element = $element[0];
this.$scope = $scope;
this.$document = $document;
@ -9,46 +9,52 @@ export default class Controller {
this.vnPopover = vnPopover;
this.$timeout = $timeout;
this.stringSearch = '';
this.$state = $state;
this.deregisterCallback = $transitions.onStart({},
transition => this.changeState(transition));
}
clearFilter() {
this.index.filter = {
page: 1,
size: 20
};
}
/**
* String search to JSON filter
*/
getFiltersFromSearch() {
let toFind = this.stringSearch;
let find;
if (this.stringSearch) {
setFilter(filterObject) {
this.clearFilter();
Object.assign(this.index.filter, filterObject);
}
getFiltersFromString(stringSearch) {
let result = {};
if (stringSearch) {
// find pattern key:value or key:(extra value) and returns array
find = toFind.match(/((([\w_]+):([\w_]+))|([\w_]+):\(([\w_ ]+)\))/gi);
// remove pattern key:value or key:(extra value) from string and returns string
this.index.filter.search = (toFind.replace(/((([\w_]+):([\w_]+))|([\w_]+):\(([\w_ ]+)\))/gi, '')).trim();
if (find)
for (let i = 0; i < find.length; i++) {
let aux = find[i].split(':');
let findPattern = stringSearch.match(/((([\w_]+):([\w_]+))|([\w_]+):\(([\w_ ]+)\))/gi);
let remnantString = (stringSearch.replace(/((([\w_]+):([\w_]+))|([\w_]+):\(([\w_ ]+)\))/gi, '')).trim();
if (findPattern) {
for (let i = 0; i < findPattern.length; i++) {
let aux = findPattern[i].split(':');
let property = aux[0];
let value = aux[1].replace(/\(|\)/g, '');
this.index.filter[property] = value.trim();
result[property] = value.trim();
}
}
if (remnantString) {
result.search = remnantString;
}
}
return result;
}
/**
* JSON filter to string search
*
* @param {Object} filter The filter
*/
createFilterSearch(filter) {
createStringFromObject(filterObject) {
let search = [];
let keys = Object.keys(filter);
let keys = Object.keys(filterObject);
if (keys.length) {
keys.forEach(k => {
let ignore = (this.ignoreKeys && this.ignoreKeys instanceof Array && this.ignoreKeys.indexOf(k) !== -1);
if (!ignore) {
let value = filter[k];
let value = filterObject[k];
if (typeof value === 'string' && value.indexOf(' ') !== -1) {
search.push(`${k}:(${value})`);
@ -57,42 +63,59 @@ export default class Controller {
}
}
});
if (filterObject.search)
search.unshift(filterObject.search);
}
if (this.index.filter.search) {
search.push(this.index.filter.search);
}
delete this.index.filter.search;
this.stringSearch = (search.length) ? search.join(' ') : '';
return (search.length) ? search.join(' ') : '';
}
changeState(transition) {
return !(transition._targetState._identifier.name === this.$state.current.name);
}
pushFiltersToState(filters) {
let history = window.history || {pushState: () => {
console.error('Error in history.pushState(): Browser incompatibility error');
}};
let aux = window.location.hash.split('?q=');
if (Object.keys(filters).length)
history.pushState({}, null, `${aux[0]}?q=${encodeURIComponent(JSON.stringify(filters))}`);
else
history.pushState({}, null, aux[0]);
}
onpenFilters(event) {
let filter = {};
if (this.stringSearch) {
this.getFiltersFromSearch();
filter = this.getFiltersFromString(this.stringSearch);
}
this.child = this.vnPopover.showComponent(this.popover, this.$scope, this.element);
// XXX: ¿Existe una forma más adecuada de acceder al controlador de un componente?
var childCtrl = angular.element(this.child).isolateScope().$ctrl;
childCtrl.filter = Object.assign({}, this.index.filter);
childCtrl.filter = Object.assign({}, filter);
childCtrl.onSubmit = filter => this.onChildSubmit(filter);
if (this.data)
childCtrl.data = Object.assign({}, this.data);
event.preventDefault();
}
onChildSubmit(filter) {
this.createFilterSearch(filter);
this.index.filter = {
page: 1,
size: 20
};
this.stringSearch = this.createStringFromObject(filter);
this.clearFilter();
this.$timeout(() => {
this.onSubmit();
});
}
onSubmit() {
let filter = {};
if (this.stringSearch) {
this.getFiltersFromSearch();
filter = this.getFiltersFromString(this.stringSearch);
}
this.setFilter(filter);
if (this.onSearch)
this.onSearch();
@ -103,12 +126,25 @@ export default class Controller {
angular.element(this.child).remove();
}
delete this.child;
this.pushFiltersToState(filter);
}
$onDestroy() {
this.clearFilter();
this.deregisterCallback();
}
$onInit() {
if (this.$state.params.q) {
let filter = JSON.parse(decodeURIComponent(this.$state.params.q));
this.stringSearch = this.createStringFromObject(filter);
}
this.$timeout(() => {
this.onSubmit();
});
}
}
Controller.$inject = ['$element', '$scope', '$document', '$compile', 'vnPopover', '$timeout'];
Controller.$inject = ['$element', '$scope', '$document', '$compile', 'vnPopover', '$timeout', '$state', '$transitions'];
ngModule.component('vnSearchbar', {
template: require('./searchbar.html'),

View File

@ -23,7 +23,7 @@ Nightmare.action('changeLanguageToEnglish', function(done) {
this.then(done);
} else {
this.click('#lang')
.click('#langs-menu > li[name="en"]')
.click('vn-main-menu [vn-id="langs-menu"] ul > li[name="en"]')
.then(done);
}
});

View File

@ -150,8 +150,8 @@ export default {
itemsIndex: {
createItemButton: `${components.vnFloatButton}`,
searchResult: `vn-item-product a`,
searchResultPreviewButton: `vn-item-product .buttons > [icon="icon-preview"]`,
searchResultCloneButton: `vn-item-product .buttons > [icon="icon-clone2"]`,
searchResultPreviewButton: `vn-item-product .buttons > [icon="desktop_windows"]`,
searchResultCloneButton: `vn-item-product .buttons > [icon="icon-clone"]`,
acceptClonationAlertButton: `vn-item-list [vn-id="clone"] [response="ACCEPT"]`,
searchItemInput: `${components.vnTextfield}`,
searchButton: `${components.vnSearchBar} > vn-icon-button > button`,

View File

@ -161,8 +161,12 @@ gulp.task('docker-compose', async () => {
// dockerFile = 'Dockerfile';
composeYml.services[service.name] = {
environment: ['NODE_ENV=${NODE_ENV}' ,'salixHost=${salixHost}', 'salixPort=${salixPort}',
'salixUser=${salixUser}', 'salixPassword=${salixPassword}'
environment: [
'NODE_ENV=${NODE_ENV}',
'salixHost=${salixHost}',
'salixPort=${salixPort}',
'salixUser=${salixUser}',
'salixPassword=${salixPassword}'
],
container_name: `\${BRANCH_NAME}-${service.name}`,
image: `${service.name}:\${TAG}`,

View File

@ -21,7 +21,7 @@ module.exports = Self => {
}
});
Self.clone = async (itemId, callback) => {
Self.clone = async itemId => {
let filter = {
where: {
id: itemId
@ -30,6 +30,7 @@ module.exports = Self => {
{relation: "itemTag", scope: {order: "priority ASC", include: {relation: "tag"}}}
]
};
try {
let origin = await Self.findOne(filter);
let copy = JSON.parse(JSON.stringify(origin));

View File

@ -2,7 +2,7 @@ module.exports = Self => {
Self.installMethod('filter', filterParams);
function filterParams(params) {
let filter = {
let filters = {
where: {},
skip: (params.page - 1) * params.size,
limit: params.size,
@ -20,7 +20,7 @@ module.exports = Self => {
delete params.order;
if (params.search) {
filter.where.and = [
filters.where.and = [
{
or: [
{id: params.search},
@ -36,21 +36,18 @@ module.exports = Self => {
delete params.itemSize;
}
let keys = Object.keys(params);
if (keys.length) {
keys.forEach(
key => {
if (filter.where.and) {
let filter = {};
filter[key] = (key === 'description') ? {regexp: params[key]} : params[key];
filter.where.and.push(filter);
} else {
filter.where[key] = (key === 'description') ? {regexp: params[key]} : params[key];
}
Object.keys(params).forEach(
key => {
if (filters.where.and) {
let filter = {};
filter[key] = (key === 'description' || key === 'name') ? {regexp: params[key]} : params[key];
filters.where.and.push(filter);
} else {
filters.where[key] = (key === 'description' || key === 'name') ? {regexp: params[key]} : params[key];
}
);
}
}
);
return filter;
return filters;
}
};

View File

@ -1,3 +1,5 @@
let UserError = require('../../../loopback/common/helpers').UserError;
module.exports = function(Self) {
require('../methods/item/filter.js')(Self);
require('../methods/item/clone.js')(Self);
@ -5,4 +7,24 @@ module.exports = function(Self) {
Self.validatesPresenceOf('name', {message: 'Cannot be blank'});
Self.validatesPresenceOf('originFk', {message: 'Cannot be blank'});
Self.observe('before save', async function(ctx) {
await Self.availableId(ctx);
});
Self.availableId = async function(ctx) {
if (ctx.isNewInstance) {
try {
let query = `SELECT i1.id + 1 as id FROM vn.item i1
LEFT JOIN vn.item i2 ON i1.id + 1 = i2.id
WHERE i2.id IS NULL ORDER BY i1.id LIMIT 1`;
let newId = await Self.rawSql(query);
ctx.instance.id = newId[0].id;
} catch (e) {
throw new UserError(e);
}
}
};
};

View File

@ -0,0 +1,11 @@
const app = require('../../../../item/server/server');
let ctx = {isNewInstance: true, instance: {}};
describe('Item availableId()', () => {
it('should define ctx.instance.id with the expected id', async() => {
let Item = app.models.Item;
await Item.availableId(ctx);
expect(ctx.instance.id).toEqual(6);
});
});

View File

@ -25,12 +25,6 @@ module.exports = function(Self) {
Self.validatesUniquenessOf('socialName', {
message: 'La razón social debe ser única'
});
Self.validatesFormatOf('postcode', {
message: 'El código postal solo debe contener números',
allowNull: true,
allowBlank: true,
with: /^\d+$/
});
Self.validatesFormatOf('email', {
message: 'Correo electrónico inválido',
allowNull: true,

View File

@ -1,39 +1,39 @@
const validateDni = require('../validateDni');
describe('DNI validation', () => {
it('should return false for invented DNI', () => {
it('should return true for any DNI when no country is passed', () => {
let isValid = validateDni('Pepinillos');
expect(isValid).toBeFalsy();
expect(isValid).toBeTruthy();
});
describe('Spanish', () => {
it('should return true for valid spanish DNI', () => {
let isValid = validateDni('20849756A');
let isValid = validateDni('20849756A', 'es');
expect(isValid).toBeTruthy();
});
it('should return false for spanish DNI with exceeded digits', () => {
let isValid = validateDni('208497563239A');
let isValid = validateDni('208497563239A', 'es');
expect(isValid).toBeFalsy();
});
it('should return false for spanish DNI with invalid letter', () => {
let isValid = validateDni('20243746E');
let isValid = validateDni('20243746E', 'es');
expect(isValid).toBeFalsy();
});
it('should return true for valid spanish CIF', () => {
let isValid = validateDni('B97367486');
let isValid = validateDni('B97367486', 'es');
expect(isValid).toBeTruthy();
});
it('should return false for spanish CIF with invalid letter', () => {
let isValid = validateDni('A97527786');
let isValid = validateDni('A97527786', 'es');
expect(isValid).toBeFalsy();
});

View File

@ -1,9 +1,11 @@
module.exports = function(fi, country) {
if (fi == null) return true;
if (typeof fi != 'string') return false;
if (fi == null || country == null)
return true;
if (typeof fi != 'string' || typeof country != 'string')
return false;
fi = fi.toUpperCase();
country = country ? country.toLowerCase() : 'es';
country = country.toLowerCase();
let len = fi.length;

View File

@ -4,7 +4,7 @@ module.exports = function(iban) {
iban = iban.toUpperCase();
iban = trim(iban);
iban = iban.replace(/\s/g, "");
iban = iban.replace(/\s/g, '');
if (iban.length != 24) {
return false;
@ -33,7 +33,7 @@ module.exports = function(iban) {
function module97(iban) {
var parts = Math.ceil(iban.length / 7);
var remainer = "";
var remainer = '';
for (var i = 1; i <= parts; i++) {
remainer = String(parseFloat(remainer + iban.substr((i - 1) * 7, 7)) % 97);
@ -48,6 +48,6 @@ module.exports = function(iban) {
}
function trim(text) {
return (text || "").replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" );
return (text || '').replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, '');
}
};