MProfitRatioCalc.py 2.9 KB

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