Esempio n. 1
0
    def get_facility(self, options):
        if options["facility"]:
            default_facility = Facility.objects.get(pk=options["facility"])
        else:
            default_facility = Facility.get_default_facility()

        return default_facility
Esempio n. 2
0
def infer_facility(facility_id, facility=None):
    if facility_id:
        try:
            # Try lookup by id first, then name
            facility = Facility.objects.get(pk=facility_id)
        except (Facility.DoesNotExist, ValueError):
            try:
                facility = Facility.objects.get(name=facility_id)
            except Facility.DoesNotExist:
                raise ValueError(
                    "Facility matching identifier {facility} was not found".
                    format(facility=facility_id))
    elif facility is not None:
        return facility
    else:
        facility = Facility.get_default_facility()
        if facility:
            logger.info(
                "No facility specified, using the default facility {}".format(
                    facility.name))
        else:
            raise ValueError(
                "No default facility exists, please make sure to provision this device before running this command"
            )
    return facility
Esempio n. 3
0
 def get(self, request):
     """
     Redirects a guest user to a learner accessible page.
     """
     dataset = getattr(Facility.get_default_facility(), "dataset", None)
     if dataset and dataset.allow_guest_access:
         return HttpResponseRedirect(get_url_by_role(user_kinds.LEARNER, False))
     return RootURLRedirectView.as_view()(request)
    def test_get_default_facility(self):
        # Get Default facility using Facility class method
        def_facility = Facility.get_default_facility()

        # Get default facility using get_facility_or_default with no arguments
        get_facitity = get_facility_or_default()

        # check that the two facility_ids are equal
        assert def_facility.id == get_facitity.id
Esempio n. 5
0
    def get_facility(self, options):
        if options["facility"]:
            default_facility = Facility.objects.get(pk=options["facility"])
        else:
            default_facility = Facility.get_default_facility()
        if not default_facility:
            self.overall_error.append(MESSAGES[NO_FACILITY])
            raise CommandError(self.overall_error[-1])

        return default_facility
Esempio n. 6
0
 def infer_dataset(self, *args, **kwargs):
     if self.user_id:
         return self.cached_related_dataset_lookup("user")
     elif self.dataset_id:
         # confirm that there exists a facility with that dataset_id
         try:
             return Facility.objects.get(dataset_id=self.dataset_id).dataset_id
         except Facility.DoesNotExist:
             pass
     # if no user or matching facility, infer dataset from the default facility
     facility = Facility.get_default_facility()
     assert facility, "Before you can save logs, you must have a facility"
     return facility.dataset_id
Esempio n. 7
0
def create_facility(facility_name=None, preset=None, interactive=False):
    if facility_name is None and interactive:
        answer = get_user_response(
            "Do you wish to create a facility? [y/n] ", ["y", "n"]
        )
        if answer == "y":
            facility_name = get_user_response(
                "What do you wish to name your facility? ", to_lower_case=False
            )
        else:
            sys.exit(1)

    if facility_name:
        facility_query = Facility.objects.filter(name__iexact=facility_name)

        if facility_query.exists():
            facility = facility_query.get()
            logger.warn(
                "Facility with name '{name}' already exists, not modifying preset.".format(
                    name=facility.name
                )
            )
            return facility
        else:
            facility = Facility.objects.create(name=facility_name)
            logger.info(
                "Facility with name '{name}' created.".format(name=facility.name)
            )

        if preset is None and interactive:
            preset = get_user_response(
                "Which preset do you wish to use? [{presets}]: ".format(
                    presets="/".join(presets.keys())
                ),
                valid_answers=presets,
            )

        # Only set preset data if we have created the facility, otherwise leave previous data intact
        if preset:
            dataset_data = mappings[preset]
            facility.dataset.preset = preset
            for key, value in dataset_data.items():
                check_facility_setting(key)
                setattr(facility.dataset, key, value)
            facility.dataset.save()
            logger.info("Facility preset changed to {preset}.".format(preset=preset))
    else:
        facility = Facility.get_default_facility() or Facility.objects.first()
        if not facility:
            raise CommandError("No facility exists")
    return facility
Esempio n. 8
0
    def handle(self, *args, **options):
        if options["facility"]:
            default_facility = Facility.objects.get(pk=options["facility"])
        else:
            default_facility = Facility.get_default_facility()

        if not default_facility:
            raise CommandError(
                "No default facility exists, please make sure to provision this device before running this command"
            )

        fieldnames = [
            "full_name",
            "username",
            "password",
            "facility",
            "class",
            "gender",
            "birth_year",
            "id_number",
        ]
        # open using default OS encoding
        with open(options["filepath"]) as f:
            header = next(csv.reader(f, strict=True))
            if all(col in fieldnames for col in header):
                # Every item in the first row matches an item in the fieldnames, it is a header row
                if "username" not in header:
                    raise CommandError(
                        "No usernames specified, this is required for user creation"
                    )
                ordered_fieldnames = header
            elif any(col in fieldnames for col in header):
                raise CommandError(
                    "Mix of valid and invalid header labels found in first row"
                )
            else:
                ordered_fieldnames = fieldnames

        # open using default OS encoding
        with open(options["filepath"]) as f:
            reader = csv.DictReader(f,
                                    fieldnames=ordered_fieldnames,
                                    strict=True)
            with transaction.atomic():
                create_func = partial(create_user,
                                      default_facility=default_facility)
                total = sum(starmap(create_func, enumerate(reader)))
                logger.info("{total} users created".format(total=total))
Esempio n. 9
0
    def handle(self, *args, **options):
        if options["facility"]:
            default_facility = Facility.objects.get(pk=options["facility"])
        else:
            default_facility = Facility.get_default_facility()

        if not default_facility:
            raise CommandError(
                "No default facility exists, please make sure to provision this device before running this command"
            )

        fieldnames = input_fields + tuple(val for val in labels.values())

        # open using default OS encoding
        with open(options["filepath"]) as f:
            header = next(csv.reader(f, strict=True))
            has_header = False
            if all(col in fieldnames for col in header):
                # Every item in the first row matches an item in the fieldnames, it is a header row
                if "username" not in header and str(
                        labels["username"]) not in header:
                    raise CommandError(
                        "No usernames specified, this is required for user creation"
                    )
                has_header = True
            elif any(col in fieldnames for col in header):
                raise CommandError(
                    "Mix of valid and invalid header labels found in first row"
                )

        # open using default OS encoding
        with open(options["filepath"]) as f:
            if has_header:
                reader = csv.DictReader(f, strict=True)
            else:
                reader = csv.DictReader(f,
                                        fieldnames=input_fields,
                                        strict=True)
            with transaction.atomic():
                total = 0
                for row in reader:
                    total += int(
                        create_user(map_input(row),
                                    default_facility=default_facility))
                logger.info("{total} users created".format(total=total))
Esempio n. 10
0
)  # noqa E402

# Initalize argparse and define command line args that can be passed to this module
argParser = argparse.ArgumentParser()
argParser.add_argument("--file", "-f", help="File to create users from")

argParser.add_argument(
    "--centre",
    "-c",
    help=
    "Name of Facility( centre_id) in the case of multiple facilities on 1 device",
)

# Get the name of the default facility on the device
# used as the default value in case facility is not passed in
def_facility = str(Facility.get_default_facility().name)


def enroll_learners_into_class(input_file,
                               facilityname=def_facility,
                               delete_existing_memberships=True):
    """Function to enroll learners into classes using a csv file
    The file is expected to have columns user_id, centre, and grade. All other columns are ignored
    The grade column represents the name of the classroom the learner should be enrolled into.
    It is assumed that the classrooms have already been created

    Args:
        input_file (string): Path to the csv file containing the users
        facility (string): Name of the facility which contains the classrooms(default facility if not specified)

    Returns:
 def test_create_facility_set_preset(self):
     default_facility = Facility.get_default_facility()
     dataset_data = mappings[self.preset]
     for key, value in dataset_data.items():
         self.assertEqual(getattr(default_facility.dataset, key), value)
 def test_no_facility_return_default(self):
     setup_device()
     default_facility = Facility.get_default_facility()
     facility = create_facility(facility_name=default_facility.name)
     self.assertEqual(default_facility, facility)
 def test_create_device_settings_default_facility(self):
     default_facility = Facility.get_default_facility()
     self.assertEqual(DeviceSettings.objects.get().default_facility,
                      default_facility)