Guest User

Untitled

a guest
Nov 19th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.72 KB | None | 0 0
  1. import {
  2. deburr,
  3. isEmpty,
  4. findIndex,
  5. drop,
  6. pad,
  7. padEnd,
  8. padStart
  9. } from 'lodash';
  10. import moment from 'moment';
  11. // import * as moment from 'moment';
  12. import 'moment/locale/pt-br';
  13. // moment.locale('pt-BR');
  14. import VMasker from '@/dg-lib/vendor/vanilla-masker';
  15. import numeral from 'numeral'
  16. import { mascaraMoeda, formatPhone, formatCnpjCpf } from '../masks/'
  17. import { loadStorage } from '@/helpers/storage/localStorage'
  18.  
  19. /*
  20. * Sanitize Data
  21. */
  22. export const sanitize = deburr;
  23. export const sanitizeText = value => sanitize(value);
  24. export const padText = (text, size = 48) => pad(text, size);
  25. export const padEndText = (text, size = 48) => padEnd(text, size);
  26. export const padStarText = (text, size = 48) => padStart(text, size);
  27. export const sanitizeAndLower = value => sanitize(value).toLowerCase();
  28. export const contains = (st, value) => sanitizeAndLower(st).indexOf(sanitizeAndLower(value)) > -1;
  29. export const sanitizeId = id => id.replace(/\[|\]/g, "");
  30. export const stringToMoneyFloat = str => (str)? parseFloat(mascaraMoeda(str,'','.')).toFixed(2) : null;
  31. export const stringToFloat = str => parseFloat(str).toFixed(2);
  32. export const FloatToMaskMoney = flt => (isNegative(flt))? `-${VMasker.toMoney(flt)}` : VMasker.toMoney(flt);
  33. export const SumMoney = (str1, str2) => (parseFloat(str1).toFixed(2) * 1) + (parseFloat(str2).toFixed(2) * 1)
  34. export const StringToCpfCnpj = str => formatCnpjCpf(str, { cpf: '999.999.999-99', cnpj: '99.999.999/9999-99' })
  35. export const convertNegativeToPositive = value => value.replace(/[-]/g, "")
  36. export const sanitizeSpecialCharacters = value => value.replace(/[&\/\\#,$~%.;˜`ˆ+()!@='"`_:*?<>{}]/g, "")
  37. export const sanitizeFloatPoint = value => value.replace(/([aA-zZ&\/\\#,$~%;˜`ˆ+()!@='"`_:*?<>{}])/g, "")
  38. export const convertToEdit = value => JSON.parse( JSON.stringify( value ) )
  39. export const sanitizeToFloatString = (value) => (value.indexOf(",")!= -1) ? value.replace(",", ".") : '0.00'
  40. export const percentage = (num, total) => parseInt(parseInt(num)*100/parseInt(total))
  41. export const isNegative = str => {
  42. const negative = /[-]/g
  43. return negative.test(str)
  44. }
  45.  
  46. export function arrCopy(arr, offset) {
  47. offset = offset || 0;
  48. const len = Math.max(0, arr.length - offset);
  49. const newArr = new Array(len);
  50. for (let ii = 0; ii < len; ii++) {
  51. newArr[ii] = arr[ii + offset];
  52. }
  53. return newArr;
  54. }
  55.  
  56. export function parseBoolean(str){
  57. const falsy = /^(?:f(?:alse)?|no?|0+)$/i;
  58. return !falsy.test(str) && !!str
  59. }
  60.  
  61. export const transformObjFromReportData = (obj, key) => {
  62. const reportModel = { key, params: [] }
  63. for(let key in obj) {
  64. reportModel.params.push({
  65. name: key,
  66. value: obj[key]
  67. })
  68. }
  69. return reportModel
  70. }
  71.  
  72. export const toCapitalize = (str) => {
  73. return str
  74. .toLowerCase()
  75. .split(" ")
  76. .map(item => item[0].toUpperCase() + item.substring(1))
  77. .join(' ')
  78. }
  79.  
  80. /*
  81. * Array Data
  82. */
  83. export const findIndexFromArray = (arrayObj, obj, attr) => findIndex(arrayObj, (o) => { return o[attr] == obj[attr] });
  84. export const findObjFromArray = (arrayObj, idCompare, attr = 'id') => arrayObj.filter((item) => (item[attr] === idCompare) ? item : false)[0]
  85. export const deleteObjFromArray = (arrayObj, obj, attr) => arrayObj.filter(item => item[attr] !== obj[attr]);
  86. export const deleteObjFromArrayById = (arrayObj, obj) => deleteObjFromArray(arrayObj, obj, 'id');
  87. export const insertObjArray = (arrayObj, obj, attr = 'id') => [ ...deleteObjFromArray(arrayObj, obj, attr), obj ];
  88. export const dropArray = (arrayObj, qtd) => drop(arrayObj, qtd);
  89. export const createArrayByBool = (arrayReturn, value, bool) => (bool)? arrayReturn.concat(value) : arrayReturn.filter(item => item !== value)
  90. export const createUniqueArray = arr => [...new Set(arr)];
  91. export const operationValueFromArray = (type, ref = 'value' ) => {
  92. function sumArray (arrayObj){
  93. return arrayObj
  94. .map(item => item[ref])
  95. .reduce((result, item) => SumMoney(result, item).toFixed(2), 0)
  96. }
  97.  
  98. switch(type){
  99. case 'sum':
  100. return sumArray
  101. }
  102. }
  103. export function cloneDeep(value) {
  104. // verifica se for um array e cria a partir desse array
  105. if (Array.isArray(value)) {
  106. return value.map(function (item) { return cloneDeep(item); });
  107. }
  108. // se for um objeto cria outro a partir do primeiro a ser clonado
  109. if (value !== null && typeof value === 'object') {
  110. var nextValue = {};
  111. for (var key in value) {
  112. if (value.hasOwnProperty(key)) {
  113. nextValue[key] = cloneDeep(value[key]);
  114. }
  115. }
  116. return nextValue;
  117. }
  118. // caso não seja nenhum do dois ele ja é um objeto mutavel é so retornar ele mesmo
  119. return value;
  120. }
  121.  
  122. /*
  123. * Date Hour format
  124. */
  125. export const isDateValid = (date) => moment(date, 'DD/MM/YYYY').isValid();
  126. export const dateToTimestamp = (date) => {
  127. if(!isDateValid(date)){ return false; }
  128. if(typeof date === 'object') {
  129. return parseInt(moment(new Date(date)).format('x'));
  130. }
  131. const arrayDate = date.split('/');
  132. const resultDate = moment({ y: parseInt(arrayDate[2]), M: parseInt(arrayDate[1] -1), d: parseInt(arrayDate[0]) }).format('x');
  133. return parseInt(resultDate);
  134. };
  135. export const getBirthdayToTimeStamp = (stamp) => moment().diff(new Date(stamp), 'years', false)
  136. export const timestampToDate = (stamp, format='DD/MM/YYYY') => {
  137. return moment(new Date(stamp), format, 'pt-BR').format(format);
  138. };
  139. export const timestampToDateHour = (stamp) => {
  140. return moment(new Date(stamp), 'DD/MM/YYYY', 'pt-BR').format('DD/MM/YYYY, H:mm:ss');
  141. };
  142. export const timestampToSimpleDateHour = (stamp) => {
  143. return moment(new Date(stamp), 'DD/MM', 'pt-BR').format('DD/MM HH:mm');
  144. };
  145. export const timestampToHour = (stamp, format='H:mm:ss') => {
  146. return moment(new Date(stamp), 'DD/MM/YYYY', 'pt-BR').format(format);
  147. };
  148. export const getDate = (date ,format= 'DD/MM/YYYY') => moment(date, 'DD/MM/YYYY', 'pt-BR').format(format);
  149. export const getTodayDate = (format= 'DD/MM/YYYY') => moment(new Date(), 'DD/MM/YYYY', 'pt-BR').format(format);
  150. export const getMonthRef = (date = new Date(), format= 'MM/YYYY') => moment(date, 'DD/MM/YYYY', 'pt-BR').format(format);
  151. export const getDaysInMonth = (date = new Date()) => moment(date, 'DD/MM/YYYY', 'pt-BR').daysInMonth()
  152. export const addDayInDate = (date, days=1) => moment(date, 'DD/MM/YYYY', 'pt-BR').add(days, 'days').format('DD/MM/YYYY');
  153. export const subtractDayInDate = (date, days=1) => moment(date, 'DD/MM/YYYY', 'pt-BR').subtract(days, 'days').format('DD/MM/YYYY');
  154. export const addPeriod = (date, period = 'days' ,days = 1, format = 'DD/MM/YYYY') => moment(date, 'DD/MM/YYYY', 'pt-BR').add(days, period).format(format);
  155. export const subPeriod = (date, period = 'days' ,days = 1, format = 'DD/MM/YYYY') => moment(date, 'DD/MM/YYYY', 'pt-BR').subtract(days, period).format(format);
  156. export const getDateByMonth = (initDate, months) => moment(initDate, 'DD/MM/YYYY', 'pt-BR').add(months, 'months').format('DD/MM/YYYY');
  157.  
  158. export const getPeriodStart = (period = 'week' ,format = 'DD/MM/YYYY', date = new Date()) =>
  159. moment(moment(date, 'DD/MM/YYYY', 'pt-BR').startOf(period), 'DD/MM/YYYY', 'pt-BR').format(format)
  160.  
  161. export const getPeriodEnd = (period = 'week' ,format = 'DD/MM/YYYY', date = new Date()) =>
  162. moment(moment(date, 'DD/MM/YYYY', 'pt-BR').endOf(period), 'DD/MM/YYYY', 'pt-BR').format(format)
  163.  
  164. export const getWeekString = (date = new Date()) =>
  165. `
  166. ${moment(moment(date, 'DD/MM/YYYY', 'pt-BR').startOf('week'), 'DD/MM/YYYY', 'pt-BR').format('DD MMM')}
  167. à
  168. ${moment(moment(date, 'DD/MM/YYYY', 'pt-BR').endOf('week'), 'DD/MM/YYYY', 'pt-BR').format('DD MMM')}
  169. `
  170.  
  171. export const getDaysBetweenDates = (dateFrom, dateTo) => {
  172. const from = moment(dateFrom, 'DD/MM/YYYY', 'pt-BR')
  173. const to = moment(dateTo, 'DD/MM/YYYY', 'pt-BR')
  174. //return parseInt(to.diff(from, 'days'))
  175. return Math.abs(parseInt(moment.duration(from.diff(to)).asDays()))
  176. }
  177. export const getMonthsBetweenDates = (dateFrom, dateTo) => {
  178. const from = moment(dateFrom, 'DD/MM/YYYY', 'pt-BR')
  179. const to = moment(dateTo, 'DD/MM/YYYY', 'pt-BR')
  180. return parseInt(to.diff(from, 'months'))
  181. }
  182. export const unformatHour = hour => (/^(([0-1]{1}[0-9]{1}|20|21|22|23):[0-5]{1}[0-9]{1})$/.test(hour))? hour.replace(/:/g, "") : hour;
  183. export const formatHour = hour => {
  184. if(hour === null || hour === ''){ return '' }
  185. const stringHour = hour.toString()
  186. if(stringHour.length === 3){
  187. return `0${stringHour[0]}:${stringHour[1]}${stringHour[2]}`;
  188. }else if(stringHour.length === 4){
  189. return `${stringHour[0]}${stringHour[1]}:${stringHour[2]}${stringHour[3]}`;
  190. }
  191. };
  192.  
  193. export const formatHourArrayObj = (arrayObj) => {
  194. return arrayObj.map(item => {
  195. item.times = item.times.map(time => {
  196. time.startTime = formatHour(time.startTime)
  197. time.endTime = formatHour(time.endTime)
  198. return time
  199. })
  200. return item
  201. })
  202. };
  203.  
  204. export const unformatHourArrayObj = (arrayObj) => {
  205. return arrayObj.map(item => {
  206. item.times = item.times.map(time => {
  207. time.startTime = parseInt(unformatHour(time.startTime))
  208. time.endTime = parseInt(unformatHour(time.endTime))
  209. return time
  210. })
  211. return item
  212. })
  213. };
  214.  
  215. export const qntDayOfMonth = (date) => {
  216. const arrayDate = date.split('/')
  217. const mes = parseInt(arrayDate['1']) -1;
  218. const ano = parseInt(arrayDate['2']);
  219. let bissexto;
  220. if((ano%4) == 0 && (ano%100)!=0 ||(ano%400)==0){
  221. bissexto = 29;
  222. }else{
  223. bissexto = 28;
  224. }
  225. const meses = new Array(31,bissexto,31,30,31,30,31,31,30,31,30,31);
  226. const qnt = meses[mes];
  227. return qnt;
  228. }
  229.  
  230.  
  231. /*
  232. * Tree View Data
  233. */
  234. export const createTreeView = (arrayData) => {
  235. const insertChildren = (item) => {
  236. arrayData.forEach(obj => {
  237. if(item.id === obj.parentId) {
  238. if(item.hasOwnProperty('children')){
  239. item.children = deleteObjFromArrayById(item.children, obj);
  240. item.children.push(obj)
  241. }else{
  242. item.children = []
  243. item.children.push(obj)
  244. }
  245. item.children.map(insertChildren)
  246. }
  247. });
  248. return item;
  249. }
  250. const newArray = arrayData.map(insertChildren).filter((item) => {
  251. return (!item.parentId) ? true : false
  252. })[0]
  253. return newArray;
  254. };
  255.  
  256. export const createTree = (arrayData, treeViewCheckList = []) => {
  257. const insertChildren = (item) => {
  258. arrayData.forEach(obj => {
  259. if(item.id === obj.parentId) {
  260. if(item.hasOwnProperty('children')){
  261. item.children = deleteObjFromArrayById(item.children, obj);
  262. item.children.push(obj)
  263. }else{
  264. item.children = []
  265. item.children.push(obj)
  266. }
  267. item.children.map(insertChildren)
  268. }
  269. item.checked = (treeViewCheckList.find(id => id === item.id))? true : false
  270. });
  271. return item;
  272. }
  273. const newArray = arrayData.map(insertChildren).filter((item) => {
  274. return (!item.parentId) ? true : false
  275. })
  276. return newArray;
  277. };
  278.  
  279.  
  280. /*
  281. * Permissions
  282. * */
  283. export const verifyPermission = (keyPermission) => {
  284. if(!keyPermission) { return true }
  285. const permissions = loadStorage('polisystem_storage_group_permissions')
  286. if(permissions && permissions.length) {
  287. const hasPermission = permissions.find(item => item === keyPermission)
  288. return (hasPermission)? hasPermission : false
  289. }
  290. return false
  291. }
  292.  
  293. /**
  294. * Styles
  295. */
  296. export function parseStyle(propertiesObj) {
  297. const arrayStyles = []
  298. for (let prop in propertiesObj) {
  299. arrayStyles.push(`${sanitizeProp(prop)}:${propertiesObj[prop]}`)
  300. }
  301. return arrayStyles.join(';')
  302. }
  303.  
  304. const sanitizeProp = (prop) => prop.replace(/([A-Z])/g, '-$1').toLowerCase()
  305.  
  306. /**
  307. * Days Difference Calculator
  308. */
  309. export function daysDifCalc(initDate, finalDate) {
  310. if(!finalDate) { finalDate = new Date() }
  311. const _MS_PER_DAY = 1000 * 60 * 60 * 24
  312. initDate = new Date(initDate)
  313. // Discard the time and time-zone information.
  314. const utc1 = Date.UTC(initDate.getFullYear(), initDate.getMonth(), initDate.getDate());
  315. const utc2 = Date.UTC(finalDate.getFullYear(), finalDate.getMonth(), finalDate.getDate());
  316. return Math.floor((utc2 - utc1) / _MS_PER_DAY);
  317. }
Add Comment
Please, Sign In to add comment