Skip to content

Instantly share code, notes, and snippets.

@brasizza
Created September 24, 2024 13:38
Show Gist options
  • Save brasizza/1bcc15d936d53b9eb4f9335a482f2a54 to your computer and use it in GitHub Desktop.
Save brasizza/1bcc15d936d53b9eb4f9335a482f2a54 to your computer and use it in GitHub Desktop.
// ignore_for_file: constant_identifier_names
import 'dart:convert';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart';
import 'package:epocpdv/src/core/extensions/strings_extension.dart';
import 'package:epocpdv/src/core/ui/constants/constants_export.dart';
import 'package:epocpdv/src/data/model/extrato_model.dart';
import 'package:epocpdv/src/data/model/user_model.dart';
import 'package:epocpdv/src/data/service/utils/utils_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:universal_platform/universal_platform.dart';
enum PlatformEnum { ANDROID, IOS, MAC, FUCHSIA, WINDOWS, LINUX, WEB }
class Utils {
static final _random = Random();
static String base64ToStringBig(String encoded) {
Codec<String, String> stringToBase64 = utf8.fuse(base64);
String decoded = stringToBase64.decode(encoded); // username:password
return decoded;
}
static UserModel? getUserByCod(
{required int codUsu, required UtilsService service}) {
return service.getUserByCod(codUsu: codUsu);
}
static String stringToMd5(String text) {
return md5.convert(utf8.encode(text)).toString();
}
static String convertObjStringJson(String myJson) {
var value = myJson;
value = value.replaceAll(r"\", '');
return value;
}
static String removeLasts(String str, int lasts) {
return str = str.substring(0, str.length - lasts);
}
static int countProdutos({ExtratoModel? extrato}) {
int totalProdutos = 0;
totalProdutos +=
(extrato?.itens.where((item) => item.flgTipoItem != 'S').length ?? 0);
totalProdutos += (extrato?.fidelidade.itens
?.where((item) => item.flgTipoItem != 'S')
.length ??
0);
if (extrato?.desmembramento != null) {
for (var desmembramento in extrato!.desmembramento) {
totalProdutos += (desmembramento.itens
.where((item) => item.flgTipoItem != 'S')
.length);
}
}
return totalProdutos;
}
static bool existeDesconto({ExtratoModel? extrato}) {
if ((extrato?.fidelidade.codMotivo ?? 0) != 0) {
return true;
}
if (extrato?.desmembramento.isNotEmpty ?? false) {
for (var desmembramento in extrato!.desmembramento) {
if ((desmembramento.fidelidade.codMotivo ?? 0) != 0) {
return true;
}
}
}
return false;
}
static String convertStringJson(String myJson) {
var value = myJson;
value = value.replaceAll('{', '{"');
value = value.replaceAll(': ', '": "');
value = value.replaceAll(', ', '", "');
value = value.replaceAll('}', '"}');
value = value.replaceAll('}"', '}');
value = value.replaceAll('"{', '{');
value = value.replaceAll('"[{', '[{');
value = value.replaceAll('}]"', '}]');
value = value.replaceAll('"[', '[');
value = value.replaceAll(']"}]', ']}]');
value = value.replaceAll(' }]",', ' }],');
value = value.replaceAll('[]', '"[]"');
value = value.replaceAll('[]', '"[]"');
return value;
}
static String generateMac(String seed) {
Random rnd = Random(
int.parse(seed.substring(1, (seed.length < 10) ? seed.length : 10)),
);
const chars = 'ABCDEF1234567890';
StringBuffer macBuffer = StringBuffer();
for (var i = 0; i < 12; i++) {
if (i % 2 == 0 && i != 0) {
macBuffer.write(':');
}
macBuffer.write(chars[rnd.nextInt(chars.length)]);
}
return macBuffer.toString();
}
static String resolveCargaName(String cargaTabela) {
List<String> cargas = cargaTabela.split('_');
String nomeCarga = cargas.map((e) => toBeginningOfSentenceCase(e)).join('');
if (nomeCarga == 'Parametros') {
nomeCarga = 'ParametrosExport';
}
if (nomeCarga == 'Cidades') {
nomeCarga = 'CidadesSemEmpresa';
}
if (nomeCarga == 'Estados') {
nomeCarga = 'EstadoSemEmpresa';
}
if (nomeCarga == 'Produto') {
nomeCarga = 'ProdutoVendavel';
}
final String nomeTabela = 'carga$nomeCarga';
return nomeTabela;
}
static String getRandomString(int length) {
const chars =
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
return (DateTime.now().toUtc().toString().replaceAll(' ', '+') +
String.fromCharCodes(Iterable.generate(length,
(_) => chars.codeUnitAt(_random.nextInt(chars.length)))))
.toBase64;
}
static String getRandomNumber(int length) {
const chars = '1234567890';
return (String.fromCharCodes(Iterable.generate(
length, (_) => chars.codeUnitAt(_random.nextInt(chars.length)))));
}
static Future<String> asymmetricEncript(String text) async {
String key = '';
if (kIsWeb) {
PickedFile localFile = PickedFile('assets/key/pdv.pem');
key = (await localFile.readAsString());
} else {
key = await rootBundle.loadString('assets/key/pdv.pem');
}
final parser = RSAKeyParser();
final publicKey = parser.parse(key) as RSAPublicKey;
final encrypter = Encrypter(RSA(publicKey: publicKey));
final encrypted = encrypter.encrypt(text);
return (encrypted.base64);
}
static Future<String> asymmetricDencript(String text) async {
String key = '';
if (kIsWeb) {
PickedFile localFile = PickedFile('assets/key/pdv.key');
key = (await localFile.readAsString());
} else {
key = await rootBundle.loadString('assets/key/pdv.key');
}
final parser = RSAKeyParser();
final private = parser.parse(key) as RSAPrivateKey;
final encrypter = Encrypter(RSA(privateKey: private));
final decriptedString = encrypter.decrypt(Encrypted(base64Decode(text)));
return (decriptedString);
}
static base64toImage(String? logotipo, {double? width}) {
if (logotipo == null) {
return Image.asset(
ImageConstants.placeHolder,
width: width,
);
} else {
String bigLogotipo = logotipo.fromBase64;
List<String> logo = bigLogotipo.split(',');
if (logo.length > 1) {
return Image.memory(
base64.decode(logo[1]),
width: width,
gaplessPlayback: true,
);
} else {
return Image.asset(
ImageConstants.placeHolder,
width: width,
);
}
}
}
static Future<void> forceFullScreen() async {
await SystemChrome.restoreSystemUIOverlays();
await SystemChannels.textInput.invokeMethod('TextInput.hide');
}
static String salt(String dados) {
return dados.toMd5;
}
static int hexToInt(String hexString) {
List<String> splitted = [];
for (int i = 0; i < hexString.length; i = i + 2) {
splitted.add(hexString.substring(i, i + 2));
}
String ascii = List.generate(
splitted.length, (i) => (int.parse(splitted[i], radix: 16))).join();
return int.parse(ascii);
}
static String hexToAscii(String hexString) {
List<String> splitted = [];
for (int i = 0; i < hexString.length; i = i + 2) {
splitted.add(hexString.substring(i, i + 2));
}
String ascii = List.generate(splitted.length,
(i) => String.fromCharCode(int.parse(splitted[i], radix: 16))).join();
return ascii;
}
static String toHexString(String str) {
final ascii = str.codeUnits;
var code = <String>[];
for (var asc in ascii) {
code.add(asc.toRadixString(16));
}
return code.join();
}
static List<String> splitStringIntoChunks(String input, int chunkSize) {
return input
.splitMapJoin(
RegExp('.{1,$chunkSize}'),
onMatch: (match) => match.group(0)!,
onNonMatch: (nonMatch) => '',
)
.split('');
}
static PlatformEnum get platform {
if (kIsWeb) {
return PlatformEnum.WEB;
}
if (UniversalPlatform.isAndroid) {
return PlatformEnum.ANDROID;
} else if (UniversalPlatform.isIOS) {
return PlatformEnum.IOS;
} else if (UniversalPlatform.isFuchsia) {
return PlatformEnum.FUCHSIA;
} else if (UniversalPlatform.isLinux) {
return PlatformEnum.LINUX;
} else if (UniversalPlatform.isMacOS) {
return PlatformEnum.MAC;
} else {
return PlatformEnum.WINDOWS;
}
}
static getRandomColor() {
final colors = <Color>[
const Color(0xFFFFCBBB),
const Color(0xFFA0F4FF),
const Color(0xFFCADCE5),
const Color(0xFFFFB8B9),
const Color(0xFFFFE8A1),
const Color(0xFFF5B9FF),
const Color(0xFFEEEEEE),
const Color(0xFFC1CBFC),
];
final randomNumber = _random.nextInt(colors.length - 1);
return colors[randomNumber];
}
static bool isEmailValid(String email) {
// Regex pattern for a basic email validation
String pattern = r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$';
RegExp regex = RegExp(pattern);
return regex.hasMatch(email);
}
static bool isBirthdateValid(String birthdate) {
try {
DateTime date = DateTime.parse(birthdate.split('/').reversed.join());
// Ensure birthdate is not in the future
if (date.isAfter(DateTime.now())) {
return false;
}
// Ensure the age is within a reasonable range (e.g., between 0 and 150 years old)
DateTime minDate =
DateTime.now().subtract(const Duration(days: 365 * 150));
if (date.isBefore(minDate)) {
return false;
}
return true;
} catch (e) {
// If parsing fails, return false
return false;
}
}
static bool isCPFValid(String cpf) {
// Remove non-digit characters
cpf = cpf.replaceAll(RegExp(r'[^\d]'), '');
// CPF must be 11 characters long
if (cpf.length != 11) return false;
// Check if all digits are the same
if (RegExp(r'^(\d)\1*$').hasMatch(cpf)) return false;
// Compute verification digits
List<int> numbers = cpf.split('').map(int.parse).toList();
int sum = 0;
for (int i = 0; i < 9; i++) {
sum += numbers[i] * (10 - i);
}
int firstDigit = 11 - (sum % 11);
if (firstDigit >= 10) firstDigit = 0;
if (numbers[9] != firstDigit) return false;
sum = 0;
for (int i = 0; i < 10; i++) {
sum += numbers[i] * (11 - i);
}
int secondDigit = 11 - (sum % 11);
if (secondDigit >= 10) secondDigit = 0;
if (numbers[10] != secondDigit) return false;
return true;
}
static String removeCommasAndDots(String input) {
String result = input.replaceAll(RegExp(r'[,.R$]'), '');
return result;
}
static String formatNumberWithDecimal(String input) {
if (input.length >= 2) {
String lastTwoDigits = input.substring(input.length - 2);
String remainingDigits = input.substring(0, input.length - 2);
String formattedNumber = '$remainingDigits.$lastTwoDigits';
return double.parse(formattedNumber).toStringAsFixed(2);
} else {
return input;
}
}
static bool isCNPJValid(String cnpj) {
// Remove non-digit characters
cnpj = cnpj.replaceAll(RegExp(r'[^\d]'), '');
// CNPJ must be 14 characters long
if (cnpj.length != 14) return false;
// Check if all digits are the same
if (RegExp(r'^(\d)\1*$').hasMatch(cnpj)) return false;
// Compute verification digits
List<int> numbers = cnpj.split('').map(int.parse).toList();
int sum = 0;
int weight = 5;
for (int i = 0; i < 12; i++) {
sum += numbers[i] * weight;
weight = (weight == 2) ? 9 : weight - 1;
}
int mod = sum % 11;
int firstDigit = (mod < 2) ? 0 : 11 - mod;
if (numbers[12] != firstDigit) return false;
sum = 0;
weight = 6;
for (int i = 0; i < 13; i++) {
sum += numbers[i] * weight;
weight = (weight == 2) ? 9 : weight - 1;
}
mod = sum % 11;
int secondDigit = (mod < 2) ? 0 : 11 - mod;
if (numbers[13] != secondDigit) return false;
return true;
}
static double totalContas({ExtratoModel? extrato}) {
double totalConta = 0;
totalConta += extrato?.fidelidade.totalItens ?? 0;
if (extrato?.desmembramento != null) {
if (extrato!.desmembramento.isNotEmpty) {
for (var desmembramento in extrato.desmembramento) {
totalConta += (desmembramento.totalDesmembramento ?? 0);
}
}
}
return totalConta;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment