Exemplo n.º 1
0
    def __init__(self, unit: str):
        """Object that represents path to unit's base folder

        Parameters
        ---
        Unit: string

        Examples
        -------
        >>> uf = UnitFolder(unit='F301')
        >>> uf.p_unit
        '/Volumes/Public/Fort Hills/02. Equipment Files/1. 980E Trucks/F301 - A40017'
        """

        # get unit's row from unit table, save to self attributes
        m = db.get_df_unit().loc[unit]
        f.copy_dict_attrs(m=m, target=self)

        modelpath = self.get_modelpath()  # needs model and model_map
        unitpath = f'{unit} - {self.serial}'

        if not 'shovels' in self.minesite.lower():
            p_unit = cf.p_drive / f'{self.equippath}/{modelpath}/{unitpath}'
        else:
            # shovels doesn't want modelpath. Could make this a list of exclusions or something
            p_unit = cf.p_drive / f'{self.equippath}/{unitpath}'

        p_dls = p_unit / 'Downloads'
        p_dls_year = p_dls / str(dt.now().year)

        f.set_self(vars())
Exemplo n.º 2
0
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        col_db_startdate, col_db_enddate = 'ShiftDate', 'ShiftDate'

        df_week = qr.df_period(freq='week')
        df_month = qr.df_period(freq='month')

        d = dt.now() + delta(days=-6)
        default_week = df_week[df_week.start_date < d].iloc[
            -1, :].name  # index name

        d = dt.now() + delta(days=-30)
        default_month = df_month[df_month.start_date < d].iloc[
            -1, :].name  # index name

        f.set_self(vars())

        self.add_input(field=InputField(text='Week', default=default_week),
                       items=df_week.index,
                       checkbox=True,
                       cb_enabled=False)
        self.add_input(field=InputField(text='Month', default=default_month),
                       items=df_month.index,
                       checkbox=True,
                       cb_enabled=False)

        self.add_features(['start_date', 'end_date', 'unit'])
        self.insert_linesep(i=2)
Exemplo n.º 3
0
    def __init__(self,
                 unit,
                 component,
                 modifier=None,
                 n=10,
                 d_lower=None,
                 d_upper=None,
                 **kw):
        super().__init__(**kw)
        a, b = self.a, self.b
        cols = [
            a.unit, a.component_id, a.modifier, a.sample_date, a.unit_smr,
            a.oil_changed, a.sample_rank, a.test_results, a.test_flags
        ]

        q = Query \
            .from_(a) \
            .where(
                (a.unit == unit) &
                (a.component_id == component)) \
            .orderby(a.sample_date, order=Order.desc)

        if d_lower is None:
            q = q.top(n)

            if not d_upper is None:
                q = q.where(a.sample_date <= d_upper)

        else:
            q = q.where(a.sample_date >= d_lower)

        if not modifier is None:
            q = q.where(a.modifier == modifier)

        f.set_self(vars())
Exemplo n.º 4
0
    def __init__(self, table_name: str, filter_vals: dict = None, **kw):
        super().__init__(select_tablename=table_name, **kw)

        # get dbtable obj to inspect for keys
        keys = dbt.get_dbtable_keys(table_name)
        keys = [key.lower() for key in keys]

        a = T(table_name)

        q = Query.from_(a) \
            .select(*keys)

        f.set_self(vars())

        # helper to add filter vals eg {'unit': 'F301'}
        if isinstance(filter_vals, dict):
            field = list(filter_vals.keys())[0]
            val = filter_vals[field]

            field_ = a.field(field)
            if isinstance(val, (list, tuple)):
                # key: list of vals
                self.fltr.add(ct=field_.isin(val))
            else:
                # single key: val
                self.fltr.add(vals=filter_vals)
Exemplo n.º 5
0
    def __init__(self, **kw) -> None:
        doc = Document()
        font_name = 'Calibri'
        font_size = Pt(10)

        font_props = dict(size=font_size, name=font_name)

        tables = {}

        f.set_self(vars())

        # set default paragraph font styles
        self.set_style_props('Normal', font_props)
        self.set_style_props('No Spacing', font_props)
        self.set_style_props('Normal Table', font_props)

        # small font table
        s = doc.styles.add_style('SmallFont', WD_STYLE_TYPE.PARAGRAPH)
        s.base_style = doc.styles['No Spacing']
        self.set_style_props('SmallFont', dict(size=Pt(6)))

        self.doc.styles['Normal'].paragraph_format.line_spacing = 1
        self.doc.styles['Heading 1'].paragraph_format.space_before = Pt(6)

        self.set_margins()
Exemplo n.º 6
0
    def __init__(self, da=None, **kw):
        super().__init__(da=da, **kw)
        a = self.a
        date_col = 'ShiftDate'
        ct_allopen = a.CategoryAssigned.isnull() | a.SMS.isnull(
        ) | a.Suncor.isnull()
        assigned = Case().when(ct_allopen, 0).else_(1).as_('Assigned')
        self.cols.append(assigned)

        f.set_self(vars())

        # set cols, func, and da for stylemap functions
        cols_gradient = ['Total', 'SMS', 'Suncor']
        self.stylemap_cols |= {
            col: dict(cols=cols_gradient, func=self.background_gradient)
            for col in cols_gradient
        }

        # reapplied to 'Unit' when column filtered with 'filter_assigned'. could also do sorting?
        self.stylemap_cols |= {
            'Unit':
            dict(cols=['Unit'],
                 func=st.pipe_highlight_alternating,
                 da=dict(subset=['Unit'], color='maroon', theme=self.theme))
        }
Exemplo n.º 7
0
    def __init__(
            self,
            ftype: str,
            max_depth: int = 6,
            d_lower: dt = None):
        """
        Parameters
        ----------
        ftype : str
            file type to collect (dsc, fault | plm | tr3)
        max_depth : int, optional
            max depth to recurse, default 5
        d_lower : dt, optional
            date to filter file date created, default 2016-01-01
        """
        if not ftype in self.keys:
            raise ValueError(f'Incorrect ftype "{ftype}", must be in {self.keys}')

        if d_lower is None:
            d_lower = dt.now() + delta(days=-180)

        cfg = self.cfg.get(ftype)
        expr_exclude = self.make_re_exclude(lst=cfg.get('exclude'))
        expr_find = cfg.get('find')

        f.set_self(vars())
Exemplo n.º 8
0
    def __init__(
            self,
            name: str = None,
            key: str = None,
            val: Any = None,
            max_width: int = None,
            *args, **kw):
        super().__init__(*args, **kw)

        # loop base classes till find a match in obj_vals
        for cls in inspect.getmro(self.__class__):
            type_ = obj_vals.get(cls, None)
            if not type_ is None:
                parentclass = cls  # eg PyQt6.QtWidgets.QTextEdit, (class object not str)
                break

        getter, setter = type_[0], type_[1]  # currentText, setCurrentText
        _settings_key = key
        f.set_self(vars(), exclude=('key', 'val'))

        # set value from constructor
        if not val is None:
            self.val = val

        # changed signal
        getattr(self, type_[2]).connect(self._state_changed)

        if not name is None:
            self.set_name(name=name)

        if not max_width is None:
            self.setMaximumWidth(max_width)
Exemplo n.º 9
0
    def __init__(self,
                 table_widget: 'TableWidget' = None,
                 mw: 'QMainWindow' = None,
                 _driver: WebDriver = None,
                 headless: bool = False,
                 use_user_settings: bool = True,
                 download_dir: Path = None,
                 **kw):

        # driver will set_self and overwrite self.driver property
        if 'driver' in vars().keys():
            raise RuntimeError('Init with "_driver", not "driver"!')

        download_dir = download_dir or Path.home() / 'Downloads'
        if isinstance(download_dir, str):
            download_dir = Path(download_dir)

        pages = {}
        if not table_widget is None:
            mw = table_widget.mainwindow

        # if specific error, may need to exit with a nice message and suppress all else
        # NOTE loose end > may need a way to turn this back on if object is to be reused
        suppress_errors = False
        f.set_self(vars())

        er.wrap_all_class_methods_static(obj=self,
                                         err_func=self.e,
                                         exclude='driver')
Exemplo n.º 10
0
    def __init__(self, **kw):
        super().__init__(**kw)
        rp.FailureReport.__init__(self, rep_type='word', **kw)

        p = cf.desktop / 'component_failure.docx'

        f.set_self(vars())
Exemplo n.º 11
0
    def __init__(self, title, report, **kw):

        report.sections[title] = self  # add self to parent report
        sub_sections = {}
        d_rng, d_rng_ytd, minesite = report.d_rng, report.d_rng_ytd, report.minesite

        f.set_self(vars())
Exemplo n.º 12
0
    def __init__(self,
                 name: str,
                 period_type='week',
                 minesite='FortHills',
                 **kw):
        """Create availability report pdf

        Parameters
        ----------
        name : str
            Period name, week = '2021-34', month = '2021-02'
        period_type : str, optional
            default 'week'
        minesite : str, optional
            default 'FortHills'
        """
        super().__init__()
        df = qr.df_period(freq=period_type, n_years=5)
        d_rng = df.loc[name, 'd_rng']
        name_title = df.loc[name, 'name_title']
        email_col_name = 'AvailReports'

        signatures = [
            'Suncor Reliability', 'Suncor Maintenance', 'SMS', 'Komatsu'
        ]

        title = f'Suncor Reconciliation Report - {minesite} - {period_type.title()}ly - {name_title}'
        f.set_self(vars())  # , exclude='d_rng'

        self.load_sections('AvailStandalone')
        self.add_items(['title_page', 'exec_summary', 'table_contents'])

        if period_type == 'month':
            self.add_items(['signature_block'])
Exemplo n.º 13
0
    def __init__(self,
                 unit: str,
                 dateadded: dt,
                 workorder: str,
                 title: str,
                 uid: int = None,
                 data_model=None,
                 irow: int = None,
                 table_widget=None,
                 **kw):
        super().__init__(unit=unit, **kw)
        # data_model only needed to set pics in table view
        self.dt_format = '%Y-%m-%d'

        year = dateadded.year

        wo_blank = 'WO' + ' ' * 14
        if not workorder or 'nan' in str(workorder).lower():
            workorder = wo_blank

        # confirm unit, date, title exist?
        folder_title = self.get_folder_title(unit, dateadded, workorder, title)

        p_base = self.p_unit / f'Events/{year}'
        _p_event = p_base / folder_title
        p_event_blank = p_base / self.get_folder_title(unit, dateadded,
                                                       wo_blank, title)

        f.set_self(vars())
Exemplo n.º 14
0
    def __init__(self, **kw):
        super().__init__(**kw)
        # url = 'https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer/' \
        #     + 'archive/refs/tags/2021-04-29.zip'
        p_root = cf.p_gtk

        f.set_self(vars())
Exemplo n.º 15
0
    def __init__(self, **kw):
        super().__init__(**kw)
        a = self.select_table
        isNumeric = cfn('ISNUMERIC', ['val'])
        left = cfn('LEFT', ['val', 'num'])

        c, d = pk.Tables('UnitSMR', 'EquipType')

        days = fn.DateDiff(PseudoColumn('day'), a.DeliveryDate, fn.CurTimestamp())
        remaining = Case().when(days <= 365, 365 - days).else_(0).as_('Remaining')
        remaining2 = Case().when(days <= 365 * 2, 365 * 2 - days).else_(0)

        ge_remaining = Case().when(isNumeric(left(a.Model, 1)) == 1, remaining2).else_(None).as_('GE_Remaining')

        b = c.select(c.Unit, fn.Max(c.SMR).as_('CurrentSMR'), fn.Max(c.DateSMR).as_('DateSMR')).groupby(c.Unit).as_('b')

        cols = [a.MineSite, a.Customer, d.EquipClass, a.Model, a.Serial, a.Unit,
                b.CurrentSMR, b.DateSMR, a.DeliveryDate, remaining, ge_remaining]

        q = Query.from_(a) \
            .left_join(b).on_field('Unit') \
            .left_join(d).on_field('Model') \
            .orderby(a.MineSite, a.Model, a.Unit)

        f.set_self(vars())

        # NOTE lots of duplication with this pattern btwn avail/ac inspect/units/comp co
        # can't remember how everything works and don't want to dig into it
        self.stylemap_cols |= {'Model': dict(
            cols=['Model'],
            func=st.pipe_highlight_alternating,
            da=dict(
                subset=['Model'],
                color='maroon',
                theme=self.theme))}
Exemplo n.º 16
0
    def __init__(self, **kw):
        import kaleido as kal
        super().__init__(v_min=kal.__version__, **kw)
        # url_github = 'https://api.github.com/repos/plotly/Kaleido/releases/latest' # not used now
        p_dest = ''
        p_root = self.p_ext / 'kaleido'

        f.set_self(vars())
Exemplo n.º 17
0
    def __init__(self, parent=None, **kw):
        super().__init__(parent=parent, **kw)
        a = self.select_table
        cols = [a.UserName, a.Email, a.LastLogin, a.Ver, a.Domain, a.UserGroup,
                a.MineSite, a.odbc_driver, a.install_dir]
        q = Query.from_(a) \
            .orderby(a.LastLogin, order=Order.desc)

        f.set_self(vars())
Exemplo n.º 18
0
    def __init__(self, theme='dark'):
        super().__init__(theme=theme)
        a, b = pk.Tables('viewFactoryCampaign', 'UnitID')

        cols = [a.FCNumber, a.Unit, b.MineSite, a.Subject, a.Complete, a.Classification, a.ReleaseDate, a.ExpiryDate]
        q = Query.from_(a).select(*cols) \
            .left_join(b).on_field('Unit')

        f.set_self(vars())
Exemplo n.º 19
0
    def __init__(self, da=None, **kw):
        super().__init__(da=da, **kw)
        a, b = pk.Tables('Downtime', 'UnitID')
        q = Query.from_(a) \
            .inner_join(b).on_field('Unit')

        self.default_dtypes.update(
            **f.dtypes_dict('float64', ['Total', 'SMS', 'Suncor']))

        f.set_self(vars())
Exemplo n.º 20
0
    def __init__(self, fltr=None, login=None):
        _samples = []
        _samples_full = []  # save all sample history

        if login is None:
            login = CredentialManager(name='fluidlife', gui=False).static_creds

        format_date = lambda x: x.strftime('%Y-%m-%d-00:00:00')

        f.set_self(vars())
Exemplo n.º 21
0
    def __init__(self):
        wb = xl.load_workbook(p)
        ws = wb['ActLog']  # default table
        tbl = ws.tables['actlog']
        max_row = ws.max_row  # type: int
        new_row = max_row + 1

        m_formula_cols = dict(actlog=2)

        f.set_self(vars())
Exemplo n.º 22
0
    def __init__(self, p: Path = None, sql=None, **kw):
        super().__init__(**kw)
        """
        Parameters
        ----------
        p : Path
            Path to .sql file
        """

        f.set_self(vars())
Exemplo n.º 23
0
    def __init__(self, **kw):
        super().__init__(**kw)
        a, b = self.a, self.b

        cols = [a.UID, a.StatusWO, a.WarrantyYN, a.WorkOrder, a.Seg, a.SuncorWO, a.SuncorPO, b.Model, a.Unit, b.Serial, a.Title, a.PartNumber, a.OrderParts, a.SMR, a.DateAdded, a.DateCompleted, a.CreatedBy, a.ComponentCO, a.Pictures, a.WOComments]  # noqa

        q = self.q \
            .orderby(a.DateAdded, a.Unit)

        f.set_self(vars())
Exemplo n.º 24
0
    def __init__(self):
        is_win = cf.is_win
        _folders = None
        _wo_folder = None

        if is_win:
            client = win32.Dispatch('Outlook.Application')
        else:
            client = app('Microsoft Outlook')

        f.set_self(vars())
Exemplo n.º 25
0
    def __init__(self, **kw):
        super().__init__(**kw)
        a, b = self.a, self.b

        cols = [a.UID, a.StatusTSI, a.DateAdded, a.DateTSISubmission, a.TSINumber, a.WorkOrder,
        b.Model, a.Unit, b.Serial, a.Title, a.SMR, a.ComponentSMR, a.TSIPartName, a.PartNumber, a.SNRemoved, a.FailureCause, a.TSIAuthor, a.Pictures, a.KAPhenomenon, a.KAComponentGroup, a.TSIDetails]  # noqa

        q = self.q \
            .orderby(a.DateAdded, a.Unit)

        f.set_self(vars())
Exemplo n.º 26
0
    def __init__(self, **kw):
        super().__init__(**kw)
        a, b = self.a, self.b

        cols = [a.UID, a.PassoverSort, a.StatusEvent, a.Unit, a.Title, a.Description, a.FailureCause,
                a.DateAdded, a.DateCompleted, a.IssueCategory, a.SubCategory, a.Cause, a.CreatedBy,
                a.TimeCalled, a.StatusTSI]

        q = self.q \
            .orderby(a.DateAdded, a.Unit)

        f.set_self(vars())
Exemplo n.º 27
0
    def __init__(
            self,
            ftype: str,
            d_lower: dt = dt(2020, 1, 1),
            max_depth: int = 4,
            search_folders: list = ['downloads']):

        self.collected_files = []
        self.collected_files_dict = {}
        self.folder_search = FolderSearch(ftype=ftype, d_lower=d_lower, max_depth=max_depth)

        f.set_self(vars())
Exemplo n.º 28
0
    def __init__(self, **kw):
        """Full table for app display/editing, NOT single list for emailing"""
        super().__init__(**kw)
        a = self.select_table
        cols = [a.UserGroup, a.MineSite, a.Email, a.Passover, a.WORequest, a.FCCancelled, a.PicsDLS,
                a.PRP, a.FCSummary, a.TSI, a.RAMP, a.Service, a.Parts, a.AvailDaily, a.AvailReports,
                a.FleetReport, a.SMRReport]

        q = Query.from_(a) \
            .orderby(a.UserGroup, a.MineSite, a.Email)

        f.set_self(vars())
Exemplo n.º 29
0
    def __init__(self, ask_token: bool = True, **kw):
        super().__init__(**kw)
        self.pages |= dict(
            home='https://workremote.suncor.com',
            citrix='https://workremote.suncor.com/+CSCO' +
            '+0075676763663A2F2F666861666F702E6668617062652E70627A++/Citrix/CitrxPRD-CGYWeb/'
        )
        token = None

        username, password = CredentialManager('sap').load()

        f.set_self(vars())
Exemplo n.º 30
0
    def __init__(self, **kw):
        super().__init__(**kw)

        a, b = Tables('Parts', 'EquipType')
        cols = [a.star, b.ModelBase]
        cols = [b.ModelBase, a.Model, a.PartNo, a.PartName, a.PartNameAlt]

        q = Query.from_(a) \
            .select(*cols) \
            .left_join(b).on_field('Model')

        f.set_self(vars())