Exemplo n.º 1
0
    def close_positions(self) -> int:
        errors: List[Exception] = []
        try:
            is_tmrw_valid: bool = self.__alpaca_client.is_tmrw_valid()
            if not is_tmrw_valid:
                LogUtils.warning('Tmrw is not a valid trade date')
                raise BadRequestException('Date',
                                          DateUtils.to_string(date.today()))

            req: GetTradeOrdersRequest = GetTradeOrdersRequest()
            req.exact_status = AppConsts.ORDER_STATUS_IN_POSITION
            orders: List[TradeOrderCustom] = self.get_trade_orders(req)

            if not orders:
                LogUtils.debug('No positions')

            for order in orders:
                try:
                    LogUtils.debug('Check position for = {0}'.format(
                        order.symbol_master.symbol))
                    spd: StockPriceDaily = self.__stock_service.get_last_single_stock_price_daily(
                        order.symbol_master.id)
                    if not spd:
                        LogUtils.warning('No Stock Price Found')
                        raise NotFoundException('SPD', 'symbol_id',
                                                order.symbol_master.id)

                    LogUtils.debug('Last close price = {0}'.format(
                        spd.close_price))
                    # is_exit: bool = (spd.close_price > order.trade_order.target_price
                    #                  or spd.close_price < order.trade_order.stop_loss)
                    if True:  # To-do: fix this to use strategy service. is_exit:

                        LogUtils.debug('Close position for = {0}'.format(
                            order.symbol_master.symbol))

                        resp: Order = self.__alpaca_client.submit_order(
                            symbol=order.symbol_master.symbol,
                            qty=order.trade_order.actual_qty,
                            action=AppConsts.ACTION_SELL
                            if order.trade_order.action == AppConsts.ACTION_BUY
                            else AppConsts.ACTION_BUY)
                        if resp:
                            org: TradeOrder = BaseService._get_by_id(
                                TradeOrder, order.trade_order.id)
                            if not org:
                                LogUtils.warning('Order not found.')
                                raise NotFoundException(
                                    'TradeOrder', 'id', order.trade_order.id)
                            org.exit_alpaca_id = resp.id
                            org.status = AppConsts.ORDER_STATUS_SUBMITTED_EXIT
                            org.modified = datetime.now()
                            BaseService._update()
                        else:
                            raise Exception('Close Position Error.')

                except Exception as ex:
                    LogUtils.error('Close Position Error', ex)
                    errors.append(ex)

        except Exception as ex:
            LogUtils.error('Close Position Error', ex)
            errors.append(ex)
        finally:
            self.__email_client.send_html(
                subject=AppConsts.EMAIL_SUBJECT_CLOSE_POSITIONS,
                template_path=AppConsts.TEMPLATE_PATH_CLOSE_POSITIONS,
                model={'errors': errors})
            return 1
class PropertyAvailibiltyTypeService():
    def __init__(self):
        self.base_service = BaseService()
        self.db = BaseService.DbFilePath
        self.ec = self.base_service.Entity()
        self.util_common = self.base_service.UtilCommon()
        self.PropertyAvailibiltyType = self.ec.InitEntityClass(
            'PropertyAvailibiltyType')
        self.service_account = AccountService()

    def get_propavailtype_all(self):
        with self.base_service.DbContext() as __context:
            result = __context.table(self.PropertyAvailibiltyType).select_all()
            return result

        return None

    def get_propavailtype_byId(self, idValue):
        with self.base_service.DbContext() as __context:
            result = __context.table(
                self.PropertyAvailibiltyType).select_by_id(idValue)
            return result

        return None

    def get_propavailtype_byName(self, searchText):
        with self.base_service.DbContext() as __context:
            conditions = ''' Name like '%{0}%' '''.format(searchText)
            result = __context.table(
                self.PropertyAvailibiltyType).select_by(conditions)
            return result

        return None

    def add_propavailtype(self, paramModel):
        if (paramModel is not None and inspect.isclass(type(paramModel))
                and type(paramModel) == self.PropertyAvailibiltyType):
            with self.base_service.DbContext() as __context:

                modelLastPropertyAvailibiltyType = __context.table(
                    self.PropertyAvailibiltyType
                ).select_lastrecord(
                )  # get last record of PropertyAvailibiltyType table to increment IndexNo

                # create new object of PropertyAvailibiltyType
                modelPropertyAvailibiltyType = self.PropertyAvailibiltyType()
                modelPropertyAvailibiltyType.PropAvailTypeId = modelLastPropertyAvailibiltyType.PropAvailTypeId + 1
                modelPropertyAvailibiltyType.Name = hasattr(
                    paramModel, 'Name') and paramModel.Name or None
                modelPropertyAvailibiltyType.Description = hasattr(
                    paramModel,
                    'Description') and paramModel.Description or None
                modelPropertyAvailibiltyType.SortOrder = hasattr(
                    paramModel, 'SortOrder') and paramModel.SortOrder or None
                modelPropertyAvailibiltyType.IsAvailable = hasattr(
                    paramModel, 'IsAvailable') and paramModel.IsAvailable or 1

                # insert to db
                result = __context.table(
                    self.PropertyAvailibiltyType).insert_by_model(
                        modelPropertyAvailibiltyType)
                if result:
                    return modelPropertyAvailibiltyType

        return None

    def update_propavailtype(self, paramModel):
        if (paramModel is not None and inspect.isclass(type(paramModel))
                and type(paramModel) == self.PropertyAvailibiltyType):

            modelPropertyAvailibiltyTypeFromDb = self.get_propavailtype_byId(
                paramModel.PropAvailTypeId)

            if (modelPropertyAvailibiltyTypeFromDb is not None):

                modelPropertyAvailibiltyTypeFromDb.Name = hasattr(
                    paramModel, 'Name'
                ) and paramModel.Name or modelPropertyAvailibiltyTypeFromDb.Name
                modelPropertyAvailibiltyTypeFromDb.Description = hasattr(
                    paramModel, 'Description'
                ) and paramModel.Description or modelPropertyAvailibiltyTypeFromDb.Description
                modelPropertyAvailibiltyTypeFromDb.SortOrder = hasattr(
                    paramModel, 'SortOrder'
                ) and paramModel.SortOrder or modelPropertyAvailibiltyTypeFromDb.SortOrder
                modelPropertyAvailibiltyTypeFromDb.IsAvailable = hasattr(
                    paramModel, 'IsAvailable'
                ) and paramModel.IsAvailable or modelPropertyAvailibiltyTypeFromDb.IsAvailable

                with self.base_service.DbContext() as __context:
                    # update to db
                    result = __context.table(
                        self.PropertyAvailibiltyType).update_by_model(
                            modelPropertyAvailibiltyTypeFromDb)
                    if result:
                        return modelPropertyAvailibiltyTypeFromDb
        return None
Exemplo n.º 3
0
    def queue_positions(self) -> int:
        errors: List[Exception] = []
        try:
            is_tmrw_valid: bool = self.__alpaca_client.is_tmrw_valid()
            if not is_tmrw_valid:
                LogUtils.warning('Tmrw is not a valid trade date')
                raise BadRequestException('Date',
                                          DateUtils.to_string(date.today()))

            req: GetTradeOrdersRequest = GetTradeOrdersRequest()

            # If Sunday, check Friday's price.
            today: date = date.today()
            if today.weekday() == AppConsts.WEEKDAY_IDX_SUN:
                today = DateUtils.add_business_days(today, -1)
            req.created = today.strftime('%Y-%m-%d')

            req.exact_status = AppConsts.ORDER_STATUS_INIT
            orders: List[TradeOrderCustom] = self.get_trade_orders(req)

            req_to_ignore: GetTradeOrdersRequest = GetTradeOrdersRequest()
            req_to_ignore.status = [
                AppConsts.ORDER_STATUS_SUBMITTED_ENTRY,
                AppConsts.ORDER_STATUS_IN_POSITION,
                AppConsts.ORDER_STATUS_SUBMITTED_EXIT,
                AppConsts.ORDER_STATUS_CANCELLED_EXIT
            ]
            orders_to_ignore: List[TradeOrderCustom] = self.get_trade_orders(
                req_to_ignore)
            symbols_to_ignore: List[str] = [
                o.symbol_master.symbol for o in orders_to_ignore
            ] if orders_to_ignore else []

            LogUtils.debug('symbols_to_ignore = {0}'.format(symbols_to_ignore))

            if not orders:
                LogUtils.debug('No orders suggested')

            shuffle(orders)
            prioritized_orders: List[TradeOrderCustom] = []
            for order in orders:
                if order.trade_order.strategy == AppConsts.STRATEGY_DOUBLE_BOTTOMS:
                    prioritized_orders.append(order)
            for order in orders:
                if order.trade_order.strategy == AppConsts.STRATEGY_DOUBLE_TOPS:
                    prioritized_orders.append(order)

            accnt: Account = self.__alpaca_client.get_account()
            capital: float = NumberUtils.to_floor(
                NumberUtils.to_float(accnt._raw['buying_power']) /
                2)  # 2 to trade everyday
            for order in prioritized_orders:
                try:
                    LogUtils.debug('Try symbol = {0}'.format(
                        order.symbol_master.symbol))

                    if order.symbol_master.symbol in symbols_to_ignore:
                        LogUtils.debug('Ignore for = {0}'.format(
                            order.symbol_master.symbol))
                        continue

                    cost: float = NumberUtils.to_float(
                        order.stock_price_daily.close_price *
                        order.trade_order.qty)

                    if cost > capital:
                        LogUtils.debug('Too expensive for = {0}'.format(
                            order.symbol_master.symbol))
                        continue
                    capital = capital - cost

                    resp: Order = self.__alpaca_client.submit_order(
                        symbol=order.symbol_master.symbol,
                        qty=order.trade_order.qty,
                        action=order.trade_order.action)
                    if resp:
                        org: TradeOrder = BaseService._get_by_id(
                            TradeOrder, order.trade_order.id)
                        if not org:
                            raise NotFoundException('TradeOrder', 'id',
                                                    order.trade_order.id)
                        org.alpaca_id = resp.id
                        org.status = AppConsts.ORDER_STATUS_SUBMITTED_ENTRY
                        org.order_type = AppConsts.ORDER_TYPE_MARKET
                        org.time_in_force = AppConsts.TIME_IN_FORCE_DAY
                        org.modified = datetime.now()
                        BaseService._update()

                except Exception as ex:
                    LogUtils.error('Queue Position Error', ex)
                    errors.append(ex)

        except Exception as ex:
            LogUtils.error('Queue Position Error', ex)
            errors.append(ex)
        finally:
            self.__email_client.send_html(
                subject=AppConsts.EMAIL_SUBJECT_QUEUE_POSITIONS,
                template_path=AppConsts.TEMPLATE_PATH_QUEUE_POSITIONS,
                model={'errors': errors})
            return 1
Exemplo n.º 4
0
    def sync_orders(self) -> int:
        errors: List[Exception] = []
        try:
            req: GetTradeOrdersRequest = GetTradeOrdersRequest()
            req.status = [
                AppConsts.ORDER_STATUS_SUBMITTED_ENTRY,
                AppConsts.ORDER_STATUS_SUBMITTED_EXIT
            ]
            orders: List[TradeOrderCustom] = self.get_trade_orders(req)

            if not orders:
                LogUtils.debug('No orders submitted')

            for order in orders:
                try:
                    LogUtils.debug('Sync order for = {0}'.format(
                        order.symbol_master.symbol))

                    resp: Order = None
                    if order.trade_order.status == AppConsts.ORDER_STATUS_SUBMITTED_ENTRY:
                        resp = self.__alpaca_client.get_order(
                            order.trade_order.alpaca_id)
                    elif order.trade_order.status == AppConsts.ORDER_STATUS_SUBMITTED_EXIT:
                        resp = self.__alpaca_client.get_order(
                            order.trade_order.exit_alpaca_id)

                    if resp:
                        org: TradeOrder = BaseService._get_by_id(
                            TradeOrder, order.trade_order.id)
                        if not org:
                            raise NotFoundException('TradeOrder', 'id',
                                                    order.trade_order.id)

                        if order.trade_order.status == AppConsts.ORDER_STATUS_SUBMITTED_ENTRY \
                                and resp.status == AppConsts.ALPACA_ORDER_STATUS_FILLED:
                            org.status = AppConsts.ORDER_STATUS_IN_POSITION
                            org.actual_qty = NumberUtils.to_int(
                                resp.filled_qty)
                            org.actual_entry_price = NumberUtils.to_float(
                                resp.filled_avg_price)
                            org.modified = datetime.now()
                            BaseService._update()
                        elif order.trade_order.status == AppConsts.ORDER_STATUS_SUBMITTED_ENTRY \
                                and resp.status == AppConsts.ALPACA_ORDER_STATUS_CANCELLED:
                            org.status = AppConsts.ORDER_STATUS_CANCELLED_ENTRY
                            org.modified = datetime.now()
                            BaseService._update()
                        elif order.trade_order.status == AppConsts.ORDER_STATUS_SUBMITTED_EXIT \
                                and resp.status == AppConsts.ALPACA_ORDER_STATUS_FILLED:
                            exit_price: StockPriceDaily = self.__stock_service.get_single_stock_price_daily(
                                order.symbol_master.id,
                                DateUtils.get_date(
                                    datetime.today().strftime('%Y-%m-%d'),
                                    '%Y-%m-%d'))
                            if exit_price:
                                org.exit_stock_price_daily_id = exit_price.id
                            org.status = AppConsts.ORDER_STATUS_COMPLETED
                            org.actual_exit_price = NumberUtils.to_float(
                                resp.filled_avg_price)
                            org.modified = datetime.now()
                            BaseService._update()
                        elif order.trade_order.status == AppConsts.ORDER_STATUS_SUBMITTED_EXIT \
                                and resp.status == AppConsts.ALPACA_ORDER_STATUS_CANCELLED:
                            org.status = AppConsts.ORDER_STATUS_CANCELLED_EXIT
                            org.modified = datetime.now()
                            BaseService._update()
                            raise Exception('Exit Error = {0}'.format(
                                resp.status))
                        else:
                            raise Exception('Sync Status = {0}'.format(
                                resp.status))
                    else:
                        raise NotFoundException('Alpaca Order', 'id',
                                                order.trade_order.alpaca_id)

                except Exception as ex:
                    LogUtils.error('Sync Orders Error', ex)
                    errors.append(ex)

        except Exception as ex:
            LogUtils.error('Sync Orders Error', ex)
            errors.append(ex)
        finally:
            self.__email_client.send_html(
                subject=AppConsts.EMAIL_SUBJECT_SYNC_ORDERS,
                template_path=AppConsts.TEMPLATE_PATH_SYNC_ORDERS,
                model={'errors': errors})
            return 1
Exemplo n.º 5
0
    def get_suggestions(self,
                        req: TradeSuggestionsRequest) -> List[TradeOrder]:
        if not req or not req.is_valid_model():
            raise BadRequestException()
        response: List[TradeOrder] = []

        # Init Symbols
        symbols: List[SymbolMaster] = self.__get_symbols__(req)

        # Init Prices
        date_to: date = date.today()
        date_from: date = date_to - timedelta(days=100)  # fix this
        prices: DataFrame = self.__get_prices__(symbols, date_from, date_to)

        # Do Base Preparation
        prices[AppConsts.CUSTOM_COL_PV] = prices[
            AppConsts.PRICE_COL_CLOSE] * prices[AppConsts.PRICE_COL_VOLUME]
        for s in symbols:
            prices = self.__calc_service.append_sma(
                prices=prices,
                index=[s.id],
                sma_period=AppConsts.ADV_PERIOD_DFLT,
                sma_column_name=AppConsts.CUSTOM_COL_ADV,
                target_column=AppConsts.PRICE_COL_VOLUME)
            prices = self.__calc_service.append_sma(
                prices=prices,
                index=[s.id],
                sma_period=AppConsts.ADPV_PERIOD_DFLT,
                sma_column_name=AppConsts.CUSTOM_COL_ADPV,
                target_column=AppConsts.CUSTOM_COL_PV)

        LogUtils.debug('Prices shape after base preparation={0}'.format(
            prices.shape))

        # region Init Service
        strategy_service: Any = self.__stock_service.get_strategy_service(
            req.strategy_type, req.strategy_request, symbols, prices)
        if not strategy_service or not strategy_service._is_valid_request():
            raise BadRequestException()
        strategy_service._do_preparations()

        LogUtils.debug('Prices shape after strategy preparation={0}'.format(
            prices.shape))
        # endregion

        LogUtils.debug(prices.info())

        # region Init Dates
        end_date: date = prices.index.get_level_values(
            AppConsts.PRICE_COL_DATE).max()
        LogUtils.debug('End_date={0}'.format(end_date))

        for symbol in symbols:
            LogUtils.debug('Start {0}'.format(symbol.symbol))

            has_price: bool = (symbol.id, end_date) in prices.index
            if not has_price:
                continue
            price: Series = prices.loc[symbol.id, end_date]

            adv: float = price.loc[AppConsts.CUSTOM_COL_ADV] if price.loc[
                AppConsts.CUSTOM_COL_ADV] > 0 else price.loc[
                    AppConsts.PRICE_COL_VOLUME]
            if adv < req.adv_min:
                continue
            adpv: float = price.loc[AppConsts.CUSTOM_COL_ADPV] if price.loc[
                AppConsts.CUSTOM_COL_ADPV] > 0 else price.loc[
                    AppConsts.CUSTOM_COL_PV]
            if adpv < req.adpv_min:
                continue

            has_entry_conditions: bool = strategy_service._has_entry_conditions(
                symbol.id, end_date)
            if not has_entry_conditions:
                continue
            no_of_shares: int = self.__stock_service.get_no_of_shares(
                req.current_capital, req.pct_risk_per_trade, req.volume_limit,
                price)
            if no_of_shares == 0:
                continue
            LogUtils.debug('Has Entry Condition = {0}'.format(symbol.symbol))

            now: datetime = datetime.now()
            order: TradeOrder = TradeOrder()
            order.stock_price_daily_id = price.loc[AppConsts.COL_ID]
            order.strategy = req.strategy_type
            order.status = AppConsts.ORDER_STATUS_INIT

            order.action = strategy_service._get_action()

            order.qty = no_of_shares
            # order.target_price = price.loc[AppConsts.CUSTOM_COL_DOUBLE_BOTTOMS_TARGET_PRICE]
            # order.stop_loss = price.loc[AppConsts.CUSTOM_COL_DOUBLE_BOTTOMS_STOP_LOSS]
            order.created = now
            order.modified = now
            response.append(order)
            if req.is_job:
                org: TradeOrder = BaseService._get_first(
                    TradeOrder, [
                        TradeOrder.stock_price_daily_id
                        == order.stock_price_daily_id, TradeOrder.strategy
                        == order.strategy
                    ])
                if not org:
                    BaseService._insert(order)

        return response
Exemplo n.º 6
0
class PropertyPricePolicyService():
    def __init__(self):
        self.base_service = BaseService()
        self.db = BaseService.DbFilePath
        self.ec = self.base_service.Entity()
        self.util_common = self.base_service.UtilCommon()
        self.PropertyPricePolicy = self.ec.InitEntityClass(
            'PropertyPricePolicy')
        self.service_account = AccountService()

    def get_proppricepol_all(self):
        with self.base_service.DbContext() as __context:
            result = __context.table(self.PropertyPricePolicy).select_all()
            return result

        return None

    def get_proppricepol_byId(self, idValue):
        with self.base_service.DbContext() as __context:
            result = __context.table(
                self.PropertyPricePolicy).select_by_id(idValue)
            return result

        return None

    def add_proppricepol(self, paramModel):
        if (paramModel is not None and inspect.isclass(type(paramModel))
                and type(paramModel) == self.PropertyPricePolicy):
            with self.base_service.DbContext() as __context:

                modelAdmin = self.service_account.get_accountAdmin(
                )  # get limit 1 result

                modelLastPropertyPricePolicy = __context.table(
                    self.PropertyPricePolicy
                ).select_lastrecord(
                )  # get last record of PropertyPricePolicy table to increment IndexNo

                # create new object of PropertyPricePolicy
                modelPropertyPricePolicy = self.PropertyPricePolicy()
                modelPropertyPricePolicy.PropPriceId = modelLastPropertyPricePolicy.PropPriceId + 1
                modelPropertyPricePolicy.PropertyItemId = hasattr(
                    paramModel,
                    'PropertyItemId') and paramModel.PropertyItemId or None
                modelPropertyPricePolicy.TimeUnitId = hasattr(
                    paramModel, 'TimeUnitId') and paramModel.TimeUnitId or None
                modelPropertyPricePolicy.CostActual = hasattr(
                    paramModel, 'CostActual') and paramModel.CostActual or None
                modelPropertyPricePolicy.PriceOrigin = hasattr(
                    paramModel,
                    'PriceOrigin') and paramModel.PriceOrigin or None
                modelPropertyPricePolicy.PercentageDiscount = hasattr(
                    paramModel, 'PercentageDiscount'
                ) and paramModel.PercentageDiscount or None
                modelPropertyPricePolicy.PriceActual = hasattr(
                    paramModel,
                    'PriceActual') and paramModel.PriceActual or None
                modelPropertyPricePolicy.DepositAmount = hasattr(
                    paramModel,
                    'DepositAmount') and paramModel.DepositAmount or None
                modelPropertyPricePolicy.DateApplied = hasattr(
                    paramModel,
                    'DateApplied') and paramModel.DateApplied or None
                modelPropertyPricePolicy.IsConfirmed = hasattr(
                    paramModel, 'IsConfirmed') and paramModel.IsConfirmed or 0

                modelPropertyPricePolicy.CreatedBy = modelAdmin.IndexNo
                modelPropertyPricePolicy.LastModifiedBy = modelAdmin.IndexNo
                modelPropertyPricePolicy.DateCreated = str(
                    self.util_common.currentDateTime())
                modelPropertyPricePolicy.DateLastModified = str(
                    self.util_common.currentDateTime())

                # insert to db
                result = __context.table(
                    self.PropertyPricePolicy).insert_by_model(
                        modelPropertyPricePolicy)
                if result:
                    return modelPropertyPricePolicy

        return None

    def update_proppricepol(self, paramModel):
        if (paramModel is not None and inspect.isclass(type(paramModel))
                and type(paramModel) == self.PropertyPricePolicy):

            modelPropertyPricePolicyFromDb = self.get_proppricepol_byId(
                paramModel.PropPriceId)

            if (modelPropertyPricePolicyFromDb is not None):

                modelAdmin = self.service_account.get_accountAdmin(
                )  # get limit 1 result

                modelPropertyPricePolicyFromDb.PropertyItemId = hasattr(
                    paramModel, 'PropertyItemId'
                ) and paramModel.PropertyItemId or modelPropertyPricePolicyFromDb.PropertyItemId
                modelPropertyPricePolicyFromDb.TimeUnitId = hasattr(
                    paramModel, 'TimeUnitId'
                ) and paramModel.TimeUnitId or modelPropertyPricePolicyFromDb.TimeUnitId
                modelPropertyPricePolicyFromDb.CostActual = hasattr(
                    paramModel, 'CostActual'
                ) and paramModel.CostActual or modelPropertyPricePolicyFromDb.CostActual
                modelPropertyPricePolicyFromDb.PriceOrigin = hasattr(
                    paramModel, 'PriceOrigin'
                ) and paramModel.PriceOrigin or modelPropertyPricePolicyFromDb.PriceOrigin
                modelPropertyPricePolicyFromDb.PercentageDiscount = hasattr(
                    paramModel, 'PercentageDiscount'
                ) and paramModel.PercentageDiscount or modelPropertyPricePolicyFromDb.PercentageDiscount
                modelPropertyPricePolicyFromDb.PriceActual = hasattr(
                    paramModel, 'PriceActual'
                ) and paramModel.PriceActual or modelPropertyPricePolicyFromDb.PriceActual
                modelPropertyPricePolicyFromDb.DepositAmount = hasattr(
                    paramModel, 'DepositAmount'
                ) and paramModel.DepositAmount or modelPropertyPricePolicyFromDb.DepositAmount
                modelPropertyPricePolicyFromDb.DateApplied = hasattr(
                    paramModel, 'DateApplied'
                ) and paramModel.DateApplied or modelPropertyPricePolicyFromDb.DateApplied
                modelPropertyPricePolicyFromDb.IsConfirmed = hasattr(
                    paramModel, 'IsConfirmed'
                ) and paramModel.IsConfirmed or modelPropertyPricePolicyFromDb.IsConfirmed

                modelPropertyPricePolicyFromDb.LastModifiedBy = modelAdmin.IndexNo
                modelPropertyPricePolicyFromDb.DateLastModified = str(
                    self.util_common.currentDateTime())

                with self.base_service.DbContext() as __context:
                    # update to db
                    result = __context.table(
                        self.PropertyPricePolicy).update_by_model(
                            modelPropertyPricePolicyFromDb)
                    if result:
                        return modelPropertyPricePolicyFromDb
        return None
Exemplo n.º 7
0
class CityService():
    def __init__(self):
        self.base_service = BaseService()
        self.db = BaseService.DbFilePath
        self.ec = self.base_service.Entity()
        self.util_common = self.base_service.UtilCommon()
        self.City = self.ec.InitEntityClass('City')
        self.service_account = AccountService()

    def get_city_all(self):
        with self.base_service.DbContext() as __context:
            result = __context.table(self.City).select_all()
            return result

        return None

    def get_city_byId(self, idValue):
        with self.base_service.DbContext() as __context:
            result = __context.table(self.City).select_by_id(idValue)
            return result

        return None

    def get_city_byName(self, searchText):
        with self.base_service.DbContext() as __context:
            conditions = ''' Name like '%{0}%' '''.format(searchText)
            result = __context.table(self.City).select_by(conditions)
            return result

        return None

    def get_city_byCode(self, searchText):
        with self.base_service.DbContext() as __context:
            conditions = ''' CityCode like '%{0}%' '''.format(searchText)
            result = __context.table(self.City).select_by(conditions)
            return result

        return None

    def add_city(self, paramModel):
        if (paramModel is not None and inspect.isclass(type(paramModel))
                and type(paramModel) == self.City):
            with self.base_service.DbContext() as __context:

                modelLastCity = __context.table(self.City).select_lastrecord(
                )  # get last record of City table to increment IndexNo

                # create new object of City
                modelCity = self.City()
                modelCity.CityId = modelLastCity.CityId + 1
                modelCity.CountryId = hasattr(
                    paramModel, 'CountryId') and paramModel.CountryId or None
                modelCity.ParentId = hasattr(
                    paramModel, 'ParentId') and paramModel.ParentId or None
                modelCity.Name = hasattr(paramModel,
                                         'Name') and paramModel.Name or None
                modelCity.CityCode = hasattr(
                    paramModel, 'CityCode') and paramModel.CityCode or None
                modelCity.SortOrder = hasattr(
                    paramModel, 'SortOrder') and paramModel.SortOrder or None
                modelCity.IsAvailable = hasattr(
                    paramModel, 'IsAvailable') and paramModel.IsAvailable or 1

                # insert to db
                result = __context.table(self.City).insert_by_model(modelCity)
                if result:
                    return modelCity

        return None

    def update_city(self, paramModel):
        if (paramModel is not None and inspect.isclass(type(paramModel))
                and type(paramModel) == self.City):

            modelCityFromDb = self.get_city_byId(paramModel.CityId)

            if (modelCityFromDb is not None):

                modelCityFromDb.CountryId = hasattr(
                    paramModel, 'CountryId'
                ) and paramModel.CountryId or modelCityFromDb.CountryId
                modelCityFromDb.ParentId = hasattr(
                    paramModel, 'ParentId'
                ) and paramModel.ParentId or modelCityFromDb.ParentId
                modelCityFromDb.Name = hasattr(
                    paramModel,
                    'Name') and paramModel.Name or modelCityFromDb.Name
                modelCityFromDb.CityCode = hasattr(
                    paramModel, 'CityCode'
                ) and paramModel.CityCode or modelCityFromDb.CityCode
                modelCityFromDb.SortOrder = hasattr(
                    paramModel, 'SortOrder'
                ) and paramModel.SortOrder or modelCityFromDb.SortOrder
                modelCityFromDb.IsAvailable = hasattr(
                    paramModel, 'IsAvailable'
                ) and paramModel.IsAvailable or modelCityFromDb.IsAvailable

                with self.base_service.DbContext() as __context:
                    # update to db
                    result = __context.table(
                        self.City).update_by_model(modelCityFromDb)
                    if result:
                        return modelCityFromDb
        return None
class PropertyItemService():

    def __init__(self):
        self.base_service = BaseService()
        self.db = BaseService.DbFilePath
        self.ec = self.base_service.Entity()
        self.util_common = self.base_service.UtilCommon()
        self.PropertyItem = self.ec.InitEntityClass('PropertyItem')
        self.service_account = AccountService()


    def get_propitem_all(self):
        with self.base_service.DbContext() as __context:
            result = __context.table(self.PropertyItem).select_all()
            return result
        
        return None

    def get_propitem_byId(self, idValue):
        with self.base_service.DbContext() as __context:
            result = __context.table(self.PropertyItem).select_by_id(idValue)
            return result
        
        return None
    
    def get_propitem_byName(self, searchText):
        with self.base_service.DbContext() as __context:
            conditions = ''' FullName like '%{0}%' '''.format(searchText)
            result = __context.table(self.PropertyItem).select_by(conditions) 
            return result
        
        return None
   
    def add_propitem(self, paramModel):
        if( paramModel is not None and inspect.isclass(type(paramModel)) and type(paramModel) == self.PropertyItem):
            with self.base_service.DbContext() as __context:
                
                modelAdmin = self.service_account.get_accountAdmin()# get limit 1 result 

                modelLastPropertyItem = __context.table(self.PropertyItem).select_lastrecord()# get last record of PropertyItem table to increment IndexNo
                
                # create new object of PropertyItem
                modelPropertyItem = self.PropertyItem()
                modelPropertyItem.PropertyItemId = str(self.util_common.generateUUID())
                modelPropertyItem.IndexNo = hasattr(paramModel, 'IndexNo') and paramModel.IndexNo or (modelLastPropertyItem.IndexNo + 1)
                modelPropertyItem.ParentId = hasattr(paramModel, 'ParentId') and paramModel.ParentId or None
                modelPropertyItem.PropertyId = hasattr(paramModel, 'PropertyId') and paramModel.PropertyId or None
                modelPropertyItem.PropertyTypeId = hasattr(paramModel, 'PropertyTypeId') and paramModel.PropertyTypeId or None
                modelPropertyItem.PropertyStatusId = hasattr(paramModel, 'PropertyStatusId') and paramModel.PropertyStatusId or None
                modelPropertyItem.PropAvailTypeId = hasattr(paramModel, 'PropAvailTypeId') and paramModel.PropAvailTypeId or None
                modelPropertyItem.Name = hasattr(paramModel, 'Name') and paramModel.Name or None
                modelPropertyItem.ShortDescription = hasattr(paramModel, 'ShortDescription') and paramModel.ShortDescription or None
                modelPropertyItem.LongDescription = hasattr(paramModel, 'LongDescription') and paramModel.LongDescription or None
                modelPropertyItem.FloorNo = hasattr(paramModel, 'FloorNo') and paramModel.FloorNo or None
                modelPropertyItem.RoomName = hasattr(paramModel, 'RoomName') and paramModel.RoomName or None
                modelPropertyItem.Width = hasattr(paramModel, 'Width') and paramModel.Width or 0
                modelPropertyItem.Length = hasattr(paramModel, 'Length') and paramModel.Length or 0
                modelPropertyItem.AreaUsage = hasattr(paramModel, 'AreaUsage') and paramModel.AreaUsage or 0
                modelPropertyItem.MaxAllowPeople = hasattr(paramModel, 'MaxAllowPeople') and paramModel.MaxAllowPeople or None
                modelPropertyItem.LastElectricalUsageNo = hasattr(paramModel, 'LastElectricalUsageNo') and paramModel.LastElectricalUsageNo or None
                modelPropertyItem.LastWaterUsageNo = hasattr(paramModel, 'LastWaterUsageNo') and paramModel.LastWaterUsageNo or None
                modelPropertyItem.IsAvailable = hasattr(paramModel, 'IsAvailable') and paramModel.IsAvailable or 1
                modelPropertyItem.IsRemoved = hasattr(paramModel, 'IsRemoved') and paramModel.IsRemoved or 0

                modelPropertyItem.CreatedBy = modelAdmin.IndexNo
                modelPropertyItem.LastModifiedBy = modelAdmin.IndexNo
                modelPropertyItem.DateCreated = str(self.util_common.currentDateTime())
                modelPropertyItem.DateLastModified = str(self.util_common.currentDateTime())

                # insert to db
                result = __context.table(self.PropertyItem).insert_by_model(modelPropertyItem)
                if result:
                    return modelPropertyItem
        
        return None

    def update_propitem(self, paramModel):
        if(paramModel is not None and inspect.isclass(type(paramModel)) and type(paramModel) == self.PropertyItem):
            
            modelPropertyItemFromDb = self.get_propitem_byId(paramModel.PropertyItemId)
            
            if(modelPropertyItemFromDb is not None):

                modelAdmin = self.service_account.get_accountAdmin()# get limit 1 result 
           
                modelPropertyItemFromDb.IndexNo = hasattr(paramModel, 'IndexNo') and paramModel.IndexNo or modelPropertyItemFromDb.IndexNo
                modelPropertyItemFromDb.ParentId = hasattr(paramModel, 'ParentId') and paramModel.ParentId or modelPropertyItemFromDb.ParentId
                modelPropertyItemFromDb.PropertyId = hasattr(paramModel, 'PropertyId') and paramModel.PropertyId or modelPropertyItemFromDb.PropertyId
                modelPropertyItemFromDb.PropertyTypeId = hasattr(paramModel, 'PropertyTypeId') and paramModel.PropertyTypeId or modelPropertyItemFromDb.PropertyTypeId
                modelPropertyItemFromDb.PropertyStatusId = hasattr(paramModel, 'PropertyStatusId') and paramModel.PropertyStatusId or modelPropertyItemFromDb.PropertyStatusId
                modelPropertyItemFromDb.PropAvailTypeId = hasattr(paramModel, 'PropAvailTypeId') and paramModel.PropAvailTypeId or modelPropertyItemFromDb.PropAvailTypeId
                modelPropertyItemFromDb.Name = hasattr(paramModel, 'Name') and paramModel.Name or modelPropertyItemFromDb.Name
                modelPropertyItemFromDb.ShortDescription = hasattr(paramModel, 'ShortDescription') and paramModel.ShortDescription or modelPropertyItemFromDb.ShortDescription
                modelPropertyItemFromDb.LongDescription = hasattr(paramModel, 'LongDescription') and paramModel.LongDescription or modelPropertyItemFromDb.LongDescription
                modelPropertyItemFromDb.FloorNo = hasattr(paramModel, 'FloorNo') and paramModel.FloorNo or modelPropertyItemFromDb.FloorNo
                modelPropertyItemFromDb.RoomName = hasattr(paramModel, 'RoomName') and paramModel.RoomName or modelPropertyItemFromDb.RoomName
                modelPropertyItemFromDb.Width = hasattr(paramModel, 'Width') and paramModel.Width or modelPropertyItemFromDb.Width
                modelPropertyItemFromDb.Length = hasattr(paramModel, 'Length') and paramModel.Length or modelPropertyItemFromDb.Length
                modelPropertyItemFromDb.AreaUsage = hasattr(paramModel, 'AreaUsage') and paramModel.AreaUsage or modelPropertyItemFromDb.AreaUsage
                modelPropertyItemFromDb.MaxAllowPeople = hasattr(paramModel, 'MaxAllowPeople') and paramModel.MaxAllowPeople or modelPropertyItemFromDb.MaxAllowPeople
                modelPropertyItemFromDb.LastElectricalUsageNo = hasattr(paramModel, 'LastElectricalUsageNo') and paramModel.LastElectricalUsageNo or modelPropertyItemFromDb.LastElectricalUsageNo
                modelPropertyItemFromDb.LastWaterUsageNo = hasattr(paramModel, 'LastWaterUsageNo') and paramModel.LastWaterUsageNo or modelPropertyItemFromDb.LastWaterUsageNo
                modelPropertyItemFromDb.IsAvailable = hasattr(paramModel, 'IsAvailable') and paramModel.IsAvailable or 1
                modelPropertyItemFromDb.IsRemoved = hasattr(paramModel, 'IsRemoved') and paramModel.IsRemoved or 0
                
                modelPropertyItemFromDb.LastModifiedBy = modelAdmin.IndexNo
                modelPropertyItemFromDb.DateLastModified = str(self.util_common.currentDateTime())

                with self.base_service.DbContext() as __context:
                    # update to db
                    result = __context.table(self.PropertyItem).update_by_model(modelPropertyItemFromDb)
                    if result:
                        return modelPropertyItemFromDb
        return None
Exemplo n.º 9
0
class AccountService():
    def __init__(self):
        self.base_service = BaseService()
        self.db = BaseService.DbFilePath
        self.ec = self.base_service.Entity()
        self.util_common = self.base_service.UtilCommon()
        self.util_security = self.base_service.UtilSecurity()
        self.Account = self.ec.InitEntityClass('Account')

    def get_account_all(self):
        with self.base_service.DbContext() as __context:
            result = __context.table(self.Account).select_all()
            return result

        return None

    def get_account_byId(self, idValue):
        with self.base_service.DbContext() as __context:
            result = __context.table(self.Account).select_by_id(idValue)
            return result

        return None

    def get_account_byUname(self, searchText):
        with self.base_service.DbContext() as __context:
            conditions = ''' Username like '%{0}%' '''.format(searchText)
            result = __context.table(self.Account).select_by(conditions)
            return result

        return None

    def get_accountAdmin(self):
        with self.base_service.DbContext() as __context:
            conditions = ''' IsMasterAdmin = 1 '''
            result = __context.table(self.Account).select_by(conditions)
            return result[0]

        return None

    def add_account(self, paramModel):
        if (paramModel is not None and inspect.isclass(type(paramModel))
                and type(paramModel) == self.Account):
            with self.base_service.DbContext() as __context:

                modelAdmin = self.get_accountAdmin()  # get limit 1 result

                modelLastAccount = __context.table(
                    self.Account).select_lastrecord(
                    )  # get last record of Account table to increment IndexNo

                password = hasattr(
                    paramModel,
                    'Pw') and paramModel.Pw or self.util_common.randomString(8)
                hashedpassword = self.util_security.generatePasswordByBcrypt(
                    password, 6)  # generate hashed password using bcrypt

                # create new object of Account
                modelAcc = self.Account()
                modelAcc.AccountId = str(self.util_common.generateUUID())
                modelAcc.IndexNo = hasattr(
                    paramModel, 'IndexNo') and paramModel.IndexNo or (
                        modelLastAccount.IndexNo + 1)
                modelAcc.Username = hasattr(
                    paramModel, 'Username') and paramModel.Username or None
                modelAcc.IsBooker = hasattr(
                    paramModel, 'IsBooker') and paramModel.IsBooker or 1
                modelAcc.IpAddress = hasattr(
                    paramModel, 'IpAddress') and paramModel.IpAddress or None
                modelAcc.Pw = hashedpassword
                modelAcc.SaltKey = hasattr(
                    paramModel, 'SaltKey') and paramModel.SaltKey or None
                modelAcc.IsAvailable = hasattr(
                    paramModel, 'IsAvailable') and paramModel.IsAvailable or 1

                modelAcc.CreatedBy = modelAdmin.IndexNo
                modelAcc.LastModifiedBy = modelAdmin.IndexNo
                modelAcc.DateCreated = str(self.util_common.currentDateTime())
                modelAcc.DateLastModified = str(
                    self.util_common.currentDateTime())
                # insert to db
                result = __context.table(
                    self.Account).insert_by_model(modelAcc)
                if result:
                    return modelAcc

        return None

    def update_account(self, paramModel):
        if (paramModel is not None and inspect.isclass(type(paramModel))
                and type(paramModel) == self.Account):

            modelAccFromDb = self.get_account_byId(paramModel.AccountId)

            if (modelAccFromDb is not None):

                modelAdmin = self.get_accountAdmin()  # get limit 1 result
                modelAccFromDb.Pw = (
                    # if paramModel.Pw (new password) has value and it not matched exist password
                    (hasattr(paramModel, 'Pw')
                     and not self.util_security.verifyHashed(
                         self.util_security, paramModel.Pw, modelAccFromDb.Pw))
                    # then generate new hashed password for new password
                    and self.util_security.generatePasswordByBcrypt(
                        paramModel.Pw, 6)
                    # else if they matched together, get exist password
                    or modelAccFromDb.Pw)
                modelAccFromDb.IndexNo = hasattr(
                    paramModel,
                    'IndexNo') and paramModel.IndexNo or modelAccFromDb.IndexNo
                modelAccFromDb.Username = hasattr(
                    paramModel, 'Username'
                ) and paramModel.Username or modelAccFromDb.Username
                modelAccFromDb.IsBooker = hasattr(
                    paramModel, 'IsBooker'
                ) and paramModel.IsBooker or modelAccFromDb.IsBooker
                modelAccFromDb.IsMasterAdmin = hasattr(
                    paramModel, 'IsMasterAdmin'
                ) and paramModel.IsMasterAdmin or modelAccFromDb.IsMasterAdmin
                modelAccFromDb.IpAddress = hasattr(
                    paramModel, 'IpAddress'
                ) and paramModel.IpAddress or modelAccFromDb.IpAddress
                modelAccFromDb.DateLastLogin = hasattr(
                    paramModel, 'DateLastLogin'
                ) and paramModel.DateLastLogin or modelAccFromDb.DateLastLogin
                modelAccFromDb.IsAvailable = hasattr(
                    paramModel, 'IsAvailable'
                ) and paramModel.IsAvailable or modelAccFromDb.IsAvailable

                modelAccFromDb.LastModifiedBy = modelAdmin.IndexNo
                modelAccFromDb.DateLastModified = str(
                    self.util_common.currentDateTime())

                with self.base_service.DbContext() as __context:
                    # update to db
                    result = __context.table(
                        self.Account).update_by_model(modelAccFromDb)
                    if result:
                        return modelAccFromDb
        return None