def end_sealedbid(self, stage): with utils.update_auction_document(self): self._end_sealedbid.set() while not self.bids_queue.empty(): LOGGER.info("Waiting for bids to process") sleep(0.1) LOGGER.info("Done processing bids queue") if len(self._bids_data.keys()) < 2: LOGGER.info("No bids on sealedbid phase. end auction") self.end_auction() return all_bids = deepcopy(self._bids_data) minimal_bids = [] max_bid = {'amount': 0} # init sealedbid winner bid for bid_id in all_bids.keys(): bid = get_latest_bid_for_bidder(all_bids[bid_id], bid_id) bid['bidder_name'] = self.mapping[bid['bidder_id']] minimal_bids.append(utils.prepare_results_stage(**bid)) # find a winner max_bid = max([max_bid, bid], key=lambda bid: bid['amount']) minimal_bids = sorting_by_amount(minimal_bids) self.auction_document['results'] = minimal_bids # save winner to stages in auction_document max_bid['sealedbid_winner'] = True self.auction_document['stages'][ self.auction_document['current_stage']].update( utils.prepare_results_stage(**max_bid)) run_time = utils.update_stage(self) self.approve_audit_info_on_sealedbid(run_time) self.auction_document['current_phase'] = PREBESTBID
def add_bid(self, current_stage, bid): LOGGER.info( '------------------ Adding bid ------------------', ) # Updating auction document with bid data with utils.update_auction_document(self.context, self.database) as auction_document: try: bid['bidder_name'] = self.context['bids_mapping'].get(bid['bidder_id'], False) result = utils.prepare_results_stage(**bid) auction_document['stages'][current_stage].update(result) results = auction_document['results'] bid_index = next((i for i, res in enumerate(results) if res['bidder_id'] == bid['bidder_id']), None) if bid_index is not None: results[bid_index] = result else: results.append(result) auction_document['results'] = sorting_by_amount(results) except Exception as e: LOGGER.fatal( "Exception during adding bid. " "Error: {}".format(e) ) return e self.end_bid_stage(bid) return True
def start_auction(self, switch_to_round=None): self.generate_request_id() self.audit['timeline']['auction_start']['time'] = datetime.now( tzlocal()).isoformat() LOGGER.info('---------------- Start auction ----------------', extra={ "JOURNAL_REQUEST_ID": self.request_id, "MESSAGE_ID": AUCTION_WORKER_SERVICE_START_AUCTION }) self.get_auction_info() self.get_auction_document() # Initital Bids bids = deepcopy(self.bidders_data) self.auction_document["initial_bids"] = [] bids_info = sorting_start_bids_by_amount(bids, features=self.features) for index, bid in enumerate(bids_info): amount = bid["value"]["amount"] audit_info = { "bidder": bid["id"], "date": bid["date"], "amount": amount } if self.features: amount_features = cooking(amount, self.features, self.bidders_features[bid["id"]]) coeficient = self.bidders_coeficient[bid["id"]] audit_info["amount_features"] = str(amount_features) audit_info["coeficient"] = str(coeficient) else: coeficient = None amount_features = None self.audit['timeline']['auction_start']['initial_bids'].append( audit_info) self.auction_document["initial_bids"].append( prepare_initial_bid_stage( time=bid["date"] if "date" in bid else self.startDate, bidder_id=bid["id"], bidder_name=self.mapping[bid["id"]], amount=amount, coeficient=coeficient, amount_features=amount_features)) if isinstance(switch_to_round, int): self.auction_document["current_stage"] = switch_to_round else: self.auction_document["current_stage"] = 0 all_bids = deepcopy(self.auction_document["initial_bids"]) minimal_bids = [] for bid_info in self.bidders_data: minimal_bids.append( get_latest_bid_for_bidder(all_bids, str(bid_info['id']))) minimal_bids = self.filter_bids_keys(sorting_by_amount(minimal_bids)) self.update_future_bidding_orders(minimal_bids) self.save_auction_document()
def prepare_auction_results(auction, bids_data): all_bids = deepcopy(bids_data) max_bids = [] for bid_id in all_bids.keys(): bid = get_latest_bid_for_bidder(all_bids[bid_id], bid_id) bid['bidder_name'] = auction.mapping[bid['bidder_id']] max_bids.append( prepare_results_stage(**bid) ) return sorting_by_amount(max_bids)
def end_bestbid(self, stage): with simple.update_auction_document(self): run_time = simple.update_stage(self) self.auction_document['current_phase'] = END all_bids = deepcopy(self._bids_data) self.auction_document['results'] = sorting_by_amount( all_bids.values()) if not self.debug: # TODO: post results data pass self.approve_audit_info_on_bestbid(run_time) self.end_auction()
def end_sealedbid(self, stage): with simple.update_auction_document(self): run_time = simple.update_stage(self) self._end_sealedbid.set() while not self.bids_queue.empty(): LOGGER.info("Waiting for bids to process") sleep(0.1) LOGGER.info("Done processing bids queue") self.auction_document['current_phase'] = PREBESTBID all_bids = deepcopy(self._bids_data) self.auction_document['results'] = sorting_by_amount( all_bids.values()) self.approve_audit_info_on_sealedbid(run_time)
def end_bids_stage(self, switch_to_round=None): self.generate_request_id() self.bids_actions.acquire() self.get_auction_document() LOGGER.info( '---------------- End Bids Stage ----------------', extra={"JOURNAL_REQUEST_ID": self.request_id, "MESSAGE_ID": AUCTION_WORKER_SERVICE_END_BID_STAGE} ) self.current_round = self.get_round_number( self.auction_document["current_stage"] ) self.current_stage = self.auction_document["current_stage"] if self.approve_bids_information(): LOGGER.info("Approved bid on current stage") start_stage, end_stage = self.get_round_stages(self.current_round) all_bids = deepcopy( self.auction_document["stages"][start_stage:end_stage] ) minimal_bids = [] for bid_info in self.bidders_data: minimal_bids.append( get_latest_bid_for_bidder(all_bids, bid_info['id']) ) minimal_bids = self.filter_bids_keys( sorting_by_amount(minimal_bids, reverse=False) ) self.update_future_bidding_orders(minimal_bids) self.approve_audit_info_on_bid_stage() if isinstance(switch_to_round, int): self.auction_document["current_stage"] = switch_to_round else: self.auction_document["current_stage"] += 1 LOGGER.info('---------------- Start stage {0} ----------------'.format( self.auction_document["current_stage"]), extra={"JOURNAL_REQUEST_ID": self.request_id, "MESSAGE_ID": AUCTION_WORKER_SERVICE_START_STAGE} ) self.save_auction_document() if self.auction_document["stages"][self.auction_document["current_stage"]]['type'] == 'pre_announcement': self.end_auction() self.bids_actions.release() if self.auction_document["current_stage"] == (len(self.auction_document["stages"]) - 1): self._end_auction_event.set()
def end_bestbid(self, stage): with utils.update_auction_document(self): all_bids = deepcopy(self._bids_data) minimal_bids = [] for bid_id in all_bids.keys(): bid = get_latest_bid_for_bidder(all_bids[bid_id], bid_id) bid['bidder_name'] = self.mapping[bid['bidder_id']] minimal_bids.append(utils.prepare_results_stage(**bid)) minimal_bids = sorting_by_amount(minimal_bids) self.auction_document['results'] = minimal_bids run_time = utils.update_stage(self) self.approve_audit_info_on_bestbid(run_time) self.end_auction()
def end_auction(self): LOGGER.info('---------------- End auction ----------------', extra={ "JOURNAL_REQUEST_ID": self.request_id, "MESSAGE_ID": AUCTION_WORKER_SERVICE_END_AUCTION }) LOGGER.debug("Stop server", extra={"JOURNAL_REQUEST_ID": self.request_id}) if self.server: self.server.stop() LOGGER.debug("Clear mapping", extra={"JOURNAL_REQUEST_ID": self.request_id}) delete_mapping(self.worker_defaults, self.auction_doc_id) start_stage, end_stage = self.get_round_stages(ROUNDS) minimal_bids = deepcopy( self.auction_document["stages"][start_stage:end_stage]) minimal_bids = self.filter_bids_keys( sorting_by_amount(minimal_bids, reverse=False)) self.auction_document["results"] = [] for item in minimal_bids: self.auction_document["results"].append( prepare_results_stage(**item)) self.auction_document["current_stage"] = ( len(self.auction_document["stages"]) - 1) LOGGER.debug(' '.join( ('Document in end_stage: \n', yaml_dump(json.loads(dumps(self.auction_document))))), extra={"JOURNAL_REQUEST_ID": self.request_id}) self.approve_audit_info_on_announcement() LOGGER.info('Audit data: \n {}'.format( yaml_dump(json.loads(dumps(self.audit)))), extra={"JOURNAL_REQUEST_ID": self.request_id}) if self.debug: LOGGER.debug('Debug: put_auction_data disabled !!!', extra={"JOURNAL_REQUEST_ID": self.request_id}) sleep(10) self.save_auction_document() else: if self.put_auction_data(): self.save_auction_document() LOGGER.debug("Fire 'stop auction worker' event", extra={"JOURNAL_REQUEST_ID": self.request_id})
def prepare_auction_stages_fast_forward(self): self.auction_document['auction_type'] = 'meat' if self.features else 'default' bids = deepcopy(self.bidders_data) self.auction_document["initial_bids"] = [] bids_info = sorting_start_bids_by_amount(bids, features=self.features, reverse=False) for index, bid in enumerate(bids_info): amount = bid["value"]["amountPerformance"] annualCostsReduction = bid["value"]["annualCostsReduction"] if self.features: amount_features = cooking( amount, self.features, self.bidders_features[bid["id"]], reverse=True ) coeficient = self.bidders_coeficient[bid["id"]] else: coeficient = None amount_features = None initial_bid_stage = prepare_initial_bid_stage( time=bid["date"] if "date" in bid else self.startDate, bidder_id=bid["id"], bidder_name=self.mapping[bid["id"]], amount=amount, coeficient=coeficient, amount_features=amount_features, annualCostsReduction=annualCostsReduction, yearlyPaymentsPercentage=bid["value"]["yearlyPaymentsPercentage"], contractDurationDays=bid["value"]["contractDuration"].get("days", None), contractDurationYears=bid["value"]["contractDuration"].get("years", None) ) self.auction_document["initial_bids"].append( initial_bid_stage ) self.auction_document['stages'] = [] next_stage_timedelta = datetime.now(tzlocal()) for round_id in xrange(ROUNDS): # Schedule PAUSE Stage pause_stage = prepare_service_stage( start=next_stage_timedelta.isoformat(), stage="pause" ) self.auction_document['stages'].append(pause_stage) # Schedule BIDS Stages for index in xrange(self.bidders_count): bid_stage = prepare_bids_stage({ 'start': next_stage_timedelta.isoformat(), 'bidder_id': '', 'bidder_name': '', 'amount': '0', "contractDurationDays": "0", "contractDurationYears": "0", "yearlyPaymentsPercentage": "0", 'time': '', }) self.auction_document['stages'].append(bid_stage) next_stage_timedelta += timedelta(seconds=BIDS_SECONDS) self.auction_document['stages'].append( prepare_service_stage( start=next_stage_timedelta.isoformat(), type="pre_announcement" ) ) self.auction_document['stages'].append( prepare_service_stage( start="", type="announcement" ) ) all_bids = deepcopy(self.auction_document["initial_bids"]) minimal_bids = [] for bid_info in self.bidders_data: minimal_bids.append(get_latest_bid_for_bidder( all_bids, str(bid_info['id']) )) minimal_bids = self.filter_bids_keys(sorting_by_amount(minimal_bids, reverse=False)) self.update_future_bidding_orders(minimal_bids) self.auction_document['endDate'] = next_stage_timedelta.isoformat() self.auction_document["current_stage"] = len(self.auction_document["stages"]) - 2