首页 > 解决方案 > 协助业务逻辑

问题描述

我有一个应用程序,杂货店可以在其中记录其常客帐户。当客户购买东西时,杂货店会将金额添加到他们的帐户中。杂货店还可以在客户支付他的标签时添加帐户的付款。

杂货店还可以撤销错误添加的金额。问题是在客户付款后,杂货店仍然可以冲销付款前的金额。这会导致我不希望在我的应用程序中出现负数。

下面是一个例子:

  1. +5
  2. +2

现在总数是7。

然后客户付款:

  1. -5

现在总数是2。

如果杂货店反转第一个数量 5,则当前总数将为 -3。

我的解决方法是在数据库中的所有文档中添加一个名为“canCorrect”的布尔字段。每当杂货店添加付款时,此“canCorrect”字段将更改为 false。任何具有错误“canCorrect”值的文档都无法撤消。

问题是我认为每次杂货店添加付款时检查所有以前的文件并不是最佳选择。如果客户在此付款之前有 200 份文件怎么办?

如果客户付款,然后在此付款后添加新金额,然后再付款怎么办?我的修复仍然会处理所有金额,即使是在第一次付款之前支付的金额。

你能告诉我一个更好的解决方案吗?

以下是我的代码:

[编辑:“hisab”和“baqala”这两个词分别是阿拉伯语的“帐户”和“杂货店”:)]

static Future<void> savePayment({
    @required BuildContext context,
    @required String mobile,
    @required double currentTotalHisab,
    @required double paymentAmount,
  }) async {
  // 1. Get the subscriber document
  QuerySnapshot snapshot = await FirebaseFirestore.instance
         .collection(CurrentUser.getCurrentUser().uid)
         .where('mobile', isEqualTo: mobile)
         .get();

  // 2. Confirm only a single subscriber document exists
  if (snapshot.docs.length == 0)
    throw UserDocumentNotFound(mobile);
  else if (snapshot.docs.length > 1) throw FoundTwoDocumentsWithSameMobile();

  // 3. Get the subscriber document reference
  DocumentReference subscriberDoc = snapshot.docs.first.reference;

  // 4. Get the current server timestamp
  FieldValue currentTimestamp = FieldValue.serverTimestamp();

  // ******************* Added to prevent reverse hisabs before a payment **************************
  // *********** It changes the "canCorrect" field to false of all previous hisabs *****************
  QuerySnapshot hisabHistoryCollection =
      await subscriberDoc.collection('hisabHistory').where('type', isEqualTo: 'hisab').get();

  WriteBatch wb = FirebaseFirestore.instance.batch();

  for (QueryDocumentSnapshot document in hisabHistoryCollection.docs) {
    wb.update(
      document.reference,
      {
        'canCorrect': false,
      },
    );
  }
  // *********************************************************************************************

  num newTotalHisab = double.parse((currentTotalHisab - paymentAmount).toStringAsFixed(2));

  // 5. Update the total hisab and the last payment date in the subscriber document

  wb.update(
    subscriberDoc,
    {
      'totalHisab': newTotalHisab,
      'lastPayment': currentTimestamp,
    },
  );

  // 6. Add a new "correction" payment document
  wb.set(
    subscriberDoc.collection('hisabHistory').doc(),
    {
      'amount': paymentAmount,
      'serverTimestamp': currentTimestamp,
      'type': 'payment',
      'note': 'normal',
      'correctedFor': null,
      'before': currentTotalHisab,
      'after': newTotalHisab,
    },
  );

  await wb.commit();

}

标签: flutter

解决方案


推荐阅读