Functions.js 13.6 KB
Newer Older
Giang Tran committed
1
import React from 'react';
Giang Tran committed
2 3 4 5 6 7 8
import {
  Dimensions,
  Platform,
  Alert,
  Text,
  PermissionsAndroid,
} from 'react-native';
Giang Tran committed
9 10
import moment from 'moment';
import _ from 'lodash';
Giang Tran committed
11
import I18n from '../helper/i18/i18n';
Giang Tran committed
12
import AppText from '../components/AppText';
Giang Tran committed
13

Giang Tran committed
14
import {DETAILNEW, NOTIFICATION} from '../routers/ScreenNames';
Giang Tran committed
15
import R from '../assets/R';
Giang Tran committed
16 17 18 19 20 21 22 23 24 25

export const convertScreen = (name) => {
  switch (name) {
    case 'CUSTOMER_NEWS':
      return DETAILNEW;
    default:
      return DETAILNEW;
  }
};

Giang Tran committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
export const requestCameraPermission = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA,
      {
        title: 'Cool Photo App Camera Permission',
        message:
          'Cool Photo App needs access to your camera ' +
          'so you can take awesome pictures.',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('You can use the camera');
    } else {
      console.log('Camera permission denied');
    }
  } catch (err) {
    console.warn(err);
  }
};

Giang Tran committed
50 51 52 53
export const renderStatus = (status) => {
  switch (status) {
    case 2:
      return (
Giang Tran committed
54 55
        <AppText
          i18nKey={'WaitVerification'}
Giang Tran committed
56 57 58 59
          style={{
            color: '#F99D1D',
            fontSize: getFontXD(42),
            fontWeight: 'bold',
Giang Tran committed
60 61
          }}
        />
Giang Tran committed
62 63 64
      );
    case 3:
      return (
Giang Tran committed
65 66
        <AppText
          i18nKey={'Verified'}
Giang Tran committed
67 68 69 70
          style={{
            color: '#17B217',
            fontWeight: 'bold',
            fontSize: getFontXD(42),
Giang Tran committed
71 72
          }}
        />
Giang Tran committed
73
      );
Giang Tran committed
74 75
    case 5:
      return (
Giang Tran committed
76 77
        <AppText
          i18nKey={'Request_Open_Account_CQG'}
Giang Tran committed
78 79 80 81
          style={{
            color: '#F99D1D',
            fontWeight: 'bold',
            fontSize: getFontXD(42),
Giang Tran committed
82 83
          }}
        />
Giang Tran committed
84 85 86
      );
    case 6:
      return (
Giang Tran committed
87 88
        <AppText
          i18nKey={'EnableCQG'}
Giang Tran committed
89 90 91 92
          style={{
            color: R.colors.main,
            fontWeight: 'bold',
            fontSize: getFontXD(42),
Giang Tran committed
93 94
          }}
        />
Giang Tran committed
95
      );
Giang Tran committed
96 97
    default:
      return (
Giang Tran committed
98 99
        <AppText
          i18nKey={'NotVerified'}
Giang Tran committed
100 101 102 103
          style={{
            color: '#929292',
            fontWeight: 'bold',
            fontSize: getFontXD(42),
Giang Tran committed
104 105
          }}
        />
Giang Tran committed
106 107 108 109
      );
  }
};

Giang Tran committed
110
export const NotificationAlert = (string) => {
Giang Tran committed
111
  Alert.alert(I18n.t('Notification'), string);
Giang Tran committed
112 113 114 115
};

export const confirmAlert = (title, callback) => {
  Alert.alert(
Giang Tran committed
116
    I18n.t('Notification'),
Giang Tran committed
117 118 119
    title,
    [
      {
Giang Tran committed
120
        text: I18n.t('Cancel'),
Giang Tran committed
121 122 123
        style: 'cancel',
      },
      {
Giang Tran committed
124
        text: I18n.t(Ok),
Giang Tran committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        onPress: () => {
          callback();
        },
      },
    ],
    {cancelable: false},
  );
};

const {width, height} = Dimensions.get('window');
export const getWidth = () => width;
export const getHeight = () => height;

// Get size for xd
export const WIDTHXD = (w) => width * (w / 1125);
export const HEIGHTXD = (h) => height * (h / 2436);
export const getLineHeightXD = (f) => f / 3 + 2;
export const getFontXD = (f) => f / 3 + 2;
// Get size for figmar
export const WIDTH = (w) => width * (w / 360);
export const HEIGHT = (h) => height * (h / 640);
export const getLineHeight = (f) => f;
export const getFont = (f) => f - 1;
Giang Tran committed
148
export const WIDTHXDICON = (w) => width * (w / 1125);
Giang Tran committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

export const validatePhone = (str) => {
  let re = /^[0-9+]{9,11}$/;
  return re.test(str);
};

// convert number 5000000=> 5.000.000
export const numberWithCommas = (x, c = '.') =>
  Math.round(x)
    .toString()
    .replace(/\B(?=(\d{3})+(?!\d))/g, c ? c : '.');

export const isIos = Platform.OS === 'ios';

export const Gender = {
  male: 0,
  female: 1,
};
167
export const converType = (type) => {
Giang Tran committed
168 169
  if (type == 'DEPOSIT') return I18n.t('Deposit');
  return I18n.t('Withdraw');
170 171 172 173
};
export const converStatus = (status) => {
  switch (status) {
    case 0:
Giang Tran committed
174
      return I18n.t('Waiting_for_Progress');
175
    case 1:
Giang Tran committed
176
      return I18n.t('Success');
177
    case 2:
Giang Tran committed
178
      return I18n.t('Cancel');
179 180
  }
};
Giang Tran committed
181 182 183 184

export function numberFormat(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
}
Giang Tran committed
185 186
export const toPriceVnd = (str) => {
  if (str) {
Giang Tran committed
187 188 189 190
    let headStringPrice = `${str
      .toString()
      .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')}`;
    return headStringPrice;
Giang Tran committed
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
  } else {
    return '';
  }
};

// cắt chuỗi dạng something...
export const ellipsis = (str = '', max = 30) =>
  str.length > max ? `${str.substring(0, max)}...` : str;

// tính chiều rộng của item dưới dạng flatlist
export const itemWidth = (numColumns, padding) => {
  let totalPadding = padding * (numColumns + 1);
  let w = (width - totalPadding) / numColumns;
  return w;
};

// chuyển string thành dạng viết hoa
export const toUpperCase = (str) => (str ? str.toUpperCase() : '');

export const sortType = {
  sortDefault: 1,
  latestNews: 2,
  priceUp: 3,
  priceDown: 4,
};

// delete item from array
export const removeItemFromArr2 = (items, index) => {
  let fill = items.filter((e, i) => i !== index);
  return fill;
};

export const removeItemFromArr = (items, index) => {
  items.splice(index, 1);
  return items;
};

// sum field of array object
export const totalByValue = (data, field) =>
  data.length === 0
    ? 0
    : data.map((item) => item[field]).reduce((prev, next) => prev + next);

// show notification
export const popupOk = (title, msg, onPress = null) => {
  Alert.alert(
    title,
    msg,
    [{text: 'Ok', style: 'ok', onPress: onPress || (() => null)}],
    {cancelable: false},
  );
};

export const popupCancel = (title, msg, onPress = null) => {
  Alert.alert(
    title,
    msg,
    [
      {text: 'Cancel', style: 'cancel'},
      {text: 'Ok', style: 'ok', onPress: onPress || (() => null)},
    ],
    {cancelable: false},
  );
};

export const cutStringBetweenCharacters = (str, char1, char2, addFirst) => {
  let re = `\\${char1}([^${char2}]+)\\${char2}`;
  let reg = new RegExp(re);
  let s = reg.exec(str) ? reg.exec(str)[1] : '';
  return addFirst ? char1 + s : s;
};
export const mark = (str, char1, char2, tag, endTag) => {
  let re = `\\${char1}(.*?)\\${char2}`;
  let reg = new RegExp(re, 'gi');
  return str.replace(reg, `<${tag}>$1</${endTag || tag}>12`);
};

export const cutStringBetweenCharacters2 = (str, char1, char2, addFirst) => {
  let s = str.split(char1).pop().split(char2)[0];
  return addFirst ? char1 + s : s;
};

export const replaceStrByIndex = (str, index, newStr) =>
  str.substr(0, index) + newStr + str.substr(index + 1);

global.langCode = 'vi';

export const getLangCode = () => global.langCode;
export const setLangCode = (langCode) => {
  global.langCode = langCode;
};

export const formatDateTime = (time) =>
  moment(time, 'DD/MM/YYYY').locale('vi').format('dddd (DD/MM/YYYY)');

export const VideoMimeType = {
  flv: 'video/x-flv',
  mp4: 'video/mp4',
  m3u8: 'application/x-mpegURL',
  ts: 'video/MP2T',
  '3gp': 'video/3gpp',
  mov: 'video/quicktime',
  avi: 'video/x-msvideo',
  wmv: 'video/x-ms-wmv',
};

export const StringFromLastCharacter = (str, char) =>
  str.substring(str.lastIndexOf(char) + 1);

export const toArrayBySeparators = (str, separators) => {
  /**
   * example: txt = "aaaa55bbb33cccc" => ["aaaa", "55", "bbb", "33", "cccc"]
   * toArrayBySeparators(txt, [55,33])
   */
  let reg = new RegExp(`(${separators.join('|')})`);
  return str
    .split(reg)
    .filter((x) => x.length > 0)
    .map((x) => x);
};

export const getRange = (startDate, endDate, type) => {
  let fromDate = moment(startDate);
  let toDate = moment(endDate);
  let range = [];
  let range2 = [];
  // for (let i = 0; i < diff; i++) {
  //   console.log('diff: ', diff);
  //   range.push(moment(startDate).add(i, type))
  // }
  while (toDate > fromDate || fromDate.format('M') === toDate.format('M')) {
    range.push(fromDate);
    range2.push(fromDate.format('DD/MM'));
    fromDate.add(1, type);
  }
  return range2;
};

export const getFirstAndLastWords = (text) => {
  let t = text.split(' ');
  return `${t[0]} ${t[t.length - 1]}`;
};

export const shortFullname = (text) => {
  let arr = text.split(' ');
  let name = '';
  arr.forEach((e, i) => {
    if (i === 0) {
      name += `${e} `;
    } else if (i === arr.length - 1) {
      name += arr.length === 2 ? e : ` ${e}`;
    } else {
      name += `${e.charAt(0)}`;
    }
  });
  return name;
};

Giang Tran committed
349 350 351 352 353
export const convertTimeApi = (date) => {
  const time = moment(date).format('YYYY-MM-DD');
  return time;
};

Giang Tran committed
354 355 356 357 358 359
export const convertDate = (date) => {
  const time = moment(date).format('DD/MM/YYYY');
  return time;
};

export const convertTime = (date) => {
Giang Tran committed
360
  const temp = new Date(moment(date, 'DD/MM/YYYY'));
Giang Tran committed
361
  const time = moment(temp).format('YYYY-MM-DD');
Giang Tran committed
362
  return time;
Giang Tran committed
363 364 365 366 367 368
};

export const getTimeDDMM = (time) => {
  let t1 = new Date(moment(time, 'DD/MM/YYYY').format('MM/DD/YYYY')).getTime();
  return t1;
};
Giang Tran committed
369 370 371 372 373 374 375

export const converStringToDate = (time) => {
  let t1 = new Date(moment(time, 'YYYY-MM-DD').format('MM/DD/YYYY')).getTime();
  const strDate = convertDate(t1);
  return strDate;
};

Giang Tran committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
export const sortDataByTime = (data) => {
  data.sort((a, b) => {
    let t1 = moment(a.time, 'DD-MM-YYYY').format('MM/YYYY');
    let t2 = moment(b.time, 'DD-MM-YYYY').format('MM/YYYY');
    if (t1 > t2) return -1;
    else {
      if (t1 < t2) return 1;
      else return 0;
    }
  });
  return data;
};

export const checkDifferMonth = (t1, t2) => t1 !== t2;
export const mapTimeVNToWorld = (data) => {
  if (!data) return data;
  // data 07/05/2019
  let str = data && data.split('/');
  if (str.length < 2) return data;
  return `${str[1]}/${str[0]}/${str[2]}`;
};

export const checkFormatWhiteSpace = (str) => {
  if (!str.replace(/\s/g, '').length) return true;
  return false;
};

// check 1 mảng dạng [a,b,c] có phần tử nào null,undefined,empty ko.
// nếu có trả về index phần từ đầu tiên ko thì return true
export const checkFormatArray = (array) => {
  let i = -1;
  if (!_.isEmpty(array)) {
    for (let j = 0; j < array.length; j++) {
      if (_.isUndefined(array[j]) || _.isNull(array[j]) || array[j] === '') {
        i = j;
        break;
      }
    }
  }
  if (i === -1) {
    return true;
  } else {
    return i;
  }
};

export const checkFormatArrayWhiteSpace = (array) => {
  let i = -1;
  if (!_.isEmpty(array)) {
    for (let j = 0; j < array.length; j++) {
      if (checkFormatWhiteSpace(array[j])) {
        i = j;
        break;
      }
    }
  }
  if (i === -1) {
    return true;
  } else {
    return i;
  }
};

// check 1 phần từ có null, undefined hay empty ko
export const checkFormatItem = (item) => {
  let i = -1;
  if (
    _.isUndefined(item) ||
    _.isNull(item) ||
    item === '' ||
    item === 'NaN' ||
    item === 0
  ) {
    i = 0;
  }
  if (i === -1) {
    return true;
  } else {
    return i;
  }
};
export const convertDataStatement = (data) => {
  let dataTmp = data;
  data.map((item, index) => {
    let date = mapTimeVNToWorld(item.transDate);
    let month = moment(date).format('M');
    let year = moment(date).format('YYYY');
    let isShowMonth = false;
    if (index === 0) {
      isShowMonth = true;
    } else if (data[index - 1]) {
      if (
        moment(mapTimeVNToWorld(data[index - 1].transDate)).format('YYYY') !==
        year
      ) {
        isShowMonth = true;
      } else if (
        moment(mapTimeVNToWorld(data[index - 1].transDate)).format('M') !==
        month
      ) {
        isShowMonth = true;
      }
    }

    dataTmp[index] = {...data[index], isShowMonth};
  });
  return dataTmp;
};

export const convertTypeFile = (name) => {
  if (name) {
    const fileNameTmp = name.toLowerCase();
    if (fileNameTmp.endsWith('.doc') || fileNameTmp.endsWith('.dox')) {
      return 0;
    }
    if (fileNameTmp.endsWith('.xls') || fileNameTmp.endsWith('.xlsx')) {
      return 1;
    }
    if (fileNameTmp.endsWith('.pdf')) {
      return 2;
    }
    if (
      fileNameTmp.endsWith('.heic') ||
      fileNameTmp.endsWith('.jpeg') ||
      fileNameTmp.endsWith('.jpg') ||
      fileNameTmp.endsWith('.png') ||
      fileNameTmp.endsWith('.bmp')
    ) {
      return 3;
    }
  }
  return 0;
};

export const getStartDateOfQuater = (quarter) => {
  return moment().quarter(quarter).startOf('quarter').format('YYYY-MM-DD');
};
export const getEndDateOfQuater = (quarter) => {
  return moment().quarter(quarter).endOf('quarter').format('YYYY-MM-DD');
};

export const changePositionElement = (element, array) => {
  let restArray = array.filter((e) => e != element);
  restArray.splice(0, 0, element);
  return restArray;
};

export const getMimeType = (fileExt) => {
  switch (fileExt) {
    case 'doc':
      return 'application/msword';
    case 'docx':
      return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    case 'ppt':
      return 'application/vnd.ms-powerpoint';
    case 'pptx':
      return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
    case 'xls':
      return 'application/vnd.ms-excel';
    case 'xlsx':
      return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    case 'pdf':
      return 'application/pdf';
    case 'png':
      return 'image/png';
    case 'bmp':
      return 'application/x-MS-bmp';
    case 'gif':
      return 'image/gif';
    case 'jpg':
      return 'image/jpeg';
    case 'jpeg':
      return 'image/jpeg';
    case 'avi':
      return 'video/x-msvideo';
    case 'aac':
      return 'audio/x-aac';
    case 'mp3':
      return 'audio/mpeg';
    case 'mp4':
      return 'video/mp4';
    case 'apk':
      return 'application/vnd.Android.package-archive';
    case 'txt':
    case 'log':
    case 'h':
    case 'cpp':
    case 'js':
    case 'html':
      return 'text/plain';
    default:
      return '*/*';
  }
};