Example #1
0
    def check_response(self, proposed_response):
        """


        DateInput.check_response(proposed_response) -> None


        Method checks for response length (must be 1 unless user_can_add).
        Method then checks that each item in reponse can make a datetime.date()
        object and for the corresponding date objects, r_min <= item <= r_max.
        """

        result = True
        lo = datetime.date.fromordinal(1)
        hi = datetime.date.fromordinal(1000000)
        #Nov. 28, 2738
        if self.r_min:
            lo = parsing_tools.date_from_iso(self.r_min)
        if self.r_max:
            hi = parsing_tools.date_from_iso(self.r_max)
        entry_count = len(proposed_response)
        if entry_count < 1:
            result = False
        else:
            if entry_count > 1 and self.user_can_add is False:
                result = False
        if result:
            for entry in proposed_response:
                n = parsing_tools.date_from_iso(entry)
                if lo <= n <= hi:
                    continue
                else:
                    result = False
                    break
        return result
Example #2
0
    def get_last_snapshot(self, ref_date=None):
        """


        CapTable.get_last_snapshot() -> Snapshot

        --``ref_date`` is datetime date, or string "YYYY-MM-DD"

        Method returns the most recent Snapshot on or before a certain date.
        Date defaults to today() if not specified
        """
        if not ref_date:
            ref_date = date.today()
        elif isinstance(ref_date, str):
            ref_date = date_from_iso(ref_date)

        last_key = None
        for key in self.snapshots:
            if key <= ref_date:
                if not last_key:
                    last_key = key
                elif key > last_key:
                    last_key = key

        if last_key:
            return self.snapshots[last_key]
        else:
            return None
Example #3
0
    def get_line(self, **kargs):
        """

        Model.get_line() -> LineItem

        --``bbid`` is bbid of line
        --``buid`` is BU id

        Method finds a LineItem matching the locator.
        """
        period_end = kargs['period']
        bbid = ID.from_database(kargs['bbid']).bbid
        buid = ID.from_database(kargs['buid']).bbid
        fins_attr = kargs['financials_attr']
        if period_end:
            key = (
                kargs.get('resolution', 'monthly'),
                kargs.get('name', 'default'),
            )
            time_line = self.timelines[key]
            if isinstance(period_end, str):
                period_end = date_from_iso(period_end)
            period = time_line[period_end]
        else:
            period = self.time_line.current_period
        financials = self.get_financials(buid, period)
        line = financials.find_line(bbid, fins_attr)
        return line
Example #4
0
    def from_database(cls, portal_data, target=None):
        """

        Parameters.from_database(portal_data) -> Parameters

        --``target`` if given, will filter the rows based on 'target' field

        **CLASS METHOD**

        Method extracts Parameters from portal_data.
        """
        result = cls()
        for data in portal_data:
            if target and data.get('target') and data['target'] != target:
                continue
            keyhold = result
            keypath = data['key_path'].split('\n')
            while keypath:
                k = keypath.pop(0)
                if keypath:
                    keyhold = keyhold.setdefault(k, cls())
                else:
                    # cast value to the stored type
                    typ = data['value_type']
                    if typ == 'date':
                        keyhold[k] = date_from_iso(data['value'])
                    elif typ == 'timedelta':
                        if isinstance(data['value'], str):
                            keyhold[k] = timedelta(int(data['value']))
                        else:
                            keyhold[k] = data['value']
                    else:
                        keyhold[k] = locate(typ)(data['value'])

        return result
Example #5
0
    def from_database(cls, data):
        if isinstance(data['ref_date'], str):
            ref_date = date_from_iso(data['ref_date'])
        else:
            ref_date = data['ref_date']

        if isinstance(data['created_date'], str):
            created_date = date_from_iso(data['created_date'])
        else:
            created_date = data['created_date']

        result = cls(ref_date, created_date=created_date)

        for flat_rec in data['records']:
            record = Record.from_database(flat_rec)
            key = (record.owner_name, record.round_name)
            result.records[key] = record

        return result
Example #6
0
    def from_database(cls, portal_data):
        new = cls()
        new._birth_event_names = set(portal_data['birth_event_names'])
        new._death_event_names = set(portal_data['death_event_names'])
        new._ref_date = date_from_iso(portal_data['ref_date']) if \
            portal_data['ref_date'] else portal_data['ref_date']

        event_list = portal_data['events']
        if event_list:
            for event in event_list:
                dt = event['date']
                event_date = date_from_iso(dt) if isinstance(dt, str) else dt
                new.events[event['event']] = event_date

        new.gestation = datetime.timedelta(portal_data['gestation'])
        new.life_span = datetime.timedelta(portal_data['life_span'])
        new.percent_maturity = portal_data['percent_maturity']
        new.percent_old_age = portal_data['percent_old_age']

        return new
Example #7
0
    def check_response(self,proposed_response):
        """


        DateRangeInput.check_response(proposed_response) -> None


        Method checks for response length (must be 1 unless user_can_add)
        and that for each (a,b) item in response, r_min <= a <= b <= r_max.
        """
        result = True
        lo = datetime.date.fromordinal(1)
        hi = datetime.date.fromordinal(1000000)
        #Nov. 28, 2738
        if self.r_min:
            lo = parsing_tools.date_from_iso(self.r_min)
        if self.r_max:
            hi = parsing_tools.date_from_iso(self.r_max)
        entry_count = len(proposed_response)
        if entry_count < 1:
            result = False
        else:
            if entry_count > 1 and self.user_can_add == False:
                result = False            
        if result:            
            for entry in proposed_response:
                #entry is "YYYY-MM-DD, YYYY-MM-DD", with 0 or more whitespace
                #between and around the elements
                (a, b) = entry.split(",")
                date_a = parsing_tools.date_from_iso(a)
                date_b = parsing_tools.date_from_iso(b)
                if lo <= date_a <= date_b <= hi:
                    continue
                else:
                    result = False
                    break
        return result
Example #8
0
    def from_database(cls, portal_data, model, **kargs):
        """

        TimeLine.from_database(portal_data) -> TimeLine

        **CLASS METHOD**

        Method extracts a TimeLine from portal_data.
        """
        if isinstance(portal_data['period_start'], str):
            period_start = date_from_iso(portal_data['period_start'])
            period_end = date_from_iso(portal_data['period_end'])
        else:
            period_start = portal_data['period_start']
            period_end = portal_data['period_end']

        new = cls(period_start, period_end)

        new.complete = portal_data.get('complete') or False
        new.periods_used = portal_data.get('periods_used') or 1

        new.parameters.add(
            Parameters.from_database(portal_data['parameters'],
                                     target='parameters'))

        new._inflate_line_storage(portal_data['financials_values'])

        # convert unit_parameters keys to UUID
        for k, v in Parameters.from_database(portal_data['unit_parameters'],
                                             target='unit_parameters').items():
            new.unit_parameters.add({ID.from_database(k).bbid: v})

        time_line = kargs['time_line']
        time_line.add_period(new)

        return new
Example #9
0
    def from_database(cls, portal_data, model, **kargs):
        """

        TimeLine.from_database(portal_data) -> TimeLine

        **CLASS METHOD**

        Method extracts a TimeLine from portal_data.
        """
        key = tuple(portal_data[k] for k in ('resolution', 'name'))
        new = cls(
            model,
            resolution=portal_data['resolution'],
            name=portal_data['name'],
        )
        new.master = model.taxo_dir

        if portal_data['interval'] is not None:
            new.interval = portal_data['interval']
        if portal_data['ref_date']:
            new.ref_date = portal_data['ref_date']
            if isinstance(new.ref_date, str):
                new.ref_date = date_from_iso(new.ref_date)
        if portal_data['has_been_extrapolated'] is not None:
            new.has_been_extrapolated = portal_data['has_been_extrapolated']
        if portal_data['parameters'] is not None:
            new.parameters = Parameters.from_database(
                portal_data['parameters'])

        for data in portal_data['periods']:
            period = TimePeriod.from_database(
                data,
                model=model,
                time_line=new,
            )

        return new
Example #10
0
    def from_database(cls, portal_model):
        """

        Model.from_database(portal_model) -> Model

        **CLASS METHOD**

        Method extracts a Model from portal_model.

        Method expects ``portal_model`` to be nested dictionary containing
        all necessary information for rebuilding a Model instance.
        """
        name = portal_model.pop('name', None)

        M = cls(name)
        M.portal_data.update(portal_model)

        business_name = portal_model.get("business_name", None)
        del portal_model

        tags = M.portal_data.pop('tags')
        if tags:
            M.tags = Tags.from_database(tags)

        # set basic attributes
        M._processing_status = M.portal_data.pop('processing_status', 'intake')

        M._ref_date = M.portal_data.pop('ref_date')
        if isinstance(M._ref_date, str):
            M._ref_date = date_from_iso(M._ref_date)

        M._started = M.portal_data.pop('started')
        M.topic_list = M.portal_data.pop('topic_list', list())
        M.transcript = M.portal_data.pop('transcript', list())
        M.report_summary = M.portal_data.pop('report_summary', None)
        M._fiscal_year_end = M.portal_data.pop('fiscal_year_end')

        scen = M.portal_data.pop('scenarios')
        if scen is not None:
            M.scenarios = scen

        link_list = list()
        # first deserialize BusinessUnits into directory
        temp_directory = dict()
        bu_list = M.portal_data.pop('business_units', list())
        reg_bus = [bu for bu in bu_list if not bu.get('taxonomy', False)]
        taxo_bus = [bu for bu in bu_list if bu.get('taxonomy', False)]

        for flat_bu in reg_bus:
            rich_bu = BusinessUnit.from_database(flat_bu, link_list)
            rich_bu.relationships.set_model(M)
            bbid = ID.from_database(flat_bu['bbid']).bbid
            temp_directory[bbid] = rich_bu

        # now rebuild structure
        company_id = M.portal_data.pop('company', None)
        if company_id:
            company_id = ID.from_database(company_id).bbid

            def build_bu_structure(seed, directory):
                component_list = seed.components
                seed.components = None
                seed._set_components()

                for component_id in component_list:
                    sub_bu = directory[component_id]
                    seed.add_component(sub_bu)
                    build_bu_structure(sub_bu, directory)

            top_bu = temp_directory[company_id]
            build_bu_structure(top_bu, temp_directory)
            M.set_company(top_bu)

        # TaxoDir
        if taxo_bus:
            M.taxo_dir = TaxoDir.from_database(taxo_bus, M, link_list)

        # Fix Links
        if link_list:
            for link in link_list:
                targ_id = link.target

                if targ_id in M.bu_directory:
                    link.target = M.bu_directory[targ_id]
                elif targ_id in M.taxo_dir.bu_directory:
                    link.target = M.taxo_dir.bu_directory[targ_id]
                else:
                    c = "ERROR: Cannot locate link target: " + targ_id.hex
                    raise LookupError(c)

        # Taxonomy
        data = M.portal_data.pop('taxonomy', None)
        if data:
            M.taxonomy = Taxonomy.from_database(data, M.taxo_dir)

        # Target
        target_id = M.portal_data.pop('target', None)
        if target_id:
            target_id = ID.from_database(target_id).bbid
            try:
                M.target = M.bu_directory[target_id]
            except KeyError:
                M.target = M.taxo_dir.bu_directory[target_id]

        # reinflate timelines
        timeline_data = M.portal_data.pop('timelines', list())
        if timeline_data:
            timelines = {}
            for data in timeline_data:
                key = (data['resolution'], data['name'])
                timelines[key] = TimeLine.from_database(data, model=M)
            M.timelines = timelines

        # reinflate drivers
        drivers = M.portal_data.pop('drivers', list())
        if drivers:
            M.drivers = DriverContainer.from_database(drivers)

        if business_name and business_name != M.title:
            M.set_name(business_name)

        M.portal_data.pop('title')
        M.portal_data.pop('bbid')

        return M