Skip to content

Commit

Permalink
fix collection rule issue
Browse files Browse the repository at this point in the history
  • Loading branch information
yellowbean committed Feb 23, 2024
1 parent d4cf550 commit e3682c8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 26 deletions.
33 changes: 10 additions & 23 deletions absbox/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,7 @@ def __post_init__(self) -> None:
try:
_r = requests.get(f"{self.url}/{Endpoints.Version.value}", verify=False, timeout=5).text
except (ConnectionRefusedError, ConnectionError):
console.print(f"❌{MsgColor.Error.value}Error: Can't not connect to API server {self.url}")
self.url = None
return
raise AbsboxError(f"❌{MsgColor.Error.value}Error: Can't not connect to API server {self.url}")
if _r is None:
raise RuntimeError(f"Failed to get version from url:{self.url}")
self.server_info = self.server_info | json.loads(_r)
Expand Down Expand Up @@ -195,7 +193,10 @@ def build_run_deal_req(self, run_type: str, deal, perfAssump=None, nonPerfAssump
r = mkTag((RunReqType.MultiStructs.value, [mDeal, _perfAssump, _nonPerfAssump]))
case _:
raise RuntimeError(f"Failed to match run type:{run_type}")
return json.dumps(r, ensure_ascii=False)
try:
return json.dumps(r, ensure_ascii=False)
except TypeError as e:
raise AbsboxError(f"❌Failed to convert request to json:{e}")

def build_pool_req(self, pool, poolAssump, rateAssumps) -> str:
"""build pool run request: (single run, multi-scenario run)
Expand Down Expand Up @@ -267,7 +268,7 @@ def run(self, deal,
rawWarnMsg = []
if multi_run_flag:
rawWarnMsgByScen = {k: [f"{MsgColor.Warning.value}{_['contents']}" for _ in filter_by_tags(v[RunResp.LogResp.value], enumVals(ValidationMsg))] for k, v in result.items()}
rawWarnMsg = [b for a in rawWarnMsgByScen.values() for b in a]
rawWarnMsg = tz.concat(rawWarnMsgByScen.values())
else:
rawWarnMsg = [f"{MsgColor.Warning.value}{_['contents']}" for _ in filter_by_tags(result[RunResp.LogResp.value], enumVals(ValidationMsg))]

Expand Down Expand Up @@ -295,25 +296,11 @@ def runPool(self, pool, poolAssump=None, rateAssump=None, read=True):
"""
def read_single(pool_resp):
(pool_flow, pool_bals) = pool_resp
flow_header, idx, expandFlag = guess_pool_flow_header(pool_flow[0], pool_lang)
result = None
try:
if not expandFlag:
result = pd.DataFrame(tz.pluck('contents', pool_flow), columns=flow_header)
else:
result = pd.DataFrame([_['contents'][-1]+_['contents'][-1] for _ in pool_flow], columns=flow_header)
except ValueError as e:
console.print(f"❌{MsgColor.Error.value}Failed to match header:{flow_header} with {pool_flow[0]['contents']}")
console.print(f"error:{e}")

result = result.set_index(idx)
result.index.rename(idx, inplace=True)
result.sort_index(inplace=True)
result = _read_cf(pool_flow['contents'], self.lang)
return (result, pool_bals)

multi_scenario = True if isinstance(poolAssump, dict) else False
url = f"{self.url}/{Endpoints.RunPoolByScenarios.value}" if multi_scenario else f"{self.url}/{Endpoints.RunPool.value}"
pool_lang = guess_pool_locale(pool)
req = self.build_pool_req(pool, poolAssump, rateAssump)
result = self._send_req(req, url)

Expand Down Expand Up @@ -559,11 +546,11 @@ def _send_req(self, _req, _url: str, timeout=10, headers={})-> dict | None:
if self.session:
r = self.session.post(_url, data=_req.encode('utf-8'), headers=hdrs, verify=False, timeout=timeout)
else:
raise AbsboxError(f"❌{MsgColor.Error.value}: None type for session")
raise AbsboxError(f"❌: None type for session")
except (ConnectionRefusedError, ConnectionError):
raise AbsboxError(f"❌{MsgColor.Error.value} Failed to talk to server {_url}")
raise AbsboxError(f"❌ Failed to talk to server {_url}")
except ReadTimeout:
raise AbsboxError(f"❌{MsgColor.Error.value} Failed to get response from server")
raise AbsboxError(f"❌ Failed to get response from server")
if r.status_code != 200:
raise EngineError(r)
try:
Expand Down
13 changes: 10 additions & 3 deletions absbox/local/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import functools
import logging
import toolz as tz
from lenses import lens

import pandas as pd
from pyspecter import query, S
Expand Down Expand Up @@ -1242,10 +1243,14 @@ def id_by_pool_assets(z):
y = None
if query(x, ["pool","tag"])=='SoloPool':
return id_by_pool_assets(x["pool"]['contents'])
elif "pool" in x and set(x.keys()) == {"pool"}:
return id_by_pool_assets(x['pool'])
elif "pool" in x and x["pool"]['tag']=='MultiPool':
assetTags = flat(query(x,["pool","contents",S.MVALS,S.ALL,"assets",S.ALL,"tag"]))
assetTags = lens['pool']['contents'].Values()['assets'][0]['tag'].collect()(x)
if len(set(assetTags))>1:
return "UDeal"
else:
return id_by_pool_assets(list(x["pool"]['contents'].values())[0])
elif "ResecDeal" == x['pool']['tag']:
vs = [ v['deal'] for k,v in x["pool"]['contents'].items() ]
assetTypes = set(map(identify_deal_type, vs))
Expand Down Expand Up @@ -1599,9 +1604,9 @@ def mkCollection(x):
case [None, s, *pcts] if isinstance(pcts, list):
return mkTag(("CollectByPct" ,[None, mkPoolSource(s), pcts]))
case [mPids, s, acc] if isinstance(acc, str):
return mkTag(("Collect",[map(mkPid,mPids), mkPoolSource(s), acc]))
return mkTag(("Collect",[lmap(mkPid,mPids), mkPoolSource(s), acc]))
case [mPids, s, *pcts] if isinstance(pcts, list):
return mkTag(("CollectByPct" ,[map(mkPid,mPids), mkPoolSource(s), pcts]))
return mkTag(("CollectByPct" ,[lmap(mkPid,mPids), mkPoolSource(s), pcts]))
case _:
raise RuntimeError(f"Failed to match collection rule {x}")

Expand Down Expand Up @@ -1847,6 +1852,8 @@ def translate(y) -> dict:
return {"pricing":mkPricingAssump(p)}
case ("fireTrigger", scheduleFired):
return {"fireTrigger":[ (dt, dealCycleMap[cyc], tn) for (dt, cyc, tn) in scheduleFired]}
case ("makeWhole", d,spd,tbl):
return {"makeWholeWhen": [d,spd,tbl]}
match xs:
case None:
return {}
Expand Down

0 comments on commit e3682c8

Please sign in to comment.