def get(self):
     now = datetime.datetime.now()
     delta = datetime.timedelta(minutes=MINUTES_INTERVAL)
     namespace_infos = {}
     for namespace in metadata.get_namespaces():
         namespace_manager.set_namespace(namespace)
         orders = Order.query(Order.status == CREATING_ORDER, Order.date_created <= now - delta).fetch()
         if orders:
             infos = []
             for order in orders:
                 if config.APP_KIND == AUTO_APP:
                     info = _handle_auto(order)
                 elif config.APP_KIND == RESTO_APP:
                     info = _handle_resto(order)
                 else:
                     info = [("ERROR", "unknown APP_KIND")]
                 infos.append(info)
             namespace_infos[namespace] = infos
     mail_body = "Orders with creating status\n"
     for namespace in namespace_infos.keys():
         mail_body += 'In namespace = %s:\n' % namespace
         mail_body += "List of orders:\n" + \
                      "\n\n".join("\n".join("%s: %s" % t for t in info) for info in namespace_infos[namespace])
     if namespace_infos:
         namespace_manager.set_namespace('')
         admins.send_error("order", "Orders crashed while creating", mail_body)
Exemple #2
0
    def get(self):
        if self.request.init_namespace:  # we want app config, not company config
            namespace_manager.set_namespace(self.request.init_namespace)

        has_cities = bool(get_company_cities())
        has_companies = AutomationCompany.query().get(
            keys_only=True) is not None

        self.render_json({
            'has_cities': has_cities,
            'has_companies': has_companies,
            'colors': {
                'main': config.ACTION_COLOR,
            },
            'appearance': {
                'ios': {
                    'color': config.GET_APP_APPEARANCE_IOS.dict()
                },
                'android': {
                    'color': config.GET_APP_APPEARANCE_ANDROID.dict()
                }
            },
            'keys': {
                'branch': config.BRANCH_API_KEY,
                'ga': {
                    'ios': config.GOOGLE_ANALYTICS_API_KEY_IOS,
                    'android': config.GOOGLE_ANALYTICS_API_KEY_ANDROID
                },
                'parse': {
                    'app_key': config.PARSE_APP_API_KEY,
                    'client_key': config.PARSE_CLIENT_API_KEY,
                },
                'yandex_metrics': config.YANDEX_METRICA_KEY,
            }
        })
 def get(self):
     namespaces = []
     for namespace in metadata.get_namespaces():
         namespace_manager.set_namespace(namespace)
         if config:
             namespaces.append(namespace)
     self.render('/companies.html', **{'companies': namespaces})
Exemple #4
0
    def get(self):
        for namespace in metadata.get_namespaces():
            namespace_manager.set_namespace(namespace)
            if not config:
                continue

            deferred.defer(defer_apply_module)
Exemple #5
0
 def get(self):
     for namespace in metadata.get_namespaces():
         namespace_manager.set_namespace(namespace)
         for cls in (GeoPush, LeftBasketPromo):
             promos = cls.query(cls.status == STATUS_AVAILABLE).fetch()
             for promo in promos:
                 promo.deactivate()
Exemple #6
0
def get_clients():
    namespace = namespace_manager.get_namespace()
    namespace_manager.set_namespace('')  # query global clients
    result = Client.query(Client.namespace_created == namespace).fetch()
    namespace_manager.set_namespace(namespace)
    result.extend(Client.query().fetch())
    return result
Exemple #7
0
 def dispatch(self):
     if self.user:
         logging.info(self.user)
         namespace_manager.set_namespace(self.user.namespace)
     else:
         namespace_manager.set_namespace('')
     logging.debug('namespace=%s' % namespace_manager.get_namespace())
     super(UserApiHandler, self).dispatch()
Exemple #8
0
def save_menu(namespace):
    logging.info(namespace)
    namespace_manager.set_namespace(namespace)
    resto_company = RestoCompany.get()
    if resto_company:
        reload_menu()
    else:
        logging.warning('Not found resto company')
 def get(self):
     if self.request.init_namespace:
         namespace_manager.set_namespace(self.request.init_namespace)
     self.render_json({
         'companies': [
             company.dict() for company in AutomationCompany.query(
                 AutomationCompany.status == STATUS_AVAILABLE).fetch()
         ]
     })
Exemple #10
0
 def post(self):
     namespace = self.request.get('namespace')
     namespace_manager.set_namespace(namespace)
     order_id = self.request.get_range('order_id')
     order = Order.get_by_id(order_id)
     if not order.response_success:
         client = Client.get(order.client_id)
         sms_text = u"%s, Ваш заказ №%s принят. Проверьте историю заказов." % (
             client.name, order_id)
         sms_pilot.send_sms([sms_phone(client.tel)], sms_text)
Exemple #11
0
 def dict(self):
     from models.config.config import config, COMPANY_PREVIEW
     namespace_manager.set_namespace(self.namespace)
     return {
         'name': config.APP_NAME,
         'namespace': self.namespace,
         'image': self.image,
         'description': self.description,
         'preview': config.COMPANY_STATUS == COMPANY_PREVIEW,
     }
Exemple #12
0
    def post(self):
        response = {}

        try:
            client_id = self.request.get_range('client_id') or int(
                self.request.headers.get('Client-Id') or 0)
        except ValueError:
            client_id = 0

        client = None
        if client_id:
            if self.request.init_namespace:
                namespace_manager.set_namespace(self.request.init_namespace)
            client = Client.get(client_id)
        if not client:
            response['success'] = False
            self.render_json(response)

        outdated_client = None
        outdated_client_id = self.request.get_range('old_client_id')
        if outdated_client_id:
            outdated_client = Client.get(outdated_client_id)

        if outdated_client:
            if config.APP_KIND == AUTO_APP:
                if config.WALLET_ENABLED:
                    wallet_balance = empatika_wallet.get_balance(
                        outdated_client.key.id())
                    if wallet_balance > 0:
                        source = "transfer from (%s) to (%s)" % (
                            outdated_client.key.id(), client.key.id())
                        empatika_wallet.deposit(client.key.id(),
                                                wallet_balance, source)
                        empatika_wallet.pay(outdated_client.key.id(), source,
                                            wallet_balance)

                if config.PROMOS_API_KEY:
                    accum_points = empatika_promos.get_user_points(
                        outdated_client.key.id())

                    if accum_points > 0:
                        empatika_promos.move_user_points(
                            outdated_client.key.id(), client.key.id(),
                            accum_points)

                history = Order.get(outdated_client)
                for order in history:
                    order.client_id = client.key.id()
                    order.put()

            response['success'] = True
        else:
            response['success'] = False

        self.render_json(response)
Exemple #13
0
def send_review_push(order):
    namespace_manager.set_namespace(order.key.namespace())
    module = config.REVIEW_MODULE
    if module and module.status:
        review = ReviewPush(order=order.key)
        review.put()
        start = datetime.utcnow() + timedelta(seconds=module.wait_seconds)
        taskqueue.add(url='/task/pushes/review',
                      method='POST',
                      eta=start,
                      params={'review_id': review.key.id()})
Exemple #14
0
 def get(self):
     namespace_manager.set_namespace('')
     user_id = self.request.get_range('user_id')
     user = CompanyUser.get_by_id(user_id)
     rights = []
     for right in CompanyUser.ALL_RIGHTS_BITS:
         rights.append({
             'name': MAP_RIGHTS[right],
             'value': right
         })
     self.render('/user/edit.html', rights=rights, cur_user=user)
 def get(self):
     if self.request.init_namespace:
         namespace_manager.set_namespace(self.request.init_namespace)
     if not self.request.city:
         self.abort(400)
     location = get_location(self.request.get("ll"))
     self.render_json({
         'venues': [
             venue.dict(user_location=location)
             for venue in self.request.city.get_venues(location)
         ]
     })
Exemple #16
0
 def post(self):
     namespace_manager.set_namespace('')
     user_id = self.request.get_range('user_id')
     user = CompanyUser.get_by_id(user_id)
     rights = []
     for right in CompanyUser.ALL_RIGHTS_BITS:
         confirmed = self.request.get(str(right))
         if confirmed:
             rights.append(right)
     user.rights = CompanyUser.make_mask(rights)
     user.put()
     self.redirect('/company/user/list')
Exemple #17
0
    def get(self):
        namespace = namespace_manager.get_namespace()
        namespace_manager.set_namespace('')
        users = CompanyUser.query(CompanyUser.namespace == namespace).fetch()
        for user in users:
            user.rights_str = ''
            for right in CompanyUser.ALL_RIGHTS_BITS:
                if user.has_rights((right,)):
                    user.rights_str += MAP_RIGHTS[right] + ', '

        public_hostname = "demo.rbcn.mobi" if CURRENT_APP_ID == DEMO_APP_ID else "auto.rbcn.mobi"
        login_url = "http://%s/company/login" % public_hostname
        self.render('/user/list.html', users=users, login_url=login_url)
Exemple #18
0
 def get(self):
     companies = []
     for namespace in metadata.get_namespaces():
         namespace_manager.set_namespace(namespace)
         if config and config.APP_NAME:
             companies.append({
                 'base_url':
                 u'http://%s.%s.%s.appspot.com' %
                 (namespace, CURRENT_VERSION, CURRENT_APP_ID),
                 'app_name':
                 config.APP_NAME
             })
     self.render_json({'companies': companies})
Exemple #19
0
def update_theme_information(controller, theme_name, theme_title, exclusive,
                             author, thumbnail, using, in_datastore):
    from google.appengine.api.namespace_manager import namespace_manager
    namespace_manager.set_namespace('shared')
    n = ThemesModel.get_or_create_by_name(name=theme_name,
                                          theme_title=theme_title,
                                          theme_name=theme_name,
                                          exclusive=exclusive,
                                          author=author,
                                          thumbnail=thumbnail,
                                          using=using,
                                          in_datastore=in_datastore)
    namespace_manager.set_namespace(controller.namespace)
 def get(self):
     if self.request.init_namespace:
         namespace_manager.set_namespace(self.request.init_namespace)
     if not self.request.city:
         self.abort(400)
     items = ProxyMenuItem.query().fetch()
     result = []
     for item in items:
         real_items = item.get_items(self.request.city)
         if not real_items:
             continue
         min_price = min(i.price for i in real_items) / 100.0
         result.append(item.dict(min_price))
     self.render_json({'items': result})
Exemple #21
0
 def post(self, admin_id):
     password = self.request.get('password')
     admin_id = int(admin_id)
     admin = Admin.get_by_id(admin_id)
     if not admin:
         self.abort(500)
     auth.set_password(admin, password)
     admin.put()
     namespace_manager.set_namespace('')
     login = admin.login
     general_admin = Admin.query(Admin.login == login).get()
     if not general_admin:
         self.abort(500)
     auth.set_password(general_admin, password)
     general_admin.put()
     self.redirect_to('barista_main')
Exemple #22
0
 def post(self):
     rights = []
     for right in CompanyUser.ALL_RIGHTS_BITS:
         confirmed = self.request.get(str(right))
         if confirmed:
             rights.append(right)
     login = self.request.get('login')
     values = {
         'namespace': namespace_manager.get_namespace(),
         'login': login,
         'password_raw': self.request.get('password'),
         'rights': CompanyUser.make_mask(rights),
     }
     namespace_manager.set_namespace('')
     success, user = CompanyUser.create_user(login, **values)
     self.redirect('/company/user/list')
Exemple #23
0
 def post(self):
     if self.user is not None:
         self.success()
     login, password, password2 = \
         self.request.get("email").strip().lower(), \
         self.request.get("password"), self.request.get("password2")
     namespace = latinize(login)
     error = None
     for metadata_instance in metadata.get_namespaces():
         if namespace == metadata_instance:
             error = u"Введите другой email"
     if error:
         pass
     elif not login:
         error = u"Не введен email"
     elif not password:
         error = u"Не введен пароль"
     elif password != password2:
         error = u"Пароли не совпадают"
     else:
         values = {
             'namespace': namespace,
             'login': login,
             'password_raw': password,
             'rights': CompanyUser.RIGHTS_MASK_ADMIN,
         }
         success, user = CompanyUser.create_user(login, **values)
         if not success:
             error = u"Пользователь с этим email уже зарегистрирован"
         else:
             set_current_user(self.auth, user)
     if error:
         logging.info(error)
         self.render('/signup.html', email=login, error=error)
     else:
         namespace_manager.set_namespace(namespace)
         cfg = Config(id=1)
         cfg.REPORT_EMAILS = '*****@*****.**'
         cfg.put()
         DeliverySlot(name=u'Сейчас', slot_type=0, value=0).put()
         DeliverySlot(name=u'Через 5 минут', slot_type=0, value=5).put()
         DeliverySlot(name=u'Через 10 минут', slot_type=0, value=10).put()
         DeliverySlot(name=u'Через 15 минут', slot_type=0, value=15).put()
         DeliverySlot(name=u'Через 20 минут', slot_type=0, value=20).put()
         DeliverySlot(name=u'Через 25 минут', slot_type=0, value=25).put()
         DeliverySlot(name=u'Через 30 минут', slot_type=0, value=30).put()
         self.success()
Exemple #24
0
 def get(self):
     namespace_manager.set_namespace('perchiniribaris')
     for item in MenuItem.query().fetch():
         if item.picture:
             if not item.icon:
                 try:
                     item.icon = get_new_image_url('MenuItemIcon', item.key.id(), url=item.picture, size=ICON_SIZE)
                     item.put()
                 except:
                     logging.warning('exception in resize image 128')
             if not item.cut_picture:
                 logging.info(item.title)
                 try:
                     item.cut_picture = get_new_image_url('MenuItem', item.key.id(), url=item.picture)
                     item.put()
                 except:
                     logging.warning('exception in resize image max size')
Exemple #25
0
 def get_venues_by_company(self, company, location=None):
     from methods import location as location_methods
     from models import Venue
     init_namespace = namespace_manager.get_namespace()
     venues = []
     namespace_manager.set_namespace(company.namespace)
     for venue in Venue.query(Venue.active == True).fetch():
         if venue.address.city == self.city:
             venue.company_id = company.key.id
             venues.append(venue)
             if location:
                 venue.distance = location_methods.distance(
                     location, venue.coordinates)
     if location:
         venues = sorted(venues, key=lambda venue: venue.distance)
     namespace_manager.set_namespace(init_namespace)
     return venues
 def get(self):
     time = datetime.datetime.now() - datetime.timedelta(
         days=MAX_DAYS_BEFORE_CANCEL)
     namespace_cancels = {}
     for namespace in metadata.get_namespaces():
         namespace_manager.set_namespace(namespace)
         unused_gifts = SharedGift.query(
             SharedGift.status == SharedGift.READY)
         old_gifts = [gift for gift in unused_gifts if gift.created < time]
         if old_gifts:
             for gift in old_gifts:
                 gift.cancel(namespace)
             namespace_cancels[namespace] = 'Gifts not used within %s days: %s. In company %s\n' % \
                                            (MAX_DAYS_BEFORE_CANCEL, len(old_gifts), config.APP_NAME)
     if namespace_cancels:
         namespace_manager.set_namespace('')
         admins.send_error('order', 'Unused gifts found',
                           ''.join(namespace_cancels.values()))
Exemple #27
0
 def get(self):
     namespace_hit = {}
     for namespace in metadata.get_namespaces():
         namespace_manager.set_namespace(namespace)
         if config.HIT_MODULE and config.HIT_MODULE.status == STATUS_AVAILABLE:
             module = config.HIT_MODULE
             update_hit_category()
             items_str = u'\n'.join([
                 '%s: rating = %s' %
                 (item.get().title, round(item.get().rating, 3))
                 for item in module.items
             ])
             text = 'In company (%s), hit category (%s) has items: \n%s\n\n' % (
                 config.APP_NAME, module.title, items_str)
             namespace_hit[namespace] = text
     if namespace_hit:
         namespace_manager.set_namespace('')
         admins.send_error('hits', 'Hits has been changed',
                           ''.join(namespace_hit.values()))
Exemple #28
0
def run_in_namespace(namespace, function, *args, **kwargs):
    """Executes a function in a given namespace, then returns back to the
    current namescape.

    :param namespace:
        Name of the namespace to run the function.
    :param function:
        Function to be executed in the given namespace.
    :param args:
        Arguments to be passed to the function.
    :param kwargs:
        Keyword arguments to be passed to the function.
    """
    current_namespace = namespace_manager.get_namespace()
    try:
        namespace_manager.set_namespace(namespace)
        return function(*args, **kwargs)
    finally:
        # Restore previous namespace.
        namespace_manager.set_namespace(current_namespace)
def run_in_namespace(namespace, function, *args, **kwargs):
    """Executes a function in a given namespace, then returns back to the
    current namescape.

    :param namespace:
        Name of the namespace to run the function.
    :param function:
        Function to be executed in the given namespace.
    :param args:
        Arguments to be passed to the function.
    :param kwargs:
        Keyword arguments to be passed to the function.
    """
    current_namespace = namespace_manager.get_namespace()
    try:
        namespace_manager.set_namespace(namespace)
        return function(*args, **kwargs)
    finally:
        # Restore previous namespace.
        namespace_manager.set_namespace(current_namespace)
Exemple #30
0
def update_namespace(namespace):
    init_namespace = None

    if CURRENT_APP_ID == PRODUCTION_APP_ID:
        if not config:
            logging.debug('namespace=%s' % namespace_manager.get_namespace())
            return False, init_namespace
        logging.debug('initial namespace=%s' %
                      namespace_manager.get_namespace())
        if namespace:
            proxy_company = AutomationCompany.query(
                AutomationCompany.namespace == namespace).get()
            if proxy_company:
                init_namespace = namespace_manager.get_namespace()
                namespace_manager.set_namespace(namespace)
    elif CURRENT_APP_ID == DEMO_APP_ID:
        if not namespace_manager.get_namespace():
            namespace_manager.set_namespace(namespace)

    logging.debug('namespace=%s' % namespace_manager.get_namespace())
    return True, init_namespace
Exemple #31
0
 def get_items(self, city, available_venues=None):
     from models import MenuItem
     init_namespace = namespace_manager.get_namespace()
     items = []
     for company in AutomationCompany.query(
             AutomationCompany.status == STATUS_AVAILABLE).fetch():
         venues = city.get_venues_by_company(company)
         namespace_manager.set_namespace(company.namespace)
         for item in MenuItem.query(
                 MenuItem.status == STATUS_AVAILABLE).fetch():
             item.venues = []
             for venue in venues:
                 if venue.key in item.restrictions:
                     continue
                 if available_venues and venue not in available_venues:
                     continue
                 if self.compare(item):
                     item.venues.append(venue)
                     items.append(item)
     namespace_manager.set_namespace(init_namespace)
     return items
Exemple #32
0
 def setUp(self):
     Domain.create(TestDecorators.HOME_DOMAIN_NAME).put()
     namespace_manager.set_namespace(TestDecorators.HOME_DOMAIN_NAME)
     self.response.clear()
Exemple #33
0
 def get(self):
   namespace_manager.set_namespace(
       self.request.get("namespace", default_value=None))
   self._handle_wrapper()
Exemple #34
0
 def set_up(self):
     ns = get_namespace(self.handler.request.host)
     if ns:
         set_namespace(ns)