Esempio n. 1
0
def create_save(json, create_or_update, company_id):
    action = g.req('action', allowed=['load', 'save', 'validate'])
    layouts = [x.get_client_side_dict() for x in db(PortalLayout).all()]
    types = {x.id: x.get_client_side_dict() for x in PortalDivisionType.get_division_types()}
    company = Company.get(company_id)
    member_companies = {company_id: company.get_client_side_dict()}
    company_logo = company.logo_file_relationship.url() if company.logo_file_id else '/static/images/company_no_logo.png'

    if action == 'load':
        ret = {'company_id': company_id,
               'company_logo': company_logo,
               'portal_company_members': member_companies,
               'portal': {'company_owner_id': company_id, 'name': '', 'host': '',
                          'logo_file_id': company.logo_file_id,
                          'portal_layout_id': layouts[0]['id'],
                          'divisions': [
                              {'name': 'index page', 'portal_division_type_id': 'index',
                               'page_size': ''},
                              {'name': 'news', 'portal_division_type_id': 'news', 'page_size': ''},
                              {'name': 'events', 'portal_division_type_id': 'events',
                               'page_size': ''},
                              {'name': 'catalog', 'portal_division_type_id': 'catalog',
                               'page_size': ''},
                              {'name': 'our subportal',
                               'portal_division_type_id': 'company_subportal',
                               'page_size': '',
                               'settings': {'company_id': company_id}}]},
               'layouts': layouts, 'division_types': types}
        if create_or_update == 'update':
            pass
            # ret['portal'] =
        return ret
    else:
        json_portal = json['portal']
        if create_or_update == 'update':
            pass
        elif create_or_update == 'create':
            page_size_for_config = dict()
            for a in json_portal['divisions']:
                page_size_for_config[a.get('name')] = a.get('page_size') \
                    if type(a.get('page_size')) is int and a.get('page_size') != 0 \
                    else Config.ITEMS_PER_PAGE
            portal = Portal(company_owner=company, **g.filter_json(json_portal, 'name', 'portal_layout_id', 'host'))
            divisions = []
            for division_json in json['portal']['divisions']:
                division = PortalDivision(portal, portal_division_type_id=division_json['portal_division_type_id'],
                                          position=len(json['portal']['divisions']) - len(divisions),
                                          name=division_json['name'])
                if division_json['portal_division_type_id'] == 'company_subportal':
                    division.settings = {'member_company_portal': portal.company_members[0]}
                divisions.append(division)
            # self, portal=portal, portal_division_type=portal_division_type, name='', settings={}
            portal.divisions = divisions
            PortalConfig(portal=portal, page_size_for_divisions=page_size_for_config)
        if action == 'save':
            return portal.setup_created_portal(g.filter_json(json_portal, 'logo_file_id')).save().get_client_side_dict()
        else:
            return portal.validate(create_or_update == 'insert')
Esempio n. 2
0
def profile_load_validate_save(json, company_id=None):
    # if not user_can_edit:
    #     raise Exception('no PORTAL_EDIT_PROFILE')
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company() if company_id is None else Company.get(company_id)
    if action == 'load':
        company_dict = company.get_client_side_dict()
        # company_dict['logo'] = company.get_logo_client_side_dict()
        user_company = UserCompany.get(company_id=company_id)
        if user_company:
            company_dict['actions'] = {'edit_company_profile': EditCompanyRight(company=company).is_allowed(),
                                       'edit_portal_profile': EditPortalRight(company=company_id).is_allowed()}
        return company_dict
    else:
        company.attr(g.filter_json(json, 'about', 'address', 'country', 'email', 'name', 'phone', 'city', 'postcode',
                                   'phone2', 'region', 'short_description', 'lon', 'lat'))
        if action == 'validate':
            if company_id is not None:
                company.detach()
            return company.validate(company_id is None)
        else:
            if company_id and EditCompanyRight(company=company_id).is_allowed() != True:
                return abort(403)
            if company_id is None:
                company.setup_new_company().save()

            company.logo = json['logo']

        return utils.dict_merge(company.save().get_client_side_dict(), actions={'edit': True if company_id else False})
Esempio n. 3
0
def profile_load_validate_save(json, company_id=None):
    user_can_edit = UserCompany.get(company_id=company_id).rights['PORTAL_EDIT_PROFILE'] if company_id else None
    # if not user_can_edit:
    #     raise Exception('no PORTAL_EDIT_PROFILE')
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company() if company_id is None else Company.get(company_id)
    if action == 'load':
        company_dict = company.get_client_side_dict()
        company_dict['logo'] = company.get_logo_client_side_dict()
        company_dict['actions'] = {'edit': True if company_id and UserCompany.get(
                company_id=company_id).rights['PORTAL_EDIT_PROFILE'] else False}
        return company_dict
    else:
        company.attr(g.filter_json(json, 'about', 'address', 'country', 'email', 'name', 'phone', 'city', 'postcode',
                                   'phone2', 'region', 'short_description', 'lon', 'lat'))
        if action == 'validate':
            if company_id is not None:
                company.detach()
            return company.validate(company_id is None)
        else:
            if company_id is None:
                company.setup_new_company()

            company_dict = company.set_logo_client_side_dict(json['logo']).save().get_client_side_dict()
            company_dict['logo'] = company.get_logo_client_side_dict()
            company_dict['actions'] = {'edit': True if company_id else False}
            return company_dict
Esempio n. 4
0
def profile_load_validate_save(json, company_id=None):
    user_can_edit = UserCompany.get(
        company_id=company_id
    ).rights['PORTAL_EDIT_PROFILE'] if company_id else None
    # if not user_can_edit:
    #     raise Exception('no PORTAL_EDIT_PROFILE')
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company() if company_id is None else Company.get(company_id)
    if action == 'load':
        company_dict = company.get_client_side_dict()
        company_dict['logo'] = company.get_logo_client_side_dict()
        company_dict['actions'] = {
            'edit':
            True if company_id and UserCompany.get(
                company_id=company_id).rights['PORTAL_EDIT_PROFILE'] else False
        }
        return company_dict
    else:
        company.attr(
            g.filter_json(json, 'about', 'address', 'country', 'email', 'name',
                          'phone', 'city', 'postcode', 'phone2', 'region',
                          'short_description', 'lon', 'lat'))
        if action == 'validate':
            if company_id is not None:
                company.detach()
            return company.validate(company_id is None)
        else:
            if company_id is None:
                company.setup_new_company()

            company_dict = company.set_logo_client_side_dict(
                json['logo']).save().get_client_side_dict()
            company_dict['logo'] = company.get_logo_client_side_dict()
            company_dict['actions'] = {'edit': True if company_id else False}
            return company_dict
Esempio n. 5
0
def load(json, company_id=None):
    user_can_edit = UserCompany.get(
        company_id=company_id
    ).rights['PORTAL_EDIT_PROFILE'] if company_id else None
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company() if company_id is None else Company.get(company_id)
    if action == 'load':
        company_dict = company.get_client_side_dict()
        image_dict = {
            'ratio': Config.IMAGE_EDITOR_RATIO,
            'coordinates': None,
            'image_file_id': company_dict.get('logo_file_id'),
            'no_image_url': g.fileUrl(FOLDER_AND_FILE.no_logo())
        }
        try:
            if company_dict.get('logo_file_id'):
                image_dict['image_file_id'], image_dict['coordinates'] = ImageCroped. \
                    get_coordinates_and_original_img(company_dict.get('logo_file_id'))
            else:
                image_dict['image_file_id'] = None
        except Exception as e:
            pass
        image = {'image': image_dict}
        company_dict.update(image)
        return company_dict
    else:
        company.attr(
            g.filter_json(json, 'about', 'address', 'country', 'email', 'name',
                          'phone', 'phone2', 'region', 'short_description',
                          'lon', 'lat'))
        if action == 'validate':
            if company_id is not None and user_can_edit:
                company.detach()
            return company.validate(company_id is None and user_can_edit)
        else:
            if json['image'].get('uploaded'):
                if company_id is None:
                    company.setup_new_company()
                company.save().get_client_side_dict()
                imgdataContent = json['image']['dataContent']
                image_data = re.sub('^data:image/.+;base64,', '',
                                    imgdataContent)
                bb = base64.b64decode(image_data)
                new_comp = db(Company, id=company.id).first()
                file_id = File.uploadForCompany(bb, json['image']['name'],
                                                json['image']['type'],
                                                new_comp)
                logo_id = crop_image(file_id, json['image']['coordinates'])
                new_comp.updates({'logo_file_id': logo_id})
            else:
                img = json['image']
                img_id = img.get('image_file_id')
                if img_id:
                    company.logo_file_id = crop_image(img_id,
                                                      img['coordinates'])
                elif not img_id:
                    company.logo_file_id = None
                if company_id is None:
                    company.setup_new_company()
                return company.save().get_client_side_dict()
Esempio n. 6
0
def submit_publish(json, article_action):
    action = g.req('action', allowed=['load', 'validate', 'save'])

    company = Company.get(json['company']['id'])

    if article_action == 'SUBMIT':
        material = ArticleCompany.get(json['material']['id'])
        publication = ArticlePortalDivision(title=material.title, subtitle=material.subtitle,
                                            keywords=material.keywords,
                                            short=material.short, long=material.long, article_company_id=material.id)
        more_data_to_ret = {
            'material': {'id': material.id},
            'can_material_also_be_published':
                MemberCompanyPortal.get(portal_id=json['portal']['id'], company_id=json['company']['id'])
                    .has_rights(MemberCompanyPortal.RIGHT_AT_PORTAL.PUBLICATION_PUBLISH)
        }
    else:
        publication = ArticlePortalDivision.get(json['publication']['id'])
        more_data_to_ret = {}

    if action == 'load':
        ret = {
            'publication': publication.get_client_side_dict(),
            'company': company.get_client_side_dict(),
            'portal': Portal.get(json['portal']['id']).get_client_side_dict()
        }
        ret['portal']['divisions'] = PRBase.get_ordered_dict([d for d in ret['portal']['divisions']
                                                              if (d['portal_division_type_id'] in ['events', 'news'])])

        return PRBase.merge_dicts(ret, more_data_to_ret)
    else:

        publication.attr(g.filter_json(json['publication'], 'portal_division_id'))
        publication.publishing_tm = PRBase.parse_timestamp(json['publication'].get('publishing_tm'))
        publication.event_tm = PRBase.parse_timestamp(json['publication'].get('event_tm'))
        if 'also_publish' in json and json['also_publish']:
            publication.status = ArticlePortalDivision.STATUSES['PUBLISHED']
        else:
            if article_action in [ArticlePortalDivision.ACTIONS['PUBLISH'], ArticlePortalDivision.ACTIONS['REPUBLISH']]:
                publication.status = ArticlePortalDivision.STATUSES['PUBLISHED']
            elif article_action in [ArticlePortalDivision.ACTIONS['UNPUBLISH'], ArticlePortalDivision.ACTIONS[
                'UNDELETE']]:
                publication.status = ArticlePortalDivision.STATUSES['UNPUBLISHED']
            elif article_action in [ArticlePortalDivision.ACTIONS['DELETE']]:
                publication.status = ArticlePortalDivision.STATUSES['DELETED']

        if action == 'validate':
            publication.detach()
            return publication.validate(True if article_action == 'SUBMIT' else False)
        else:
            if article_action == 'SUBMIT':
                publication.long = material.clone_for_portal_images_and_replace_urls(publication.portal_division_id,
                                                                                     publication)
            publication.save()
            return get_portal_dict_for_material(publication.portal, company, publication=publication)
Esempio n. 7
0
def load_form_create(json, company_id=None, material_id=None, publication_id=None):
    action = g.req('action', allowed=['load', 'validate', 'save'])

    def portal_division_dict(article, tags=None):
        if (not hasattr(article, 'portal_division_id')) or (article.portal_division_id is None):
            return {'positioned_articles': []}
        else:
            filter = article.position_unique_filter()
            return {'positioned_articles':
                        [pda.get_client_side_dict(fields='id|position|title') for pda in
                         db(ArticlePortalDivision).filter(filter).
                             order_by(expression.desc(ArticlePortalDivision.position)).all()],
                    'availableTags': tags
                    }

    available_tag_names = None

    if company_id:  # creating material version
        articleVersion = ArticleCompany(company_id=company_id, editor=g.user, article=Article(author_user_id=g.user.id))
    elif material_id:  # companys version. always updating existing
        articleVersion = ArticleCompany.get(material_id)
    elif publication_id:  # updating portal version
        articleVersion = ArticlePortalDivision.get(publication_id)
        portal_division_id = articleVersion.portal_division_id
        article_tag_names = articleVersion.tags
        available_tags = PortalDivision.get(portal_division_id).portal_division_tags
        available_tag_names = list(map(lambda x: getattr(x, 'name', ''), available_tags))

    if action == 'load':
        article_dict = articleVersion.get_client_side_dict(more_fields='long|company')
        article_dict['image'] = articleVersion.get_image_client_side_dict()
        if publication_id:
            article_dict = dict(list(article_dict.items()) + [('tags', article_tag_names)])
        return {'article': article_dict,
                'portal_division': portal_division_dict(articleVersion, available_tag_names)}
    else:
        parameters = g.filter_json(json, 'article.title|subtitle|short|long|keywords')
        articleVersion.attr(parameters['article'])
        if action == 'validate':
            articleVersion.detach()
            return articleVersion.validate(articleVersion.id is not None)
        else:
            if type(articleVersion) == ArticlePortalDivision:
                tag_names = json['article']['tags']
                articleVersion.manage_article_tags(tag_names)
            article_dict = articleVersion.set_image_client_side_dict(
                json['article']['image']).save().get_client_side_dict(more_fields='long|company')
            if publication_id:
                articleVersion.insert_after(json['portal_division']['insert_after'],
                                            articleVersion.position_unique_filter())
            article_dict['image'] = articleVersion.get_image_client_side_dict()
            return {'article': article_dict,
                    'portal_division': portal_division_dict(articleVersion)}
Esempio n. 8
0
def load(json, company_id=None):
    user_can_edit = UserCompany.get(company_id=company_id).rights['PORTAL_EDIT_PROFILE'] if company_id else None
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company() if company_id is None else Company.get(company_id)
    if action == 'load':
        company_dict = company.get_client_side_dict()
        image_dict = {'ratio': Config.IMAGE_EDITOR_RATIO, 'coordinates': None,
                      'image_file_id': company_dict.get('logo_file_id'),
                      'no_image_url': g.fileUrl(FOLDER_AND_FILE.no_logo())
                      }
        try:
            if company_dict.get('logo_file_id'):
                image_dict['image_file_id'], image_dict['coordinates'] = ImageCroped. \
                    get_coordinates_and_original_img(company_dict.get('logo_file_id'))
            else:
                image_dict['image_file_id'] = None
        except Exception as e:
            pass
        image = {'image': image_dict}
        company_dict.update(image)
        return company_dict
    else:
        company.attr(g.filter_json(json, 'about', 'address', 'country', 'email', 'name', 'phone',
                                   'phone2', 'region', 'short_description', 'lon', 'lat'))
        if action == 'validate':
            if company_id is not None and user_can_edit:
                company.detach()
            return company.validate(company_id is None and user_can_edit)
        else:
            if json['image'].get('uploaded'):
                if company_id is None:
                    company.setup_new_company()
                company.save().get_client_side_dict()
                imgdataContent = json['image']['dataContent']
                image_data = re.sub('^data:image/.+;base64,', '', imgdataContent)
                bb = base64.b64decode(image_data)
                new_comp = db(Company, id=company.id).first()
                file_id = File.uploadForCompany(bb, json['image']['name'], json['image']['type'], new_comp)
                logo_id = crop_image(file_id, json['image']['coordinates'])
                new_comp.updates({'logo_file_id': logo_id})
            else:
                img = json['image']
                img_id = img.get('image_file_id')
                if img_id:
                    company.logo_file_id = crop_image(img_id, img['coordinates'])
                elif not img_id:
                    company.logo_file_id = None
                if company_id is None:
                    company.setup_new_company()
                return company.save().get_client_side_dict()
Esempio n. 9
0
def load_form_create(json):
    action = g.req('action', allowed=['load', 'validate', 'save'])
    if action == 'load':
        return {'id': '', 'title': '', 'short': '', 'long': '', 'coordinates': '',
                'ratio': Config.IMAGE_EDITOR_RATIO}
    if action == 'validate':
        del json['coordinates'], json['ratio']

        return Article.save_new_article(g.user_dict['id'], **g.filter_json(json, 'title,short,long,keywords')).mine_version.validate('insert')
    else:
        image_id = json.get('image_file_id')
        if image_id:
            json['image_file_id'] = crop_image(image_id, json.get('coordinates'))
        del json['coordinates'], json['ratio']
        article = Article.save_new_article(g.user_dict['id'], **json)
        g.db.add(article)
        return article.get_client_side_dict()
Esempio n. 10
0
def load(json, company_id=None):
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company() if company_id is None else Company.get(company_id)
    if action == 'load':
        return company.get_client_side_dict()
    else:
        company.attr(g.filter_json(json, 'about', 'address', 'country', 'email', 'name', 'phone',
                                   'phone2', 'region', 'short_description'))
        if json['logo_file_id']:
            company.logo_file_id = json['logo_file_id']

        if action == 'save':
            if company_id is None:
                company.setup_new_company()
            return company.save().get_client_side_dict()
        else:
            if company_id is not None:
                company.detach()
            return company.validate('insert' if company_id is None else 'update')
Esempio n. 11
0
def load(json, company_id=None):
    action = g.req("action", allowed=["load", "validate", "save"])
    company = Company() if company_id is None else Company.get(company_id)
    if action == "load":
        return company.get_client_side_dict()
    else:
        company.attr(
            g.filter_json(
                json, "about", "address", "country", "email", "name", "phone", "phone2", "region", "short_description"
            )
        )
        if action == "save":
            if company_id is None:
                company.setup_new_company()
            return company.save().get_client_side_dict()
        else:
            if company_id is not None:
                company.detach()
            return company.validate("insert" if company_id is None else "update")
Esempio n. 12
0
def load_form_create(json_data, company_id=None, material_id=None):
    action = g.req('action', allowed=['load', 'validate', 'save'])

    if material_id:
        material = Material.get(material_id)
    else:
        material = Material(company=Company.get(company_id), company_id=company_id, editor=g.user)

    if action == 'load':
        return {'material': material.get_client_side_dict(more_fields='long|company|illustration')}
    else:
        parameters = g.filter_json(json_data, 'material.title|subtitle|short|long|keywords|author')
        material.attr(parameters['material'])
        if action == 'validate':
            material.detach()
            return material.validate(material.id is not None)
        else:
            material.save()
            material.illustration = json_data['material']['illustration']

            return {'material': material.save().get_client_side_dict(more_fields='long|company|illustration')}
Esempio n. 13
0
def signup(json_data):
    action = g.req('action', allowed=['validate', 'save'])

    params = g.filter_json(json_data, 'first_name,last_name,email,password,password_confirmation')
    params['address_email'] = params['email']
    del params['email']
    new_user = User(**params)

    if action == 'validate':
        return new_user.validate(True)
    else:
        # try:
        if session.get('portal_id'):
            addtourl = {'subscribe_to_portal': session['portal_id']}
            session.pop('portal_id')
        else:
            addtourl = {}
        new_user.set_password_hash()
        new_user.generate_confirmation_token(addtourl).save()
        g.db.commit()
        return {}
Esempio n. 14
0
def load(json, company_id=None):
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company() if company_id is None else Company.get(company_id)
    if action == 'load':
        company_dict = company.get_client_side_dict()
        image_dict = {'ratio': Config.IMAGE_EDITOR_RATIO, 'coordinates': None,
                      'image_file_id': company_dict.get('logo_file_id'),
                      'no_image_url': g.fileUrl(FOLDER_AND_FILE.no_logo())
                      }
        try:
            if company_dict.get('logo_file_id'):
                image_dict['image_file_id'], image_dict['coordinates'] = ImageCroped. \
                    get_coordinates_and_original_img(company_dict.get('logo_file_id'))
            else:
                image_dict['image_file_id'] = None
        except Exception as e:
            pass
        image = {'image': image_dict}
        company_dict.update(image)
        return company_dict
    else:
        company.attr(g.filter_json(json, 'about', 'address', 'country', 'email', 'name', 'phone',
                                   'phone2', 'region', 'short_description', 'lon', 'lat'))

        if action == 'validate':
            if company_id is not None:
                company.detach()
            return company.validate(company_id is None)
        else:
            img = json['image']
            img_id = img.get('image_file_id')
            if img_id:
                company.logo_file_id = crop_image(img_id, img['coordinates'])
            elif not img_id:
                company.logo_file_id = None

            if company_id is None:
                company.setup_new_company()
            return company.save().get_client_side_dict()
Esempio n. 15
0
def load_form_create(json_data, company_id=None, material_id=None):
    action = g.req('action', allowed=['load', 'validate', 'save'])

    if material_id:
        material = Material.get(material_id)
    else:
        material = Material(company=Company.get(company_id),
                            company_id=company_id,
                            editor=g.user)

    if action == 'load':
        return {
            'material':
            material.get_client_side_dict(
                more_fields='long|company|illustration')
        }
    else:
        parameters = g.filter_json(
            json_data, 'material.title|subtitle|short|long|keywords|author')
        material.attr(parameters['material'])
        if action == 'validate':
            material.detach()
            return material.validate(material.id is not None)
        else:
            material.illustration = utils.dict_merge(
                json_data['material']['illustration'], {
                    'company':
                    material.company,
                    'file_name_prefix':
                    'illustration_for_material_%s' % (material.id, )
                })

            return {
                'material':
                material.save().get_client_side_dict(
                    more_fields='long|company|illustration')
            }
Esempio n. 16
0
def profile_load(json, create_or_update, company_id, portal_id=None):
    action = g.req('action', allowed=['load', 'save', 'validate'])
    layouts = [x.get_client_side_dict() for x in db(PortalLayout).all()]
    types = {x.id: x.get_client_side_dict() for x in PortalDivisionType.get_division_types()}
    company = Company.get(company_id)
    portal = Portal() if portal_id is None else Portal.get(portal_id)
    if action == 'load':
        ret = {'company': company.get_client_side_dict(),
               'layouts': layouts, 'division_types': types}
        if create_or_update == 'update':
            ret['portal'] = {}
            ret['portal_company_members'] = company.portal_members
            ret['host_profi_or_own'] = 'profi' if re.match(r'^profireader\.', ret['portal']['hostname']) else 'own'
        else:
            ret['portal_company_members'] = [company.get_client_side_dict()]
            ret['portal'] = {'company_owner_id': company_id, 'name': '', 'host': '',

                             'logo_file_id': company.logo_file_id,
                             'host_profi_or_own': 'profi',
                             'host_own': '',
                             'host_profi': '',
                             'portal_layout_id': layouts[0]['id'],
                             'divisions': [
                                 {'name': 'index page', 'portal_division_type_id': 'index',
                                  'page_size': ''},
                                 {'name': 'news', 'portal_division_type_id': 'news', 'page_size': ''},
                                 {'name': 'events', 'portal_division_type_id': 'events',
                                  'page_size': ''},
                                 {'name': 'catalog', 'portal_division_type_id': 'catalog',
                                  'page_size': ''},
                                 {'name': 'our subportal',
                                  'portal_division_type_id': 'company_subportal',
                                  'page_size': '',
                                  'settings': {'company_id': ret['portal_company_members'][0]['id']}}]}
            ret['logo'] = portal.get_logo_client_side_dict()
        return ret
    else:
        json_portal = json['portal']
        if create_or_update == 'update':
            pass
        elif create_or_update == 'create':
            page_size_for_config = dict()
            for a in json_portal['divisions']:
                page_size_for_config[a.get('name')] = a.get('page_size') \
                    if type(a.get('page_size')) is int and a.get('page_size') != 0 \
                    else Config.ITEMS_PER_PAGE
            # print(json)
            json_portal['host'] = (json_portal['host_profi'] + '.profireader.com') \
                if json_portal['host_profi_or_own'] == 'profi' else json_portal['host_own']

            portal = Portal(company_owner=company, **g.filter_json(json_portal, 'name', 'portal_layout_id', 'host'))
            divisions = []
            for division_json in json['portal']['divisions']:
                division = PortalDivision(portal, portal_division_type_id=division_json['portal_division_type_id'],
                                          position=len(json['portal']['divisions']) - len(divisions),
                                          name=division_json['name'])
                if division_json['portal_division_type_id'] == 'company_subportal':
                    division.settings = {'member_company_portal': portal.company_members[0]}
                divisions.append(division)
            # self, portal=portal, portal_division_type=portal_division_type, name='', settings={}
            portal.divisions = divisions
            PortalConfig(portal=portal, page_size_for_divisions=page_size_for_config)
        if action == 'save':
            portal.setup_created_portal(g.filter_json(json_portal, 'logo_file_id')).save()
            portal_dict = portal.set_logo_client_side_dict(json['logo']).save().get_client_side_dict()
            return portal_dict
        else:
            return portal.validate(create_or_update == 'create')
Esempio n. 17
0
    def to_dict(self, *args, prefix=''):
        ret = {}
        __debug = True

        req_columns = {}
        req_relationships = {}

        def add_to_req_relationships(column_name, columns):
            if column_name not in req_relationships:
                req_relationships[column_name] = []
            req_relationships[column_name].append(columns)

        def get_next_level(child, nextlevelargs, prefix, standard_fields_required):
            in_next_level_dict = {k: v for k, v in child.items() if k in nextlevelargs} if \
                isinstance(child, dict) else child.to_dict(*nextlevelargs, prefix=prefix)
            if standard_fields_required:
                in_next_level_dict.update(child if isinstance(child, dict) else child.get_client_side_dict())
            return in_next_level_dict

        for arguments in args:
            if arguments:
                for argument in re.compile('\s*,\s*').split(arguments):
                    columnsdevided = argument.split('.')
                    column_names = columnsdevided.pop(0)
                    for column_name in column_names.split('|'):
                        if len(columnsdevided) == 0:
                            req_columns[column_name] = True
                        else:
                            add_to_req_relationships(column_name, '.'.join(columnsdevided))

        columns = class_mapper(self.__class__).columns
        relations = {a: b for (a, b) in class_mapper(self.__class__).relationships.items()}
        for a, b in class_mapper(self.__class__).all_orm_descriptors.items():
            if isinstance(b, AssociationProxy):
                relations[a] = b
        # association_proxies = {a: b for (a, b) in class_mapper(self.__class__).all_orm_descriptors.items()
        #                        if isinstance(b, AssociationProxy)}
        pass

        for col in columns:
            if col.key in req_columns or (__debug and '*' in req_columns):
                ret[col.key] = self.to_dict_object_property(col.key)
                if col.key in req_columns:
                    del req_columns[col.key]
        if '*' in req_columns and __debug:
            del req_columns['*']

        del_req_columns_in_attrs = []
        for colname in req_columns:
            if hasattr(self, colname) and colname not in relations:
                del_req_columns_in_attrs.append(colname)
                ret[colname] = getattr(self, colname)
        for colname in del_req_columns_in_attrs:
            del req_columns[colname]

        if len(req_columns) > 0:
            columns_not_in_relations = list(set(req_columns.keys()) - set(relations.keys()))
            if len(columns_not_in_relations) > 0:
                raise ValueError(
                    "you requested not existing attribute(s) `%s%s`" % (
                        prefix, '`, `'.join(columns_not_in_relations),))
            else:
                for rel_name in req_columns:
                    add_to_req_relationships(rel_name, '~')
                    # raise ValueError("you requested for attribute(s) but "
                    #                  "relationships found `%s%s`" % (
                    #                      prefix, '`, `'.join(set(relations.keys()).
                    #                          intersection(
                    #                          req_columns.keys())),))

        for relationname, relation in relations.items():
            rltn = relations[relation.target_collection] if isinstance(relation, AssociationProxy) else relation
            if relationname in req_relationships or (__debug and '*' in req_relationships):
                if relationname in req_relationships:
                    nextlevelargs = req_relationships[relationname]
                    del req_relationships[relationname]
                else:
                    nextlevelargs = req_relationships['*']
                related_obj = getattr(self, relationname)
                standard_fields_required = False
                while '~' in nextlevelargs:
                    standard_fields_required = True
                    nextlevelargs.remove('~')

                if rltn.uselist:
                    add = [get_next_level(child, nextlevelargs, prefix + relationname + '.', standard_fields_required)
                           for child in related_obj]
                else:
                    add = None if related_obj is None else \
                        get_next_level(related_obj, nextlevelargs, prefix + relationname + '.',
                                       standard_fields_required)

                ret[relationname] = add

        if '*' in req_relationships:
            del req_relationships['*']

        del_req_columns_in_attrs = []
        for relname, nextlevelargs in req_relationships.items():
            if hasattr(self, relname):
                del_req_columns_in_attrs.append(relname)
                add = g.filter_json(getattr(self, relname), *nextlevelargs) if nextlevelargs else getattr(
                    self, relname)
                ret[relname] = utils.dict_merge_recursive(ret[relname] if relname in ret else {}, add)

        for colname in del_req_columns_in_attrs:
            del req_relationships[colname]

        if len(req_relationships) > 0:
            relations_not_in_columns = list(set(
                req_relationships.keys()) - set(columns))
            if len(relations_not_in_columns) > 0:
                raise ValueError(
                    "you requested not existing relation(s) `%s%s`" % (
                        prefix, '`, `'.join(relations_not_in_columns),))
            else:
                raise ValueError("you requested for relation(s) but "
                                 "column(s) found `%s%s`" % (
                                     prefix, '`, `'.join(set(columns).intersection(
                                         req_relationships)),))

        return ret
Esempio n. 18
0
def submit_publish(json, article_action):
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company.get(json['company']['id'])
    if article_action == 'SUBMIT':
        material = Material.get(json['material']['id'])
        check = EditOrSubmitMaterialInPortal(
            material=material,
            portal=json['portal']['id']).action_is_allowed(article_action)
        if check != True:
            return check
        publication = Publication(material=material)
        more_data_to_ret = {
            'material': {
                'id': material.id
            },
            'can_material_also_be_published': check == True
        }
    else:
        publication = Publication.get(json['publication']['id'])
        check = PublishUnpublishInPortal(
            publication=publication,
            division=publication.portal_division_id,
            company=company).action_is_allowed(article_action)
        if check != True:
            return check
        more_data_to_ret = {}

    if action == 'load':
        portal = Portal.get(json['portal']['id'])
        ret = {
            'publication': publication.get_client_side_dict(),
            'company': company.get_client_side_dict(),
            'portal': portal.get_client_side_dict()
        }
        ret['portal']['divisions'] = PRBase.get_ordered_dict(
            PublishUnpublishInPortal().get_active_division(portal.divisions))

        return utils.dict_merge(ret, more_data_to_ret)
    else:

        publication.attr(
            g.filter_json(json['publication'], 'portal_division_id'))
        publication.publishing_tm = PRBase.parse_timestamp(
            json['publication'].get('publishing_tm'))
        publication.event_begin_tm = PRBase.parse_timestamp(
            json['publication'].get('event_begin_tm'))
        publication.event_end_tm = PRBase.parse_timestamp(
            json['publication'].get('event_end_tm'))
        publication.tags = [
            Tag.get(t['id']) for t in json['publication']['tags']
        ]

        if 'also_publish' in json and json['also_publish']:
            publication.status = PublishUnpublishInPortal.STATUSES['PUBLISHED']
        else:
            if article_action in [
                    PublishUnpublishInPortal.ACTIONS['PUBLISH'],
                    PublishUnpublishInPortal.ACTIONS['REPUBLISH']
            ]:
                publication.status = PublishUnpublishInPortal.STATUSES[
                    'PUBLISHED']
            elif article_action in [
                    PublishUnpublishInPortal.ACTIONS['UNPUBLISH'],
                    PublishUnpublishInPortal.ACTIONS['UNDELETE']
            ]:
                publication.status = PublishUnpublishInPortal.STATUSES[
                    'UNPUBLISHED']
            elif article_action in [
                    PublishUnpublishInPortal.ACTIONS['DELETE']
            ]:
                publication.status = PublishUnpublishInPortal.STATUSES[
                    'DELETED']

        if action == 'validate':
            publication.detach()
            return publication.validate(True if article_action ==
                                        'SUBMIT' else False)
        else:
            # if article_action == 'SUBMIT':
            #     publication.long = material.clone_for_portal_images_and_replace_urls(publication.portal_division_id,
            #                                                                          publication)
            publication.save().set_tags_positions()
            return get_portal_dict_for_material(
                publication.portal,
                company,
                publication=publication,
                submit=article_action == 'SUBMIT')
Esempio n. 19
0
def load_form_create(json,
                     company_id=None,
                     material_id=None,
                     publication_id=None):
    action = g.req('action', allowed=['load', 'validate', 'save'])

    def portal_division_dict(article, tags=None):
        if (not hasattr(article, 'portal_division_id')) or (
                article.portal_division_id is None):
            return {'positioned_articles': []}
        else:
            filter = article.position_unique_filter()
            return {
                'positioned_articles': [
                    pda.get_client_side_dict(fields='id|position|title') for
                    pda in db(ArticlePortalDivision).filter(filter).order_by(
                        expression.desc(ArticlePortalDivision.position)).all()
                ],
                'availableTags':
                tags
            }

    available_tag_names = None

    if company_id:  # creating material version
        articleVersion = ArticleCompany(
            company_id=company_id,
            editor=g.user,
            article=Article(author_user_id=g.user.id))
    elif material_id:  # companys version. always updating existing
        articleVersion = ArticleCompany.get(material_id)
    elif publication_id:  # updating portal version
        articleVersion = ArticlePortalDivision.get(publication_id)
        portal_division_id = articleVersion.portal_division_id

        article_tag_names = articleVersion.tags
        available_tags = PortalDivision.get(
            portal_division_id).portal_division_tags
        available_tag_names = list(
            map(lambda x: getattr(x, 'name', ''), available_tags))

    if action == 'load':
        article_dict = articleVersion.get_client_side_dict(
            more_fields='long|company')

        if publication_id:
            article_dict = dict(
                list(article_dict.items()) + [('tags', article_tag_names)])

        image_dict = {
            'ratio': Config.IMAGE_EDITOR_RATIO,
            'coordinates': None,
            'image_file_id': article_dict['image_file_id'],
            'no_image_url': g.fileUrl(FOLDER_AND_FILE.no_article_image())
        }
        # article_dict['long'] = '<table><tr><td><em>cell</em> 1</td><td><strong>cell<strong> 2</td></tr></table>'
        # TODO: VK by OZ: this code should be moved to model
        try:
            if article_dict.get('image_file_id'):
                image_dict['image_file_id'], image_dict['coordinates'] = ImageCroped. \
                    get_coordinates_and_original_img(article_dict.get('image_file_id'))
            else:
                image_dict['image_file_id'] = None
        except Exception as e:
            pass

        return {
            'article':
            article_dict,
            'image':
            image_dict,
            'portal_division':
            portal_division_dict(articleVersion, available_tag_names)
        }
    else:
        parameters = g.filter_json(
            json, 'article.title|subtitle|short|long|keywords, image.*')
        articleVersion.attr(parameters['article'])

        if action == 'validate':
            articleVersion.detach()
            return articleVersion.validate(articleVersion.id is not None)
        else:
            image_id = parameters['image'].get('image_file_id')
            # TODO: VK by OZ: this code dont work if ArticlePortalDivision updated
            if image_id:
                articleVersion.image_file_id = crop_image(
                    image_id, parameters['image']['coordinates'])
            else:
                articleVersion.image_file_id = None

            if type(articleVersion) == ArticlePortalDivision:
                tag_names = json['article']['tags']
                articleVersion.manage_article_tags(tag_names)

            articleVersion.save()
            if publication_id:
                articleVersion.insert_after(
                    json['portal_division']['insert_after'],
                    articleVersion.position_unique_filter())
            return {
                'article':
                articleVersion.save().get_client_side_dict(more_fields='long'),
                'image':
                json['image'],
                'portal_division':
                portal_division_dict(articleVersion)
            }
Esempio n. 20
0
def submit_publish(json, article_action):
    action = g.req('action', allowed=['load', 'validate', 'save'])

    company = Company.get(json['company']['id'])

    if article_action == 'SUBMIT':
        material = ArticleCompany.get(json['material']['id'])
        publication = ArticlePortalDivision(title=material.title,
                                            subtitle=material.subtitle,
                                            keywords=material.keywords,
                                            short=material.short,
                                            long=material.long,
                                            article_company_id=material.id)
        more_data_to_ret = {
            'material': {
                'id': material.id
            },
            'can_material_also_be_published':
            MemberCompanyPortal.get(
                portal_id=json['portal']['id'],
                company_id=json['company']['id']).has_rights(
                    MemberCompanyPortal.RIGHT_AT_PORTAL.PUBLICATION_PUBLISH)
        }
    else:
        publication = ArticlePortalDivision.get(json['publication']['id'])
        more_data_to_ret = {}

    if action == 'load':
        ret = {
            'publication': publication.get_client_side_dict(),
            'company': company.get_client_side_dict(),
            'portal': Portal.get(json['portal']['id']).get_client_side_dict()
        }
        ret['portal']['divisions'] = PRBase.get_ordered_dict([
            d for d in ret['portal']['divisions']
            if (d['portal_division_type_id'] in ['events', 'news'])
        ])

        return PRBase.merge_dicts(ret, more_data_to_ret)
    else:

        publication.attr(
            g.filter_json(json['publication'], 'portal_division_id'))
        publication.publishing_tm = PRBase.parse_timestamp(
            json['publication'].get('publishing_tm'))
        publication.event_tm = PRBase.parse_timestamp(
            json['publication'].get('event_tm'))
        if 'also_publish' in json and json['also_publish']:
            publication.status = ArticlePortalDivision.STATUSES['PUBLISHED']
        else:
            if article_action in [
                    ArticlePortalDivision.ACTIONS['PUBLISH'],
                    ArticlePortalDivision.ACTIONS['REPUBLISH']
            ]:
                publication.status = ArticlePortalDivision.STATUSES[
                    'PUBLISHED']
            elif article_action in [
                    ArticlePortalDivision.ACTIONS['UNPUBLISH'],
                    ArticlePortalDivision.ACTIONS['UNDELETE']
            ]:
                publication.status = ArticlePortalDivision.STATUSES[
                    'UNPUBLISHED']
            elif article_action in [ArticlePortalDivision.ACTIONS['DELETE']]:
                publication.status = ArticlePortalDivision.STATUSES['DELETED']

        if action == 'validate':
            publication.detach()
            return publication.validate(True if article_action ==
                                        'SUBMIT' else False)
        else:
            if article_action == 'SUBMIT':
                publication.long = material.clone_for_portal_images_and_replace_urls(
                    publication.portal_division_id, publication)
            publication.save()
            return get_portal_dict_for_material(publication.portal,
                                                company,
                                                publication=publication)
Esempio n. 21
0
def load_form_create(json, article_company_id=None, mine_version_article_company_id=None,
                     article_portal_division_id=None):
    action = g.req('action', allowed=['load', 'validate', 'save'])

    def portal_division_dict(article, tags=None):
        if (not hasattr(article, 'portal_division_id')) or (article.portal_division_id is None):
            return {'positioned_articles': []}
        else:
            filter = article.position_unique_filter()
            return {'positioned_articles':
                        [pda.get_client_side_dict(fields='id|position|title') for pda in
                         db(ArticlePortalDivision).filter(filter).
                             order_by(expression.desc(ArticlePortalDivision.position)).all()],
                    'availableTags': tags
                    }

    available_tag_names = None

    if article_company_id:  # companys version. always updating existing
        articleVersion = ArticleCompany.get(article_company_id)
    elif mine_version_article_company_id:  # updating personal version
        articleVersion = ArticleCompany.get(mine_version_article_company_id)
    elif article_portal_division_id:  # updating portal version
        articleVersion = ArticlePortalDivision.get(article_portal_division_id)
        portal_division_id = articleVersion.portal_division_id

        article_tag_names = articleVersion.tags
        available_tags = PortalDivision.get(portal_division_id).portal_division_tags
        available_tag_names = list(map(lambda x: getattr(x, 'name', ''), available_tags))

    else:  # creating personal version
        articleVersion = ArticleCompany(editor=g.user, article=Article(author_user_id=g.user.id))

    if action == 'load':
        article_dict = articleVersion.get_client_side_dict(more_fields='long|company')

        if article_portal_division_id:
            article_dict = dict(list(article_dict.items()) + [('tags', article_tag_names)])

        image_dict = {'ratio': Config.IMAGE_EDITOR_RATIO, 'coordinates': None,
                      'image_file_id': article_dict['image_file_id'],
                      'no_image_url': g.fileUrl(FOLDER_AND_FILE.no_article_image())
                      }
        # article_dict['long'] = '<table><tr><td><em>cell</em> 1</td><td><strong>cell<strong> 2</td></tr></table>'
        # TODO: VK by OZ: this code should be moved to model
        try:
            if article_dict.get('image_file_id'):
                image_dict['image_file_id'], image_dict['coordinates'] = ImageCroped. \
                    get_coordinates_and_original_img(article_dict.get('image_file_id'))
            else:
                image_dict['image_file_id'] = None
        except Exception as e:
            pass

        return {'article': article_dict,
                'image': image_dict,
                'portal_division': portal_division_dict(articleVersion, available_tag_names)}
    else:
        parameters = g.filter_json(json, 'article.title|short|long|keywords, image.*')

        articleVersion.attr(parameters['article'])
        if action == 'validate':
            articleVersion.detach()
            return articleVersion.validate(article_company_id is None)
        else:
            image_id = parameters['image'].get('image_file_id')
            # TODO: VK by OZ: this code dont work if ArticlePortalDivision updated
            if image_id:
                articleVersion.image_file_id = crop_image(image_id, parameters['image']['coordinates'])
            else:
                articleVersion.image_file_id = None

            if type(articleVersion) == ArticlePortalDivision:
                tag_names = json['article']['tags']
                articleVersion.manage_article_tags(tag_names)

            a = articleVersion.save()
            if article_portal_division_id:
                articleVersion.insert_after(json['portal_division']['insert_after'], articleVersion.position_unique_filter())
            return {'article': articleVersion.save().get_client_side_dict(more_fields='long'), 'image': json['image'],
                    'portal_division': portal_division_dict(articleVersion)}
Esempio n. 22
0
def load_form_create(json,
                     company_id=None,
                     material_id=None,
                     publication_id=None):
    action = g.req('action', allowed=['load', 'validate', 'save'])

    def portal_division_dict(article, tags=None):
        if (not hasattr(article, 'portal_division_id')) or (
                article.portal_division_id is None):
            return {'positioned_articles': []}
        else:
            filter = article.position_unique_filter()
            return {
                'positioned_articles': [
                    pda.get_client_side_dict(fields='id|position|title') for
                    pda in db(ArticlePortalDivision).filter(filter).order_by(
                        expression.desc(ArticlePortalDivision.position)).all()
                ],
                'availableTags':
                tags
            }

    available_tag_names = None

    if company_id:  # creating material version
        articleVersion = ArticleCompany(
            company_id=company_id,
            editor=g.user,
            article=Article(author_user_id=g.user.id))
    elif material_id:  # companys version. always updating existing
        articleVersion = ArticleCompany.get(material_id)
    elif publication_id:  # updating portal version
        articleVersion = ArticlePortalDivision.get(publication_id)
        portal_division_id = articleVersion.portal_division_id
        article_tag_names = articleVersion.tags
        available_tags = PortalDivision.get(
            portal_division_id).portal_division_tags
        available_tag_names = list(
            map(lambda x: getattr(x, 'name', ''), available_tags))

    if action == 'load':
        article_dict = articleVersion.get_client_side_dict(
            more_fields='long|company')
        article_dict['image'] = articleVersion.get_image_client_side_dict()
        if publication_id:
            article_dict = dict(
                list(article_dict.items()) + [('tags', article_tag_names)])
        return {
            'article':
            article_dict,
            'portal_division':
            portal_division_dict(articleVersion, available_tag_names)
        }
    else:
        parameters = g.filter_json(
            json, 'article.title|subtitle|short|long|keywords')
        articleVersion.attr(parameters['article'])
        if action == 'validate':
            articleVersion.detach()
            return articleVersion.validate(articleVersion.id is not None)
        else:
            if type(articleVersion) == ArticlePortalDivision:
                tag_names = json['article']['tags']
                articleVersion.manage_article_tags(tag_names)
            article_dict = articleVersion.set_image_client_side_dict(
                json['article']['image']).save().get_client_side_dict(
                    more_fields='long|company')
            if publication_id:
                articleVersion.insert_after(
                    json['portal_division']['insert_after'],
                    articleVersion.position_unique_filter())
            article_dict['image'] = articleVersion.get_image_client_side_dict()
            return {
                'article': article_dict,
                'portal_division': portal_division_dict(articleVersion)
            }
Esempio n. 23
0
 def set_client_side_dict(self, json):
     self.attr(g.filter_json(json, 'status|position|rights'))
Esempio n. 24
0
def submit_publish(json, article_action):
    action = g.req('action', allowed=['load', 'validate', 'save'])
    company = Company.get(json['company']['id'])
    if article_action == 'SUBMIT':
        material = Material.get(json['material']['id'])
        check = EditOrSubmitMaterialInPortal(material=material, portal=json['portal']['id']).action_is_allowed(
            article_action)
        if check != True:
            return check
        publication = Publication(material=material)
        more_data_to_ret = {
            'material': {'id': material.id},
            'can_material_also_be_published': check == True
        }
    else:
        publication = Publication.get(json['publication']['id'])
        check = PublishUnpublishInPortal(publication=publication, division=publication.portal_division_id,
                                         company=company).action_is_allowed(article_action)
        if check != True:
            return check
        more_data_to_ret = {}

    if action == 'load':
        portal = Portal.get(json['portal']['id'])
        ret = {
            'publication': publication.get_client_side_dict(),
            'company': company.get_client_side_dict(),
            'portal': portal.get_client_side_dict()
        }
        ret['portal']['divisions'] = PRBase.get_ordered_dict(
            PublishUnpublishInPortal().get_active_division(portal.divisions))

        return utils.dict_merge(ret, more_data_to_ret)
    else:

        publication.attr(g.filter_json(json['publication'], 'portal_division_id'))
        publication.publishing_tm = PRBase.parse_timestamp(json['publication'].get('publishing_tm'))
        publication.event_begin_tm = PRBase.parse_timestamp(json['publication'].get('event_begin_tm'))
        publication.event_end_tm = PRBase.parse_timestamp(json['publication'].get('event_end_tm'))
        publication.tags = [Tag.get(t['id']) for t in json['publication']['tags']]

        if 'also_publish' in json and json['also_publish']:
            publication.status = PublishUnpublishInPortal.STATUSES['PUBLISHED']
        else:
            if article_action in [PublishUnpublishInPortal.ACTIONS['PUBLISH'],
                                  PublishUnpublishInPortal.ACTIONS['REPUBLISH']]:
                publication.status = PublishUnpublishInPortal.STATUSES['PUBLISHED']
            elif article_action in [PublishUnpublishInPortal.ACTIONS['UNPUBLISH'],
                                    PublishUnpublishInPortal.ACTIONS['UNDELETE']]:
                publication.status = PublishUnpublishInPortal.STATUSES['UNPUBLISHED']
            elif article_action in [PublishUnpublishInPortal.ACTIONS['DELETE']]:
                publication.status = PublishUnpublishInPortal.STATUSES['DELETED']

        if action == 'validate':
            publication.detach()
            return publication.validate(True if article_action == 'SUBMIT' else False)
        else:
            # if article_action == 'SUBMIT':
            #     publication.long = material.clone_for_portal_images_and_replace_urls(publication.portal_division_id,
            #                                                                          publication)
            publication.save().set_tags_positions()
            return get_portal_dict_for_material(publication.portal, company, publication=publication,
                                                submit=article_action == 'SUBMIT')
Esempio n. 25
0
def load_form_create(json, company_id=None, material_id=None, publication_id=None):
    action = g.req("action", allowed=["load", "validate", "save"])

    def portal_division_dict(article, tags=None):
        if (not hasattr(article, "portal_division_id")) or (article.portal_division_id is None):
            return {"positioned_articles": []}
        else:
            filter = article.position_unique_filter()
            return {
                "positioned_articles": [
                    pda.get_client_side_dict(fields="id|position|title")
                    for pda in db(ArticlePortalDivision)
                    .filter(filter)
                    .order_by(expression.desc(ArticlePortalDivision.position))
                    .all()
                ],
                "availableTags": tags,
            }

    available_tag_names = None

    if company_id:  # creating material version
        articleVersion = ArticleCompany(company_id=company_id, editor=g.user, article=Article(author_user_id=g.user.id))
    elif material_id:  # companys version. always updating existing
        articleVersion = ArticleCompany.get(material_id)
    elif publication_id:  # updating portal version
        articleVersion = ArticlePortalDivision.get(publication_id)
        portal_division_id = articleVersion.portal_division_id

        article_tag_names = articleVersion.tags
        available_tags = PortalDivision.get(portal_division_id).portal_division_tags
        available_tag_names = list(map(lambda x: getattr(x, "name", ""), available_tags))

    if action == "load":
        article_dict = articleVersion.get_client_side_dict(more_fields="long|company")

        if publication_id:
            article_dict = dict(list(article_dict.items()) + [("tags", article_tag_names)])

        image_dict = {
            "ratio": Config.IMAGE_EDITOR_RATIO,
            "coordinates": None,
            "image_file_id": article_dict["image_file_id"],
            "no_image_url": g.fileUrl(FOLDER_AND_FILE.no_article_image()),
        }
        # article_dict['long'] = '<table><tr><td><em>cell</em> 1</td><td><strong>cell<strong> 2</td></tr></table>'
        # TODO: VK by OZ: this code should be moved to model
        try:
            if article_dict.get("image_file_id"):
                image_dict["image_file_id"], image_dict["coordinates"] = ImageCroped.get_coordinates_and_original_img(
                    article_dict.get("image_file_id")
                )
            else:
                image_dict["image_file_id"] = None
        except Exception as e:
            pass

        return {
            "article": article_dict,
            "image": image_dict,
            "portal_division": portal_division_dict(articleVersion, available_tag_names),
        }
    else:
        parameters = g.filter_json(json, "article.title|subtitle|short|long|keywords, image.*")
        articleVersion.attr(parameters["article"])

        if action == "validate":
            articleVersion.detach()
            return articleVersion.validate(articleVersion.id is not None)
        else:
            image_id = parameters["image"].get("image_file_id")
            # TODO: VK by OZ: this code dont work if ArticlePortalDivision updated
            if image_id:
                articleVersion.image_file_id = crop_image(image_id, parameters["image"]["coordinates"])
            else:
                articleVersion.image_file_id = None

            if type(articleVersion) == ArticlePortalDivision:
                tag_names = json["article"]["tags"]
                articleVersion.manage_article_tags(tag_names)

            articleVersion.save()
            if publication_id:
                articleVersion.insert_after(
                    json["portal_division"]["insert_after"], articleVersion.position_unique_filter()
                )
            return {
                "article": articleVersion.save().get_client_side_dict(more_fields="long"),
                "image": json["image"],
                "portal_division": portal_division_dict(articleVersion),
            }