All files / middlewares storageAddressValidations.js

100% Statements 96/96
100% Branches 99/99
100% Functions 15/15
100% Lines 96/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392                      7x   7x 2x           5x                 5x 2x               3x 3x           2x         2x 1x         3x 3x   3x 1x           2x         2x 1x                 3x 3x   3x 1x           2x         2x 1x                 2x   2x 1x               2x   2x 1x               3x   3x 2x             2x 1x         1x         2x   2x 1x                                 12x 12x       12x 1x       11x 1x       10x 1x       9x 1x       8x 1x       7x 1x           6x 1x           5x 1x           4x 1x           3x 1x           2x 1x                   3x   3x 1x               5x 5x 1x         4x             4x 1x                 3x   3x 2x                                 4x 4x   4x       4x 2x       2x 1x                   3x   3x     3x 2x               4x   4x 3x       3x                   3x 2x 2x     2x 1x                                                              
import APIError from '../helpers/error';
import { t } from '../helpers/i18n';
import StorageAddressInformation from '../source/storageAddresses/information';
import BranchInformation from '../source/branches/information';
import StorageAddressTypeInformation from '../source/storageAddressTypes/information';
import StockInformation from '../source/stock/information';
import RangesInformation from '../source/ranges/information';
import PickingAreaInformation from '../source/pickingAreas/information';
 
async function validStorageAddressId(req) {
  const storageAddressId =
    req.body.storageAddressId || req.query.storageAddressId;
 
  if (!storageAddressId) {
    throw new APIError(
      t('BEE1244' /* ID não pode ser vazio */),
      'INVALID_STORAGE_ADDRESS_ID'
    );
  } else {
    const existStorageAddress =
      await StorageAddressInformation.getStorageAddress(
        {
          id: storageAddressId,
        },
        {
          userBranches: req.userBranches,
        }
      );
 
    if (!existStorageAddress) {
      throw new APIError(
        t(
          'BEE1243',
          { 0: storageAddressId } /* Tipo endereço %{0} não localizada */
        ),
        'NOT_EXIST_STORAGE_ADDRESS_ID'
      );
    } else {
      req.addressCode = existStorageAddress.code;
      req.addressBranchCode = existStorageAddress.branchCode;
    }
  }
}
 
async function unusedAddress(req) {
  const stockBalance = await StockInformation.getBalanceAvailable({
    branchCode: req.addressBranchCode,
    addressCode: req.addressCode,
  });
 
  if (stockBalance) {
    throw new APIError('', t('BEE2383' /* Endereço associada a um estoque */));
  }
}
 
async function validCode(req) {
  const code = req.body.code || req.query.code;
  const branchCode = req.body.branchCode || req.query.branchCode;
 
  if (!code) {
    throw new APIError(
      t('BEE1245' /* Código não pode ser vazio */),
      'INVALID_STORAGE_ADDRESS_CODE'
    );
  } else {
    const existStorageAddress =
      await StorageAddressInformation.getStorageAddress({
        code,
        branchCode,
      });
 
    if (existStorageAddress) {
      throw new APIError(
        t('BEE1173', { 0: code } /* Codigo %{0} já cadastrado  */),
        'EXIST_STORAGE_ADDRESS_CODE'
      );
    }
  }
}
 
async function validExistingCode(req) {
  const code = req.body.code || req.query.code;
  const branchCode = req.body.branchCode || req.query.branchCode;
 
  if (!code) {
    throw new APIError(
      t('BEE1245' /* Código não pode ser vazio */),
      'INVALID_STORAGE_ADDRESS_CODE'
    );
  } else {
    const existStorageAddress =
      await StorageAddressInformation.getStorageAddress({
        code,
        branchCode,
      });
 
    if (!existStorageAddress) {
      throw new APIError(
        t('BEE1192', { 0: code } /* Código %{0} não cadastrado */),
        'NOT_EXIST_STORAGE_ADDRESS_CODE'
      );
    }
  }
}
 
function validStorageAddressName(req) {
  const name = req.body.name || req.query.name;
 
  if (!name) {
    throw new APIError(
      t('BEE1234' /* Nome não pode ser vazio ! */),
      'INVALID_STORAGE_ADDRESS_NAME'
    );
  }
}
 
async function validSize(req) {
  const { size } = req.body;
 
  if (!size) {
    throw new APIError(
      t('BEE2971' /* Classificação é obrigatória */),
      'INVALID_STORAGE_ADDRESS_SIZE'
    );
  }
}
 
async function validBranch(req) {
  const branch = req.body.branchCode || req.query.branchCode;
 
  if (branch) {
    const existBranch = await BranchInformation.getBranch(
      {
        code: branch,
      },
      { userBranches: req.userBranches }
    );
 
    if (!existBranch)
      throw new APIError(
        '',
        t('BEE1160', { 0: branch } /* Filial %{0} inválida ! */)
      );
  } else {
    throw new APIError('', t('BEE1246' /* Filial não definida ! */));
  }
}
 
async function validType(req) {
  const type = req.body.type || req.query.type;
 
  if (!type) {
    throw new APIError('', t('BEE1659' /* Tipos de endereço não definida ! */));
  }
}
 
async function validateGenerators(req) {
  const {
    sector,
    sectorTo,
    street,
    streetTo,
    level,
    levelTo,
    column,
    columnTo,
    drawer,
    drawerTo,
    rangeCode,
  } = req.body || req.query;
  const lessThan = t(
    'BEE1284' /* campo inicial não pode ser maior que campo final ! */
  );
 
  if (!sectorTo) {
    throw new APIError(
      t('BEE1279' /* Setor até, campo obrigatório ! */),
      'INVALID_STORAGE_ADDRESS_SECTOR'
    );
  } else if (!streetTo) {
    throw new APIError(
      t('BEE1280' /* Rua até, campo obrigatório ! */),
      'INVALID_STORAGE_ADDRESS_STREET'
    );
  } else if (!columnTo) {
    throw new APIError(
      t('BEE1281' /* Coluna até, campo obrigatório ! */),
      'INVALID_STORAGE_ADDRESS_COLUMN'
    );
  } else if (!levelTo) {
    throw new APIError(
      t('BEE1282' /* Nível até, campo obrigatório ! */),
      'INVALID_STORAGE_ADDRESS_LEVEL'
    );
  } else if (!drawerTo) {
    throw new APIError(
      t('BEE1283' /* Gaveta até, campo obrigatório ! */),
      'INVALID_STORAGE_ADDRESS_DRAWER'
    );
  } else if (!rangeCode) {
    throw new APIError(
      t('BEE2522' /* Range não informado */),
      'INVALID_STORAGE_ADDRESS_RANGE'
    );
  }
 
  if (parseInt(sector, 10) > parseInt(sectorTo, 10)) {
    throw new APIError(
      `${t('BEE279' /* Setor */)}, ${lessThan} || ${
        parseInt(sector, 10) > parseInt(sectorTo, 10)
      }`,
      'INVALID_STORAGE_ADDRESS_SECTOR'
    );
  } else if (parseInt(street, 10) > parseInt(streetTo, 10)) {
    throw new APIError(
      `${t('BEE121' /* Rua */)}, ${lessThan} || ${
        parseInt(street, 10) > parseInt(streetTo, 10)
      }`,
      'INVALID_STORAGE_ADDRESS_STREET'
    );
  } else if (parseInt(column, 10) > parseInt(columnTo, 10)) {
    throw new APIError(
      `${t('BEE281' /* Coluna */)}, ${lessThan} || ${
        parseInt(column, 10) > parseInt(columnTo, 10)
      }`,
      'INVALID_STORAGE_ADDRESS_COLUMN'
    );
  } else if (parseInt(level, 10) > parseInt(levelTo, 10)) {
    throw new APIError(
      `${t('BEE283' /* Nível */)}, ${lessThan} || ${
        parseInt(level, 10) > parseInt(levelTo, 10)
      }`,
      'INVALID_STORAGE_ADDRESS_LEVEL'
    );
  } else if (parseInt(drawer, 10) > parseInt(drawerTo, 10)) {
    throw new APIError(
      `${t('BEE285' /* Gaveta */)}, ${lessThan} || ${
        parseInt(drawer, 10) > parseInt(drawerTo, 10)
      }`,
      'INVALID_STORAGE_ADDRESS_DRAWER'
    );
  }
}
 
function validateGenerateList(req) {
  const addressesList = req.body || req.query;
 
  if (!addressesList.length) {
    throw new APIError(
      t('BEE1247' /* Lista vazia ! */),
      'INVALID_STORAGE_ADDRESS_LIST'
    );
  }
}
 
async function validBlockUpdate(req) {
  const { addressId, blocked } = req.body;
  if (!addressId) {
    throw new APIError(
      t('BEE1244' /* ID não pode ser vazio */),
      'INVALID_STORAGE_ADDRESS_ID'
    );
  } else {
    const storageAddress = await StorageAddressInformation.getStorageAddress(
      {
        id: addressId,
      },
      { userBranches: req.userBranches }
    );
 
    if (!storageAddress) {
      throw new APIError(
        t(
          'BEE1248',
          { 0: addressId } /* O endereço com id %{0} não foi encontrado */
        ),
        'INVALID_STORAGE_ADDRESS_ID'
      );
    }
 
    const isBlocked = !!storageAddress.blocked;
 
    if (isBlocked === blocked) {
      throw new APIError(
        t(
          'BEE1277',
          {
            0: storageAddress.code,
            1: isBlocked
              ? t('BEE207' /* Bloqueado */)
              : t('BEE1278' /* Desbloqueado */),
          } /* O endereço %{0} já está %{1} */
        ),
        'BLOCKED_VALUE_HAS_NOT_CHANGED'
      );
    }
  }
}
 
async function validStorageAddressType(req) {
  const { type } = req.body || req.query;
  const { code } = req.body || req.query;
 
  const existType = await StorageAddressTypeInformation.getStorageAddressType({
    id: type,
  });
 
  if (!existType) {
    throw new APIError(
      t('BEE1249' /* Tipo de endereço inválido ! */),
      'INVALID_STORAGE_ADDRESS_TYPE'
    );
  } else if (existType.status === 8 && !!code && code.length > 10) {
    throw new APIError(
      t(
        'BEE3497' /* O endereço do tipo Stage não pode ter um código maior que 10 caracteres! */,
        'INVALID_STORAGE_ADDRESS_TYPE'
      )
    );
  }
}
 
async function validStorageAddressRange(req) {
  const { rangeCode } = req.body || req.query;
 
  const existRange = await RangesInformation.getRange({
    code: rangeCode,
  });
  if (!existRange) {
    throw new APIError(
      t('BEE2513' /* Range não encontrado */),
      'INVALID_STORAGE_ADDRESS_RANGE'
    );
  }
}
 
async function validStorageAddressPickingArea(req) {
  const { pickingAreaId, storageAddressId } = req.body;
 
  if (pickingAreaId && storageAddressId) {
    const pickingArea = await PickingAreaInformation.getPickingArea({
      id: pickingAreaId,
    });
 
    const address = await StorageAddressInformation.getAddressWithStockBalance(
      {
        id: storageAddressId,
        branchCode: pickingArea.branchCode,
      },
      {
        userBranches: req.userBranches,
      }
    );
 
    if (address) {
      const stockOtherProduct = address.balances.filter(
        (item) => item.productCode !== pickingArea.productCode
      );
 
      if (stockOtherProduct.length > 0) {
        throw new APIError(
          t(
            'BEE3297',
            {
              0: address.storageAddressCode,
              1: stockOtherProduct[0].productCode,
            } /* O endereço %{0} possui saldo de outro produto (%{1}). */
          ),
          'INVALID_STORAGE_ADDRESS_PICKING_AREA'
        );
      }
    }
  }
}
 
export default {
  validStorageAddressId,
  validCode,
  validStorageAddressName,
  validBranch,
  validType,
  validateGenerators,
  validateGenerateList,
  validExistingCode,
  validBlockUpdate,
  validStorageAddressType,
  unusedAddress,
  validStorageAddressRange,
  validSize,
  validStorageAddressPickingArea,
};