flutter - 协助业务逻辑
问题描述
我有一个应用程序,杂货店可以在其中记录其常客帐户。当客户购买东西时,杂货店会将金额添加到他们的帐户中。杂货店还可以在客户支付他的标签时添加帐户的付款。
杂货店还可以撤销错误添加的金额。问题是在客户付款后,杂货店仍然可以冲销付款前的金额。这会导致我不希望在我的应用程序中出现负数。
下面是一个例子:
- +5
- +2
现在总数是7。
然后客户付款:
- -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();
}
解决方案
推荐阅读
- arrays - 给定一个数字数组,找到一个数字开头,使得总和永远不会为负
- arrays - 快速将结构数组添加到另一个数组中时出现致命错误
- python - Pandas 多索引错误:MultiIndex 切片需要对索引进行 lexsorted
- twilio - Twilio SMS:有没有办法从 SMS API 与 TwiML 生成的 SMS 中识别状态更新
回应? - python - 将 .py 转换为 .exe 时出现问题,“致命错误:无法运行脚本”
- mysql - 了解如何设计 MySQL 索引以获得良好的性能
- python - 在没有循环的情况下限制每个唯一 pyspark 数据帧列值返回的行
- javascript - Nuxt Auth Module - 如何通过 id/username 获取用户
- python - 在 Google Compute Engine 上部署 Telegram 聊天机器人以及有关 webhook url 设置的问题
- python - Python PyQt5标签进入全局变量