createCalibreAndArticleRetailFromForm method

Future<CalibreWeebi<ArticleRawAbstract>> createCalibreAndArticleRetailFromForm()
inherited

Implementation

Future<CalibreWeebi> createCalibreAndArticleRetailFromForm() async {
  final calibreId = await _articlesStore.generateNextCalibreId;
  final now = DateTime.now();
  ArticleRetail newArticle = ArticleRetail(
    calibreId: calibreId,
    id: 1,
    designation: name.trim(),
    kind: ArticleKind.retail,
    price: num.parse(price.trim()),
    cost: 0,
    unitsInOnePiece: 1,
    barcodeEAN: barcodeEAN.trim(),
    creationDate: now,
    status: true,
  );

  if (photoPath.isNotEmpty) {
    final localPhotoFilePath =
        photoSaver.copyPhotoFile(newArticle.designation, photoPath).path;

    final photo = ArticlePhoto(
        calibreId: newArticle.calibreId,
        id: newArticle.id,
        path: localPhotoFilePath,
        source: PhotoSource.file,
        dateUTC: now.toUtc());
    await _articlesStore.upsertPhoto(photo);
  }

  if (cost.isNotEmpty) {
    newArticle = newArticle.copyWith(cost: num.parse(cost.trim()));
  }
  if (unitsInOnePiece.isNotEmpty) {
    newArticle = newArticle.copyWith(
        unitsInOnePiece: double.parse(unitsInOnePiece.trim()));
  }
  if (barcodeEAN.isNotEmpty) {
    newArticle = newArticle.copyWith(barcodeEAN: barcodeEAN.trim());
  }

  final newCalibre = CalibreWeebi<ArticleRetail>(
    id: calibreId,
    title: name.trim(),
    stockUnit: stockUnit,
    creationDate: now,
    updateDate: now,
    status: true,
    statusUpdateDate: now,
    articles: [newArticle],
    kind: ArticleKind.retail,
  );

  if (photoPath.isNotEmpty) {
    final localPhotoFilePath =
        photoSaver.copyPhotoFile(newCalibre.title, photoPath).path;

    final photo = ArticlePhoto(
        calibreId: newCalibre.id,
        id: 0,
        path: localPhotoFilePath,
        source: PhotoSource.file,
        dateUTC: now.toUtc());
    await _articlesStore.upsertPhoto(photo);
  }

  final calibreRetail =
      await _articlesStore.createCalibrateArticle<ArticleRetail>(newCalibre);

  if (categories.isNotEmpty) {
    for (final category in categories) {
      final calibreIds = category.calibresIds..add(calibreId);
      final c = category.copyWith(calibresIds: calibreIds);
      await _articlesStore.updateCategory(c);
    }
  }

  return calibreRetail;
}