74 lines
2.2 KiB
Dart
74 lines
2.2 KiB
Dart
class Product {
|
|
const Product({
|
|
required this.id,
|
|
this.gradeId = 0,
|
|
required this.code,
|
|
required this.grade,
|
|
required this.name,
|
|
required this.departmentCode,
|
|
required this.writeDate,
|
|
this.priceMinorUnits,
|
|
this.stock,
|
|
this.imageBase64,
|
|
});
|
|
|
|
final int id;
|
|
final int gradeId;
|
|
final String code;
|
|
final String grade;
|
|
final String name;
|
|
final int departmentCode;
|
|
final String writeDate;
|
|
final int? priceMinorUnits;
|
|
final num? stock;
|
|
final String? imageBase64;
|
|
|
|
String get cartKey => '$id:$grade';
|
|
|
|
factory Product.fromJson(Map<String, dynamic> json) {
|
|
final id = json['id'];
|
|
final departmentCode = json['departamento_id'];
|
|
if (id is! num || departmentCode is! num) {
|
|
throw const FormatException('Resposta de produto inválida.');
|
|
}
|
|
|
|
return Product(
|
|
id: id.toInt(),
|
|
gradeId: json['grade_id'] is num ? (json['grade_id'] as num).toInt() : 0,
|
|
code: json['codigo']?.toString() ?? '',
|
|
grade: json['grade']?.toString() ?? '',
|
|
name: json['descricao']?.toString() ?? '',
|
|
departmentCode: departmentCode.toInt(),
|
|
writeDate: json['write_date']?.toString() ?? '',
|
|
priceMinorUnits: _toMinorUnits(json['preco']),
|
|
stock: _number(json['qtdEmEstoque']),
|
|
imageBase64: json['foto'] is String && (json['foto'] as String).isNotEmpty
|
|
? json['foto'] as String
|
|
: null,
|
|
);
|
|
}
|
|
|
|
static int? _toMinorUnits(dynamic value) {
|
|
if (value == null || value is bool) return null;
|
|
final normalized = value.toString().replaceAll(',', '.');
|
|
final match = RegExp(r'^(-?)(\d+)(?:\.(\d+))?$').firstMatch(normalized);
|
|
if (match == null) return null;
|
|
|
|
final isNegative = match.group(1) == '-';
|
|
final whole = int.tryParse(match.group(2)!);
|
|
if (whole == null) return null;
|
|
|
|
final fraction = match.group(3) ?? '';
|
|
final centsText = fraction.padRight(2, '0');
|
|
var minorUnits = whole * 100 + int.parse(centsText.substring(0, 2));
|
|
if (fraction.length > 2 && int.parse(fraction[2]) >= 5) minorUnits++;
|
|
return isNegative ? -minorUnits : minorUnits;
|
|
}
|
|
|
|
static num? _number(dynamic value) {
|
|
if (value is num) return value;
|
|
if (value is String) return num.tryParse(value.replaceAll(',', '.'));
|
|
return null;
|
|
}
|
|
}
|