MProfitRatioCalc.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from .MerchantCalc import MerchantCalc, mch_detail_paths, mch_paths
  2. from .algorithm import calc_mch_profit
  3. from .DataStream import EMchPosmap as pos_map
  4. import logging
  5. import time as time
  6. import logging
  7. import json
  8. logger = logging.getLogger('MProfitRatioCalc')
  9. def mixed_ratio(rclient):
  10. result = list()
  11. data = rclient.get('nc_refill-stat-merchant-mixed')
  12. if data is not None:
  13. mch_cfgs = json.loads(data)
  14. for mchid, val in mch_cfgs.items():
  15. mchid = int(mchid)
  16. period = int(val['period'])
  17. formula = val['profit_formula'].strip()
  18. result.append((mchid, period, formula))
  19. return result
  20. class MProfitRatioCalc(MerchantCalc):
  21. def _calc_handler(self, rclient):
  22. logger.debug('_calc_handler')
  23. mixed_ratios = mixed_ratio(rclient)
  24. reader = self._reader()
  25. gross = dict()
  26. detail = dict()
  27. for mchid, period, formula in mixed_ratios:
  28. end_time = int(time.time())
  29. days, start_time, end_time = self.calc_time(reader, end_time - period, end_time)
  30. if len(days) == 0:
  31. continue
  32. day_stamp = days[0]
  33. tuple_pathes = reader.many_tuple_path(days, mchids={mchid})
  34. gen = mch_detail_paths(reader, tuple_pathes, days)
  35. start = start_time - day_stamp
  36. end = end_time - day_stamp
  37. spec_amount = 0.0
  38. for _mchid, _card_type, _spec, _data in gen:
  39. submit_count, succ_count, fail_count, succ_ratio, profit = calc_mch_profit(_data, pos_map, start, end)
  40. if _card_type is None and _spec is None:
  41. profit_ratio = profit / (spec_amount + 0.000001)
  42. gross[_mchid] = [submit_count, succ_count, fail_count, succ_ratio, profit, round(profit_ratio, 5)]
  43. spec_amount = 0.0
  44. else:
  45. key = f"{_mchid}-{_card_type}-{_spec}"
  46. amount = succ_count * _spec
  47. spec_amount += amount
  48. profit_ratio = profit / (amount + 0.000001)
  49. detail[key] = [submit_count, succ_count, fail_count, succ_ratio, profit, round(profit_ratio, 5)]
  50. result = {'gross': gross, 'detail': detail}
  51. if len(gross) != 0 or len(detail) != 0:
  52. rclient.set(f"nc_refill_merchant_profit_ratio", json.dumps(result))
  53. rclient.publish('refill', json.dumps({'type': 'mch_profit_ratio', 'value': 0}))
  54. return 1