Esempio n. 1
0
    def add_map_feature_types(self, types):
        """
        add_map_feature_types(self, types)

        types is a list of map feature class names.

        Add these types to the instance config,
        save the instance!!!,
        and create udf rows for udfs that have settings defaults,
        if they don't already exist.
        """
        from treemap.models import MapFeature  # prevent circular import
        from treemap.audit import add_default_permissions

        classes = [MapFeature.get_subclass(type) for type in types]

        dups = set(types) & set(self.map_feature_types)
        if len(dups) > 0:
            raise ValidationError('Map feature types already added: %s' % dups)

        self._map_feature_types = list(self.map_feature_types) + list(types)
        self.save()

        for type, clz in zip(types, classes):
            settings = (getattr(clz, 'udf_settings', {}))
            for udfc_name, udfc_settings in settings.items():
                if udfc_settings.get('defaults'):
                    get_or_create_udf(self, type, udfc_name)

        add_default_permissions(self, models=classes)
Esempio n. 2
0
    def add_map_feature_types(self, types):
        """
        add_map_feature_types(self, types)

        types is a list of map feature class names.

        Add these types to the instance config,
        save the instance!!!,
        and create udf rows for udfs that have settings defaults,
        if they don't already exist.
        """
        from treemap.models import MapFeature  # prevent circular import
        from treemap.audit import add_default_permissions

        classes = [MapFeature.get_subclass(type) for type in types]

        dups = set(types) & set(self.map_feature_types)
        if len(dups) > 0:
            raise ValidationError('Map feature types already added: %s' % dups)

        self._map_feature_types = list(self.map_feature_types) + list(types)
        self.save()

        for type, clz in zip(types, classes):
            settings = (getattr(clz, 'udf_settings', {}))
            for udfc_name, udfc_settings in settings.items():
                if udfc_settings.get('defaults'):
                    get_or_create_udf(self, type, udfc_name)

        add_default_permissions(self, models=classes)
Esempio n. 3
0
    def assertTaskProducesCSV(self, user, model, assert_fields_and_values):
        self._assertTaskProducesCSVBase(user, model, assert_fields_and_values)

        # run the test again without a user
        # catches original version of:
        # https://github.com/OpenTreeMap/otm-core/issues/1384
        # "initial_qs referenced before assignment"
        add_default_permissions(self.instance, [self.instance.default_role])
        self._assertTaskProducesCSVBase(None, model, assert_fields_and_values)
Esempio n. 4
0
    def assertTaskProducesCSV(self, user, model, assert_fields_and_values):
        self._assertTaskProducesCSVBase(user, model, assert_fields_and_values)

        # run the test again without a user
        # catches original version of:
        # https://github.com/OpenTreeMap/OTM2/issues/1384
        # "initial_qs referenced before assignment"
        add_default_permissions(self.instance, [self.instance.default_role])
        self._assertTaskProducesCSVBase(None, model, assert_fields_and_values)
Esempio n. 5
0
def _make_loaded_role(instance, name, default_permission, permissions=(),
                      rep_thresh=2):
    role, created = Role.objects.get_or_create(
        name=name, instance=instance, default_permission=default_permission,
        rep_thresh=rep_thresh)
    role.save()

    add_default_permissions(instance, [role])
    _set_permissions(instance, role, permissions)

    return role
Esempio n. 6
0
    def setup_env(self, *args, **options):
        """ Create some seed data """
        if options['instance']:
            instance = Instance.objects.get(pk=options['instance'])
        elif options['instance_url_name']:
            instance = Instance.objects.get(
                url_name=options['instance_url_name'])
        else:
            raise Exception("must provide instance")

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role.objects.get_or_create(name=Role.ADMINISTRATOR,
                                           rep_thresh=0,
                                           instance=instance,
                                           default_permission=3)
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r[0])
            instance_user.save_with_user(user)
            self.stdout.write(
                'Added system user to instance with ADMINISTRATOR role')

        add_default_permissions(instance)

        dt = 0
        dp = 0
        if options.get('delete', False):
            for t in Tree.objects.all():
                t.delete_with_user(user)
                dt += 1
            for p in Plot.objects.all():
                p.delete_with_user(user)
                dp += 1

            self.stdout.write("Deleted %s trees and %s plots" % (dt, dp))

        dr = 0
        if options.get('delete_resources', False):
            for f in MapFeature.objects.all():
                if f.feature_type != 'Plot':
                    f.delete_with_user(user)
                    dr += 1

            self.stdout.write("Deleted %s resources" % dr)

        return instance, user
Esempio n. 7
0
def _make_loaded_role(instance, name, default_permission, permissions=(),
                      rep_thresh=2):
    role, created = Role.objects.get_or_create(
        name=name, instance=instance, default_permission=default_permission,
        rep_thresh=rep_thresh)
    role.save()

    add_default_permissions(instance, [role])
    _set_permissions(instance, role, permissions)

    return role
Esempio n. 8
0
    def setup_env(self, *args, **options):
        """ Create some seed data """
        if options['instance']:
            instance = Instance.objects.get(pk=options['instance'])
        elif options['instance_url_name']:
            instance = Instance.objects.get(
                url_name=options['instance_url_name'])
        else:
            raise Exception("must provide instance")

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role.objects.get_or_create(name=Role.ADMINISTRATOR,
                                           rep_thresh=0,
                                           instance=instance,
                                           default_permission=3)
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r[0])
            instance_user.save_with_user(user)
            self.stdout.write(
                'Added system user to instance with ADMINISTRATOR role')

        add_default_permissions(instance)

        dt = 0
        dp = 0
        if options.get('delete', False):
            for t in Tree.objects.all():
                t.delete_with_user(user)
                dt += 1
            for p in Plot.objects.all():
                p.delete_with_user(user)
                dp += 1

            self.stdout.write("Deleted %s trees and %s plots" % (dt, dp))

        dr = 0
        if options.get('delete_resources', False):
            for f in MapFeature.objects.all():
                if f.feature_type != 'Plot':
                    f.delete_with_user(user)
                    dr += 1

            self.stdout.write("Deleted %s resources" % dr)

        return instance, user
Esempio n. 9
0
def _make_loaded_role(instance, name, default_permission_level, permissions=(),
                      rep_thresh=2):
    role, __ = Role.objects.get_or_create(
        name=name, instance=instance,
        default_permission_level=default_permission_level,
        rep_thresh=rep_thresh)
    role.save()

    add_default_permissions(instance, {role})
    _set_permissions(instance, role, permissions)

    return role
Esempio n. 10
0
    def add_map_feature_types(self, types):
        from treemap.models import MapFeature  # prevent circular import
        from treemap.audit import add_default_permissions

        classes = [MapFeature.get_subclass(type) for type in types]

        dups = set(types) & set(self.map_feature_types)
        if len(dups) > 0:
            raise ValidationError('Map feature types already added: %s' % dups)

        self.map_feature_types = list(self.map_feature_types) + list(types)
        self.save()

        for type, clz in zip(types, classes):
            settings = (getattr(clz, 'udf_settings', {}))
            for udfc_name, udfc_settings in settings.items():
                if udfc_settings.get('defaults'):
                    get_or_create_udf(self, type, udfc_name)

        add_default_permissions(self, models=classes)
Esempio n. 11
0
    def add_map_feature_types(self, types):
        from treemap.models import MapFeature  # prevent circular import
        from treemap.audit import add_default_permissions

        classes = [MapFeature.get_subclass(type) for type in types]

        dups = set(types) & set(self.map_feature_types)
        if len(dups) > 0:
            raise ValidationError('Map feature types already added: %s' % dups)

        self.map_feature_types = list(self.map_feature_types) + list(types)
        self.save()

        for type, clz in zip(types, classes):
            settings = (getattr(clz, 'udf_settings', {}))
            for udfc_name, udfc_settings in settings.items():
                if udfc_settings.get('defaults'):
                    get_or_create_udf(self, type, udfc_name)

        add_default_permissions(self, models=classes)
Esempio n. 12
0
def roles_create(request, instance):
    params = json_from_request(request)

    role_name = params.get('name', None)

    if not role_name:
        return HttpResponseBadRequest(
            _("Must provide a name for the new role."))

    role, created = Role.objects.get_or_create(name=role_name,
                                               instance=instance,
                                               rep_thresh=0)

    if created is False:
        return HttpResponseBadRequest(
            _("A role with name '%(role_name)s' already exists") %
            {'role_name': role_name})

    add_default_permissions(instance, roles=[role])

    return roles_list(request, instance)
Esempio n. 13
0
def roles_create(request, instance):
    params = json_from_request(request)

    role_name = params.get('name', None)

    if not role_name:
        return HttpResponseBadRequest(
            _("Must provide a name for the new role."))

    role, created = Role.objects.get_or_create(name=role_name,
                                               instance=instance,
                                               rep_thresh=0)

    if created is False:
        return HttpResponseBadRequest(
            _("A role with name '%(role_name)s' already exists") %
            {'role_name': role_name})

    add_default_permissions(instance, roles=[role])

    return roles_list(request, instance)
Esempio n. 14
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise Exception(
                'Expected instance name as the first argument')

        name = args[0]

        if not options['user']:
            raise Exception('An admin user must be specified. with "--user"')

        if options.get('center', None) and options.get('geojson', None):
            raise Exception('You must specifiy only one of '
                            '"center" and "geojson"')
        elif (not options.get('center', None) and
              not options.get('geojson', None)):
            raise Exception('You must specifiy at least one of '
                            '"center" and "geojson"')

        if options['center']:
            center = options['center'].split(',')
            if len(center) != 2:
                raise Exception('Center should be a lat,lng pair in SRID 4326')

            center_pt = Point(float(center[0]), float(center[1]), srid=4326)

            # Bounding box built in web mercator to have units in meters
            center_pt.transform(3857)
            x = center_pt.x
            y = center_pt.y
            offset = 50000
            bounds = Polygon(((x - offset, y - offset),
                              (x - offset, y + offset),
                              (x + offset, y + offset),
                              (x + offset, y - offset),
                              (x - offset, y - offset)))

            bounds = MultiPolygon((bounds, ))
        else:
            bounds = GEOSGeometry(open(options['geojson'], srid=4326).read())

        if not options.get('url_name', None):
            raise Exception('You must specify a "url_name" starting with a '
                            'lowercase letter and containing lowercase '
                            'letters, numbers, and dashes ("-")')
        url_name = options.get('url_name')

        instance = Instance(
            config={},
            name=name,
            bounds=bounds,
            is_public=True,
            url_name=url_name)

        instance.seed_with_dummy_default_role()
        instance.full_clean()
        instance.save()

        instance.boundaries = Boundary.objects.filter(
            geom__intersects=bounds)

        role = Role.objects.create(
            name='user', instance=instance, rep_thresh=0,
            default_permission=FieldPermission.WRITE_DIRECTLY)

        add_default_permissions(instance, roles=[role])

        instance.default_role = role
        instance.save()

        user = User.objects.get(username=options['user'])
        InstanceUser(
            instance=instance,
            user=user,
            role=role,
            admin=True).save_with_user(user)
Esempio n. 15
0
    def setup_env(self, *args, **options):
        """ Create some seed data """
        if options['instance']:
            instance = Instance.objects.get(pk=options['instance'])
        elif options['instance_url_name']:
            instance = Instance.objects.get(
                url_name=options['instance_url_name'])
        else:
            raise Exception("must provide instance")

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role.objects.get_or_create(name=Role.ADMINISTRATOR,
                                           rep_thresh=0,
                                           instance=instance,
                                           default_permission_level=3)
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r[0])
            instance_user.save_with_user(user)
            self.stdout.write(
                'Added system user to instance with ADMINISTRATOR role')

        add_default_permissions(instance)

        if options.get('delete', False):
            # Can't delete through the ORM because it will pull all the data
            # into memory for signal handlers, then run out of memory and crash
            # BUT... cascading delete is not handled at the DB level, so we
            # need to delete from all related tables in the right order

            n_photo = MapFeaturePhoto.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_treephoto t
                    WHERE t.mapfeaturephoto_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeaturephoto p
                         WHERE p.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_mapfeaturephoto t WHERE t.instance_id = %s',  # NOQA
                    (instance.pk, ))
            self.stdout.write("Deleted %s photos" % n_photo)

            n_trees = Tree.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_tree t WHERE t.instance_id = %s',
                    (instance.pk, ))
            self.stdout.write("Deleted %s trees" % n_trees)

            n_favorites = Favorite.objects \
                .filter(map_feature__instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_favorite f
                    WHERE f.map_feature_id IN
                        (SELECT id
                         FROM treemap_mapfeature m
                         WHERE m.instance_id = %s)
                    """, (instance.pk, ))
            self.stdout.write("Deleted %s favorites" % n_favorites)

            n_comments = EnhancedThreadedComment.objects \
                .filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM otm_comments_enhancedthreadedcommentflag f
                    WHERE f.comment_id IN
                        (SELECT threadedcomment_ptr_id
                         FROM otm_comments_enhancedthreadedcomment c
                         WHERE c.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM otm_comments_enhancedthreadedcomment c
                    WHERE c.instance_id = %s
                    """, (instance.pk, ))
            self.stdout.write("Deleted %s comments" % n_comments)

            n_rows = TreeImportRow.objects \
                .filter(plot__instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    UPDATE importer_treeimportrow r
                    SET plot_id = NULL
                    WHERE r.import_event_id IN
                        (SELECT id
                         FROM importer_treeimportevent e
                         WHERE e.instance_id = %s)
                    """, (instance.pk, ))
            self.stdout.write("Nulled out plot in %s import rows" % n_rows)

            n_features = MapFeature.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_plot p
                    WHERE p.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_bioswale b
                    WHERE b.polygonalmapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_raingarden b
                    WHERE b.polygonalmapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_rainbarrel b
                    WHERE b.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_polygonalmapfeature b
                    WHERE b.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """, (instance.pk, ))
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_mapfeature f WHERE f.instance_id = %s',  # NOQA
                    (instance.pk, ))
            self.stdout.write("Deleted %s map features" % n_features)

            n_audits = Audit.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
    DELETE FROM treemap_audit a
    WHERE a.instance_id = %s
    AND a.model NOT IN
    ('InstanceUser', 'Species', 'ITreeCodeOverride', 'EnhancedInstance')
                    """, (instance.pk, ))
            self.stdout.write("Deleted %s audits" % n_audits)

        instance.update_revs('geo_rev', 'eco_rev', 'universal_rev')

        return instance, user
    def handle(self, *args, **options):
        if len(args) != 1:
            raise Exception('Expected instance name as the first argument')

        name = args[0]

        if not options['user']:
            raise Exception('An admin user must be specified. with "--user"')

        if options.get('center', None) and options.get('geojson', None):
            raise Exception('You must specifiy only one of '
                            '"center" and "geojson"')
        elif (not options.get('center', None)
              and not options.get('geojson', None)):
            raise Exception('You must specifiy at least one of '
                            '"center" and "geojson"')

        if options['center']:
            center = options['center'].split(',')
            if len(center) != 2:
                raise Exception('Center should be a lat,lng pair in SRID 4326')

            center_pt = Point(float(center[0]), float(center[1]), srid=4326)

            # Bounding box built in web mercator to have units in meters
            center_pt.transform(3857)
            x = center_pt.x
            y = center_pt.y
            offset = 50000
            bounds = Polygon(
                ((x - offset, y - offset), (x - offset, y + offset),
                 (x + offset, y + offset), (x + offset, y - offset),
                 (x - offset, y - offset)))

            bounds = MultiPolygon((bounds, ))
        else:
            bounds = GEOSGeometry(open(options['geojson'], srid=4326).read())

        if not options.get('url_name', None):
            raise Exception('You must specify a "url_name" starting with a '
                            'lowercase letter and containing lowercase '
                            'letters, numbers, and dashes ("-")')
        url_name = options.get('url_name')

        instance = Instance(config={},
                            name=name,
                            bounds=bounds,
                            is_public=True,
                            url_name=url_name)

        instance.seed_with_dummy_default_role()
        instance.full_clean()
        instance.save()

        instance.boundaries = Boundary.objects.filter(geom__intersects=bounds)

        role = Role.objects.create(
            name='user',
            instance=instance,
            rep_thresh=0,
            default_permission=FieldPermission.WRITE_DIRECTLY)

        add_default_permissions(instance, roles=[role])

        instance.default_role = role
        instance.save()

        user = User.objects.get(username=options['user'])
        InstanceUser(instance=instance, user=user, role=role,
                     admin=True).save_with_user(user)
Esempio n. 17
0
    def setup_env(self, *args, **options):
        """ Create some seed data """
        if options['instance']:
            instance = Instance.objects.get(pk=options['instance'])
        elif options['instance_url_name']:
            instance = Instance.objects.get(
                url_name=options['instance_url_name'])
        else:
            raise Exception("must provide instance")

        try:
            user = User.system_user()
        except User.DoesNotExist:
            self.stdout.write('Error: Could not find a superuser to use')
            return 1

        instance_user = user.get_instance_user(instance)

        if instance_user is None:
            r = Role.objects.get_or_create(name=Role.ADMINISTRATOR,
                                           rep_thresh=0,
                                           instance=instance,
                                           default_permission=3)
            instance_user = InstanceUser(instance=instance,
                                         user=user,
                                         role=r[0])
            instance_user.save_with_user(user)
            self.stdout.write(
                'Added system user to instance with ADMINISTRATOR role')

        add_default_permissions(instance)

        if options.get('delete', False):
            # Can't delete through the ORM because it will pull all the data
            # into memory for signal handlers, then run out of memory and crash
            # BUT... cascading delete is not handled at the DB level, so we
            # need to delete from all related tables in the right order

            n_photo = MapFeaturePhoto.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_treephoto t
                    WHERE t.mapfeaturephoto_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeaturephoto p
                         WHERE p.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_mapfeaturephoto t WHERE t.instance_id = %s',  # NOQA
                    (instance.pk,))
            self.stdout.write("Deleted %s photos" % n_photo)

            n_trees = Tree.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_tree t WHERE t.instance_id = %s',
                    (instance.pk,))
            self.stdout.write("Deleted %s trees" % n_trees)

            n_favorites = Favorite.objects \
                .filter(map_feature__instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_favorite f
                    WHERE f.map_feature_id IN
                        (SELECT id
                         FROM treemap_mapfeature m
                         WHERE m.instance_id = %s)
                    """,
                    (instance.pk,))
            self.stdout.write("Deleted %s favorites" % n_favorites)

            n_comments = EnhancedThreadedComment.objects \
                .filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM otm_comments_enhancedthreadedcommentflag f
                    WHERE f.comment_id IN
                        (SELECT threadedcomment_ptr_id
                         FROM otm_comments_enhancedthreadedcomment c
                         WHERE c.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM otm_comments_enhancedthreadedcomment c
                    WHERE c.instance_id = %s
                    """,
                    (instance.pk,))
            self.stdout.write("Deleted %s comments" % n_comments)

            n_rows = TreeImportRow.objects \
                .filter(plot__instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    UPDATE importer_treeimportrow r
                    SET plot_id = NULL
                    WHERE r.import_event_id IN
                        (SELECT id
                         FROM importer_treeimportevent e
                         WHERE e.instance_id = %s)
                    """,
                    (instance.pk,))
            self.stdout.write("Nulled out plot in %s import rows" % n_rows)

            n_features = MapFeature.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM treemap_plot p
                    WHERE p.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_bioswale b
                    WHERE b.polygonalmapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_raingarden b
                    WHERE b.polygonalmapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_rainbarrel b
                    WHERE b.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    DELETE FROM stormwater_polygonalmapfeature b
                    WHERE b.mapfeature_ptr_id IN
                        (SELECT id
                         FROM treemap_mapfeature f
                         WHERE f.instance_id = %s)
                    """,
                    (instance.pk,))
            with connection.cursor() as cursor:
                cursor.execute(
                    'DELETE FROM treemap_mapfeature f WHERE f.instance_id = %s',  # NOQA
                    (instance.pk,))
            self.stdout.write("Deleted %s map features" % n_features)

            n_audits = Audit.objects.filter(instance=instance).count()
            with connection.cursor() as cursor:
                cursor.execute(
                    """
    DELETE FROM treemap_audit a
    WHERE a.instance_id = %s
    AND a.model NOT IN
    ('InstanceUser', 'Species', 'ITreeCodeOverride', 'EnhancedInstance')
                    """,
                    (instance.pk,))
            self.stdout.write("Deleted %s audits" % n_audits)

        return instance, user
Esempio n. 18
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise Exception('Expected instance name as the first argument')

        name = args[0]

        if not options['user']:
            logger.warning('An admin user was not specified. While not a '
                           'problem initially, no users will be able to '
                           'modify many parts of this instance. It is '
                           'recommended that you create a user first and call '
                           'this command with "--user"')

        if options.get('center', None) and options.get('geojson', None):
            raise Exception('You must specifiy only one of '
                            '"center" and "geojson"')
        elif (not options.get('center', None)
              and not options.get('geojson', None)):
            raise Exception('You must specifiy at least one of '
                            '"center" and "geojson"')

        if options['center']:
            center = options['center'].split(',')
            if len(center) != 2:
                raise Exception('Center should be an x,y pair in EPSG3857')

            x = int(center[0])
            y = int(center[1])
            offset = 50000
            bounds = Polygon(
                ((x - offset, y - offset), (x - offset, y + offset),
                 (x + offset, y + offset), (x + offset, y - offset),
                 (x - offset, y - offset)))

            bounds = MultiPolygon((bounds, ))
        else:
            bounds = GEOSGeometry(open(options['geojson']).read())

        if not options.get('url_name', None):
            raise Exception('You must specify a "url_name" starting with a '
                            'lowercase letter and containing lowercase '
                            'letters, numbers, and dashes ("-")')
        url_name = options.get('url_name')

        # Instances need roles and roles needs instances... crazy
        # stuff we're going to create the needed role below however,
        # we'll temporarily use a 'dummy role'. The dummy role has
        # no instance.
        dummy_roles = Role.objects.filter(instance__isnull=True)
        if len(dummy_roles) == 0:
            dummy_role = Role.objects.create(name='empty', rep_thresh=0)
        else:
            dummy_role = dummy_roles[0]

        instance = Instance(config={},
                            name=name,
                            bounds=bounds,
                            is_public=True,
                            default_role=dummy_role,
                            url_name=url_name)

        instance.full_clean()
        instance.save()

        instance.boundaries = Boundary.objects.filter(geom__intersects=bounds)

        role = Role.objects.create(
            name='user',
            instance=instance,
            rep_thresh=0,
            default_permission=FieldPermission.WRITE_DIRECTLY)

        add_default_permissions(instance, roles=[role])

        instance.default_role = role
        instance.save()

        user = User.objects.get(pk=options['user'])
        InstanceUser(instance=instance, user=user, role=role,
                     admin=True).save_with_user(user)
Esempio n. 19
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise Exception(
                'Expected instance name as the first argument')

        name = args[0]

        if not options['user']:
            raise Exception('An admin user must be specified. with "--user"')

        if options.get('center', None) and options.get('geojson', None):
            raise Exception('You must specifiy only one of '
                            '"center" and "geojson"')
        elif (not options.get('center', None) and
              not options.get('geojson', None)):
            raise Exception('You must specifiy at least one of '
                            '"center" and "geojson"')

        if options['center']:
            center = options['center'].split(',')
            if len(center) != 2:
                raise Exception('Center should be a lon,lat pair')

            center_pt = Point(float(center[0]), float(center[1]), srid=4326)

            # Bounding box built in web mercator to have units in meters
            center_pt.transform(3857)
            x = center_pt.x
            y = center_pt.y
            instance_bounds = InstanceBounds.create_from_point(x, y)
        else:
            geom = GEOSGeometry(open(options['geojson'], srid=4326).read())
            instance_bounds = InstanceBounds.objects.create(geom=geom)

        if not options.get('url_name', None):
            raise Exception('You must specify a "url_name" starting with a '
                            'lowercase letter and containing lowercase '
                            'letters, numbers, and dashes ("-")')
        url_name = options.get('url_name')

        instance = Instance(
            config={},
            name=name,
            bounds=instance_bounds,
            is_public=True,
            url_name=url_name)

        instance.seed_with_dummy_default_role()
        instance.full_clean()
        instance.save()

        instance.boundaries = Boundary.objects.filter(
            geom__intersects=instance_bounds.geom)

        role = Role.objects.create(
            name='user', instance=instance, rep_thresh=0,
            default_permission=FieldPermission.WRITE_DIRECTLY)

        create_stewardship_udfs(instance)

        add_species_to_instance(instance)

        add_default_permissions(instance, roles=[role])

        eco_benefits_conversion = \
            BenefitCurrencyConversion.get_default_for_point(Point(x, y))
        if eco_benefits_conversion:
            eco_benefits_conversion.save()

        instance.eco_benefits_conversion = eco_benefits_conversion

        instance.default_role = role
        instance.save()

        user = User.objects.get(username=options['user'])
        InstanceUser(
            instance=instance,
            user=user,
            role=role,
            admin=True).save_with_user(user)
    def handle(self, *args, **options):
        if len(args) != 1:
            raise Exception('Expected instance name as the first argument')

        name = args[0]

        if not options['user']:
            raise Exception('An admin user must be specified. with "--user"')

        if options.get('center', None) and options.get('geojson', None):
            raise Exception('You must specifiy only one of '
                            '"center" and "geojson"')
        elif (not options.get('center', None)
              and not options.get('geojson', None)):
            raise Exception('You must specifiy at least one of '
                            '"center" and "geojson"')

        if options['center']:
            center = options['center'].split(',')
            if len(center) != 2:
                raise Exception('Center should be a lon,lat pair')

            center_pt = Point(float(center[0]), float(center[1]), srid=4326)

            # Bounding box built in web mercator to have units in meters
            center_pt.transform(3857)
            x = center_pt.x
            y = center_pt.y
            instance_bounds = InstanceBounds.create_from_point(x, y)
        else:
            geom = GEOSGeometry(open(options['geojson'], srid=4326).read())
            instance_bounds = InstanceBounds.objects.create(geom=geom)

        if not options.get('url_name', None):
            raise Exception('You must specify a "url_name" starting with a '
                            'lowercase letter and containing lowercase '
                            'letters, numbers, and dashes ("-")')
        url_name = options.get('url_name')

        instance = Instance(config={},
                            name=name,
                            bounds=instance_bounds,
                            is_public=True,
                            url_name=url_name)

        instance.seed_with_dummy_default_role()
        instance.full_clean()
        instance.save()

        instance.boundaries = Boundary.objects.filter(
            geom__intersects=instance_bounds.geom)

        role = Role.objects.create(
            name='user',
            instance=instance,
            rep_thresh=0,
            default_permission_level=FieldPermission.WRITE_DIRECTLY)

        create_stewardship_udfs(instance)

        add_species_to_instance(instance)

        add_default_permissions(instance, roles=[role])
        add_instance_permissions([role])

        eco_benefits_conversion = \
            BenefitCurrencyConversion.get_default_for_instance(instance)
        if eco_benefits_conversion:
            eco_benefits_conversion.save()
            instance.eco_benefits_conversion = eco_benefits_conversion

        instance.default_role = role
        instance.save()

        user = User.objects.get(username=options['user'])
        InstanceUser(instance=instance, user=user, role=role,
                     admin=True).save_with_user(user)
Esempio n. 21
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise Exception("Expected instance name as the first argument")

        name = args[0]

        if not options["user"]:
            logger.warning(
                "An admin user was not specified. While not a "
                "problem initially, no users will be able to "
                "modify many parts of this instance. It is "
                "recommended that you create a user first and call "
                'this command with "--user"'
            )

        if options.get("center", None) and options.get("geojson", None):
            raise Exception("You must specifiy only one of " '"center" and "geojson"')
        elif not options.get("center", None) and not options.get("geojson", None):
            raise Exception("You must specifiy at least one of " '"center" and "geojson"')

        if options["center"]:
            center = options["center"].split(",")
            if len(center) != 2:
                raise Exception("Center should be an x,y pair in EPSG3857")

            x = int(center[0])
            y = int(center[1])
            offset = 50000
            bounds = Polygon(
                (
                    (x - offset, y - offset),
                    (x - offset, y + offset),
                    (x + offset, y + offset),
                    (x + offset, y - offset),
                    (x - offset, y - offset),
                )
            )

            bounds = MultiPolygon((bounds,))
        else:
            bounds = GEOSGeometry(open(options["geojson"]).read())

        if not options.get("url_name", None):
            raise Exception(
                'You must specify a "url_name" starting with a '
                "lowercase letter and containing lowercase "
                'letters, numbers, and dashes ("-")'
            )
        url_name = options.get("url_name")

        # Instances need roles and roles needs instances... crazy
        # stuff we're going to create the needed role below however,
        # we'll temporarily use a 'dummy role'. The dummy role has
        # no instance.
        dummy_roles = Role.objects.filter(instance__isnull=True)
        if len(dummy_roles) == 0:
            dummy_role = Role.objects.create(name="empty", rep_thresh=0)
        else:
            dummy_role = dummy_roles[0]

        instance = Instance(
            config={}, name=name, bounds=bounds, is_public=True, default_role=dummy_role, url_name=url_name
        )

        instance.full_clean()
        instance.save()

        instance.boundaries = Boundary.objects.filter(geom__intersects=bounds)

        role = Role.objects.create(
            name="user", instance=instance, rep_thresh=0, default_permission=FieldPermission.WRITE_DIRECTLY
        )

        add_default_permissions(instance, roles=[role])

        instance.default_role = role
        instance.save()

        user = User.objects.get(pk=options["user"])
        InstanceUser(instance=instance, user=user, role=role, admin=True).save_with_user(user)