def get_input_fields_for_model(model, only_fields, exclude_fields, optional_fields=(), required_fields=(), many_to_many_extras=None, foreign_key_extras=None, many_to_one_extras=None, parent_type_name="", field_types=None) -> OrderedDict: registry = get_global_registry() meta_registry = get_type_meta_registry() model_fields = get_model_fields(model) many_to_many_extras = many_to_many_extras or {} foreign_key_extras = foreign_key_extras or {} many_to_one_extras = many_to_one_extras or {} field_types = field_types or {} fields = OrderedDict() fields_lookup = {} for name, field in model_fields: # We ignore the primary key if getattr(field, "primary_key", False): continue # If the field has an override, use that if name in field_types: fields[name] = field_types[name] continue # Save for later fields_lookup[name] = field is_not_in_only = only_fields and name not in only_fields # is_already_created = name in options.fields is_excluded = name in exclude_fields # or is_already_created # https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_query_name is_no_backref = str(name).endswith("+") if is_not_in_only or is_excluded or is_no_backref: # We skip this field if we specify only_fields and is not # in there. Or when we exclude this field in exclude_fields. # Or when there is no back reference. continue required = None if name in optional_fields: required = False elif name in required_fields: required = True converted = convert_django_field_with_choices( field, registry, required, many_to_many_extras.get(name, {}).get('exact'), foreign_key_extras.get(name, {})) fields[name] = converted # Create extra many_to_many_fields for name, extras in many_to_many_extras.items(): field = fields_lookup.get(name) if field is None: raise GraphQLError( f"Error adding extras for {name} in model f{model}. Field {name} does not exist." ) for extra_name, data in extras.items(): # This is handled above if extra_name == "exact": continue if isinstance(data, bool): data = {} _type_name = data.get('type') _field = convert_many_to_many_field(field, registry, False, data, None) # Default to the same as the "exact" version if not _field: _field = fields[name] # operation = data.get('operation') or get_likely_operation_from_name(extra_name) fields[name + "_" + extra_name] = _field for name, extras in many_to_one_extras.items(): field = fields_lookup.get(name) if field is None: raise GraphQLError( f"Error adding extras for {name} in model f{model}. Field {name} does not exist." ) for extra_name, data in extras.items(): argument_name = data.get('name', name + "_" + extra_name) # Override default if extra_name == "exact": argument_name = name if isinstance(data, bool): data = {"type": 'ID'} _type = data.get('type') if not _type or _type == "auto": # Create new type. _type_name = data.get( 'type_name', f"{parent_type_name}Create{model.__name__}{name.capitalize()}" ) converted_fields = get_input_fields_for_model( field.related_model, data.get('only_fields', ()), data.get( 'exclude_fields', (field.field.name, ) ), # Exclude the field referring back to the foreign key data.get('optional_fields', ()), data.get('required_fields', ()), data.get('many_to_many_extras'), data.get('foreign_key_extras'), data.get('many_to_one_extras'), parent_type_name=_type_name, field_types=data.get('field_types')) InputType = type(_type_name, (InputObjectType, ), converted_fields) meta_registry.register( _type_name, { 'auto_context_fields': data.get( 'auto_context_fields', {}), 'optional_fields': data.get('optional_fields', ()), 'required_fields': data.get('required_fields', ()), 'many_to_many_extras': data.get( 'many_to_many_extras', {}), 'many_to_one_extras': data.get('many_to_one_extras', {}), 'foreign_key_extras': data.get('auto_context_fields', {}), 'field_types': data.get('field_types', {}), }) _field = graphene.List(type(_type_name, (InputObjectType, ), converted_fields), required=False) else: _field = convert_many_to_many_field(field, registry, False, data, None) fields[argument_name] = _field return fields
def report_error(context: ValidationContext, error: Exception): context.report_error(GraphQLError(str(error), original_error=error))
def resolve_article(self, info, **kwargs): slug = kwargs.get('slug') try: return get_model_object(Article, 'slug', slug) except: raise GraphQLError("Article does not exist")
def validate_operation_name(operation_name) -> None: if operation_name is not None and not isinstance(operation_name, str): raise GraphQLError('"%s" is not a valid operation name.' % operation_name)
def resolve_profile(self,info,id): try: profile = Profile.objects.get(id=id) except Profile.DoesNotExist: raise GraphQLError('Profile with given id doesnt exist') return profile
def enter_field(self, node, *args) -> None: if node.name.value == "example": self.report_error(GraphQLError("Can't query field 'example'"))
def validate_query_body(query) -> None: if not query or not isinstance(query, str): raise GraphQLError("The query must be a string.")
def foreign_key_conflict(self, entity_name, entity): # Database foreign key error raise GraphQLError( '{} {} does not exists'.format(entity_name, entity))
def db_connection(self): # Database connection error raise GraphQLError('Error: Could not connect to Db')
def mutate(self, info, enrollments, **kwargs): owner = Admin.objects.get(user=info.context.user) business_id = owner.business.id error_excel = "" wb = create_enrollment_templates(business_id, show_errors=True) overall_total = 0 total_errors = 0 xls = pd.ExcelFile(enrollments.read()) # check all course spreadsheets reflect courses that exist def isValidCourseSheetName(sheet_name): if sheet_name == "Student Roster (hidden)": return True # check sheet name matches "name - id" valid_sheet_name = COURSE_SHEET_NAME_PATTERN.search(sheet_name) if not valid_sheet_name: return False # check id and title exist in database course_title, course_id = valid_sheet_name.groups() if (not Course.objects.business(business_id).filter( id=course_id, title=course_title).exists()): return False return True invalid_sheet_names = [ sheet_name for sheet_name in xls.sheet_names if not isValidCourseSheetName(sheet_name) ] if invalid_sheet_names: raise GraphQLError( "Invalid spreadsheet names in Enrollments worksheet: " + str(invalid_sheet_names)) # upload enrollments for sheet_name in wb.sheetnames: if sheet_name == "Student Roster (hidden)": continue # extract spreadsheet and use 8th row (7th 0-indexed) for header, skipping all previous rows enrollment_df = pd.read_excel(xls, sheet_name=sheet_name, skiprows=7, header=0, usecols=[0]) # check students enrolled columns exists enrollment_ws_missing_columns = {"Students Enrolled"} - set( enrollment_df.columns.values) if len(enrollment_ws_missing_columns) > 0: raise GraphQLError( f"Missing columns in enrollments worksheet ({sheet_name}): " + str(enrollment_ws_missing_columns)) # extract the course course_title, course_id = COURSE_SHEET_NAME_PATTERN.search( sheet_name).groups() course = (Course.objects.business(business_id).filter( id=int(course_id), title=course_title).first()) # create enrollments enrollment_df = enrollment_df.dropna(how="all") enrollment_error_df = [] for _index, row in enrollment_df.iloc[0:].iterrows(): entry = row["Students Enrolled"] student_email = (entry[entry.find("(") + 1:entry.find(")")] if entry.find("(") and entry.find(")") else "") if not Student.objects.filter( user__email=student_email).exists(): enrollment_error_df.append(row.to_dict()) enrollment_error_df[-1][ "Error Message"] = "No student with that email exists. Please check the entry again." continue try: with transaction.atomic(): student = Student.objects.get( user__email=student_email) enrollment_object = Enrollment.objects.create( student=student, course=course, invite_status=Enrollment.SENT, ) except Exception as e: enrollment_error_df.append(row.to_dict()) enrollment_error_df[-1]["Error Message"] = str(e) continue total = enrollment_df.shape[0] errors = len(enrollment_error_df) if errors > 0: enrollments_ws = wb.get_sheet_by_name(sheet_name) enrollments_column_order = [ cell.value for cell in enrollments_ws[8] ][:2] for index, row_error in enumerate(enrollment_error_df): for col in range(len(enrollments_column_order)): enrollments_ws.cell(row=9 + index, column=1 + col).value = row_error[ enrollments_column_order[col]] autosize_ws_columns(enrollments_ws) overall_total += total total_errors += errors if total_errors > 0: error_excel = workbook_to_base64(wb) return UploadEnrollmentsMutation( total_success=overall_total - total_errors, total_failure=total_errors, error_excel=error_excel, )
def check_conflict(self, entity_name, entity): # Database integrity error raise GraphQLError( '{} {} already exists'.format(entity_name, entity))
def mutate(self, info, courses, **kwargs): owner = Admin.objects.get(user=info.context.user) business_id = owner.business.id business = Business.objects.get(id=business_id) xls = pd.ExcelFile(courses.read()) # check all spreadsheets exist spreadsheet_names = ["Step 1 - Subject Categories", "Step 2 - Classes"] if not all(name in xls.sheet_names for name in spreadsheet_names): raise GraphQLError("Please include all spreadsheets: " + str(spreadsheet_names)) # extract spreadsheets and skip first comment row subjects_df = pd.read_excel(xls, sheet_name="Step 1 - Subject Categories", header=1) courses_df = pd.read_excel(xls, sheet_name="Step 2 - Classes", header=1) # check all column headers present subjects_ws_missing_columns = set( COURSE_SHEET_NAME_TO_REQUIRED_FIELDS["subjects"]) - set( subjects_df.columns.values) if len(subjects_ws_missing_columns) > 0: raise GraphQLError("Missing columns in subjects worksheet: " + str(subjects_ws_missing_columns)) courses_ws_missing_columns = set( COURSE_SHEET_NAME_TO_REQUIRED_FIELDS["courses"]) - set( courses_df.columns.values) if len(courses_ws_missing_columns) > 0: raise GraphQLError("Missing columns in courses workshet: " + str(courses_ws_missing_columns)) # create subjects subjects_df = subjects_df.dropna(how="all") subjects_df = subjects_df.where(pd.notnull(subjects_df), None) # cast np.Nan to None subjects_error_df = [] for _index, row in subjects_df.iloc[1:].iterrows(): required_fields_check = check_course_sheet_row(row, "subjects") if required_fields_check: subjects_error_df.append(row.to_dict()) subjects_error_df[-1]["Error Message"] = required_fields_check continue # include valid subjects in error file for courses that rely on them subjects_error_df.append(row.to_dict()) subjects_error_df[-1]["Error Message"] = "" try: # ignore subjects that already exist if CourseCategory.objects.filter( name=row.get("Subjects")).exists(): continue course_category = CourseCategory( name=row.get("Subjects"), description=row.get("Description")) course_category.save() except Exception as e: subjects_error_df[-1]["Error Message"] = str(e) continue LogEntry.objects.log_action( user_id=info.context.user.id, content_type_id=ContentType.objects.get_for_model( CourseCategory).pk, object_id=course_category.id, object_repr=course_category.name, action_flag=ADDITION, ) # create courses def extract_from_parenthesis(s): if s: return s[s.find("(") + 1:s.find(")")] else: return s academic_level_to_enum_str = { "Elementary": "elementary_lvl", "Middle School": "middle_lvl", "High School": "high_lvl", "College": "college_lvl", } courses_df = courses_df.dropna(how="all") courses_df = courses_df.where(pd.notnull(courses_df), None) # cast np.Nan to None courses_error_df = [] dropdown_subject_names = set(subjects_df["Subjects"]) for _index, row in courses_df.iloc[1:].iterrows(): orig_instructor_field = row["Instructor"] row["Instructor"] = extract_from_parenthesis(row["Instructor"]) required_fields_check = check_course_sheet_row( row, "courses_minimum", business_id, dropdown_subject_names) if required_fields_check: courses_error_df.append(row.to_dict()) courses_error_df[-1]["Instructor"] = orig_instructor_field courses_error_df[-1]["Error Message"] = required_fields_check continue try: course = Course( business=business, title=row.get("Course Name"), course_category=CourseCategory.objects.get( name=row.get("Subject")), description=row.get("Course Description"), total_tuition=row.get("Total Tuition"), instructor=Instructor.objects.get( user__email=row.get("Instructor")), is_confirmed=row.get("Instructor Confirmed? (Y/N)") == "Y", academic_level=academic_level_to_enum_str[row.get( "Academic Level")], room=row.get("Room Location"), start_date=row.get("Start Date"), end_date=row.get("End Date"), course_type="class", max_capacity=int(row.get("Enrollment Capacity (>=4)")), ) course.save() except Exception as e: courses_error_df.append(row.to_dict()) courses_error_df[-1]["Instructor"] = orig_instructor_field courses_error_df[-1]["Error Message"] = str(e) continue # parse course availabilities availabilities = [{ "day_of_week": row.get(f"Session Day {i+1}").lower(), "start_time": row.get(f"Start Time {i+1}"), "end_time": row.get(f"End Time {i+1}"), } for i in range(5) if row.get(f"Session Day {i+1}")] # populate sessions and availabilities course_availabilities = create_availabilities_and_sessions( course, availabilities) # calculate total hours across all sessions total_hours = decimal.Decimal("0.0") for availability in course_availabilities: duration_sec = ( datetime.combine(date.min, availability.end_time) - datetime.combine(date.min, availability.start_time)).seconds duration_hours = decimal.Decimal(duration_sec) / (60 * 60) total_hours += duration_hours * availability.num_sessions course.hourly_tuition = course.total_tuition / total_hours course.save() course.refresh_from_db() LogEntry.objects.log_action( user_id=info.context.user.id, content_type_id=ContentType.objects.get_for_model(Course).pk, object_id=course.id, object_repr=course.title, action_flag=ADDITION, ) total = subjects_df.shape[0] - 1 + courses_df.shape[0] - 1 total_failure = sum(1 for row in subjects_error_df if row["Error Message"]) + len(courses_error_df) # construct error excel error_excel = "" if total_failure > 0: wb = create_course_templates(business_id, show_errors=True) categories_ws = wb.get_sheet_by_name("Step 1 - Subject Categories") categories_column_order = [cell.value for cell in categories_ws[2]] for index, row_error in enumerate(subjects_error_df): for col in range(len(categories_column_order)): categories_ws.cell( row=4 + index, column=1 + col).value = row_error[categories_column_order[col]] autosize_ws_columns(categories_ws) course_ws = wb.get_sheet_by_name("Step 2 - Classes") course_column_order = [cell.value for cell in course_ws[2]] for index, row_error in enumerate(courses_error_df): for col in range(len(course_column_order)): course_ws.cell( row=4 + index, column=1 + col).value = row_error[course_column_order[col]] autosize_ws_columns(course_ws) error_excel = workbook_to_base64(wb) return UploadCoursesMutation( total_success=total - total_failure, total_failure=total_failure, error_excel=error_excel, )
def mutate(self, info, accounts, **kwargs): owner = Admin.objects.get(user=info.context.user) business_id = owner.business.id business = Business.objects.get(id=business_id) xls = pd.ExcelFile(accounts.read()) # check all spreadsheets exist account_names = ["Parents", "Students", "Instructors"] if not all(name in xls.sheet_names for name in account_names): raise GraphQLError("Please include all spreadsheets: " + str(account_names)) # extract spreadsheets and skip first comment row parents_df = pd.read_excel(xls, sheet_name="Parents", header=1) students_df = pd.read_excel(xls, sheet_name="Students", header=1) instructors_df = pd.read_excel(xls, sheet_name="Instructors", header=1) # check all column headers present parent_ws_missing_columns = set( ACCOUNT_SHEET_NAME_TO_REQUIRED_FIELDS["parent"]) - set( parents_df.columns.values) if len(parent_ws_missing_columns) > 0: raise GraphQLError("Missing columns in parents worksheet: " + str(parent_ws_missing_columns)) instructor_ws_missing_columns = set( ACCOUNT_SHEET_NAME_TO_REQUIRED_FIELDS["instructor"]) - set( instructors_df.columns.values) if len(instructor_ws_missing_columns) > 0: raise GraphQLError("Missing columns in instructors workshet: " + str(instructor_ws_missing_columns)) student_ws_missing_columns = set( ACCOUNT_SHEET_NAME_TO_REQUIRED_FIELDS["student"]) - set( students_df.columns.values) if len(student_ws_missing_columns) > 0: raise GraphQLError("Missing columns in students workshet: " + str(student_ws_missing_columns)) # create parents parents_df = parents_df.dropna(how="all") parents_df = parents_df.where(pd.notnull(parents_df), None) # cast np.Nan to None parents_error_df = [] for _index, row in parents_df.iloc[1:].iterrows(): required_fields_check = check_account_sheet_row(row, "parent") if required_fields_check: parents_error_df.append(row.to_dict()) parents_error_df[-1]["Error Message"] = required_fields_check continue try: with transaction.atomic(): user_object = User( username=row["Email"], email=row["Email"], first_name=row["First Name"], last_name=row["Last Name"], password=User.objects.make_random_password(), ) user_object.save() parent = Parent( user=user_object, business=business, account_type="parent", phone_number=row["Phone"], zipcode=row.get("Zip Code (Optional)"), ) parent.save() except Exception as e: parents_error_df.append(row.to_dict()) parents_error_df[-1]["Error Message"] = str(e) continue Token.objects.get_or_create(user=user_object) ParentNotificationSettings.objects.create(parent=parent) Email.objects.create( template_id=WELCOME_PARENT_TEMPLATE, recipient=parent.user.email, data={ "parent_name": parent.user.first_name, "business_name": settings.BUSINESS_NAME, }, ) LogEntry.objects.log_action( user_id=info.context.user.id, content_type_id=ContentType.objects.get_for_model(Parent).pk, object_id=parent.user.id, object_repr=f"{parent.user.first_name} {parent.user.last_name}", action_flag=ADDITION, ) # create Schools school_names = set(students_df["School (Optional)"].dropna().apply( lambda x: x.strip())) for name in school_names: if not School.objects.filter(name=name).exists(): School.objects.create(name=name) # create students students_df = students_df.dropna(how="all") students_df = students_df.where(pd.notnull(students_df), None) # cast np.Nan to None students_error_df = [] for _index, row in students_df.iloc[1:].iterrows(): required_fields_check = check_account_sheet_row( row, "student", business_id) if required_fields_check: students_error_df.append(row.to_dict()) students_error_df[-1]["Error Message"] = required_fields_check continue try: with transaction.atomic(): user_object = User( username=row["Email"], email=row["Email"], first_name=row["First Name"], last_name=row["Last Name"], password=User.objects.make_random_password(), ) user_object.save() student = Student( user=user_object, business=business, account_type="student", grade=row.get("Grade Level (Optional)"), school=None if not row.get("School (Optional)") else School.objects.get(name=row.get("School (Optional)")), primary_parent=Parent.objects.get( user__username=row["Parent's Email"]), birth_date=row.get("Birthday MM/DD/YYYY (Optional)"), ) student.save() except Exception as e: students_error_df.append(row.to_dict()) students_error_df[-1]["Error Message"] = str(e) continue Token.objects.get_or_create(user=user_object) LogEntry.objects.log_action( user_id=info.context.user.id, content_type_id=ContentType.objects.get_for_model(Student).pk, object_id=student.user.id, object_repr= f"{student.user.first_name} {student.user.last_name}", action_flag=ADDITION, ) # create instructors instructors_df = instructors_df.dropna(how="all") instructors_df = instructors_df.where(pd.notnull(instructors_df), None) # cast np.Nan to None instructors_error_df = [] for index, row in instructors_df.iloc[1:].iterrows(): required_fields_check = check_account_sheet_row(row, "instructor") if required_fields_check: instructors_error_df.append(row.to_dict()) instructors_error_df[-1][ "Error Message"] = required_fields_check continue try: with transaction.atomic(): user_object = User( username=row["Email"], email=row["Email"], first_name=row["First Name"], last_name=row["Last Name"], password=User.objects.make_random_password(), ) user_object.save() instructor = Instructor( user=user_object, business=business, account_type="instructor", city=row["City"], phone_number=row["Phone"], state=row["State"], zipcode=row["Zip Code"], ) instructor.save() except Exception as e: instructors_error_df.append(row.to_dict()) instructors_error_df[-1]["Error Message"] = str(e) continue Token.objects.get_or_create(user=user_object) LogEntry.objects.log_action( user_id=info.context.user.id, content_type_id=ContentType.objects.get_for_model( Instructor).pk, object_id=instructor.user.id, object_repr= f"{instructor.user.first_name} {instructor.user.last_name}", action_flag=ADDITION, ) total = (parents_df.shape[0] - 1 + students_df.shape[0] - 1 + instructors_df.shape[0] - 1) total_failure = (len(parents_error_df) + len(students_error_df) + len(instructors_error_df)) # construct error excel error_excel = "" if total_failure > 0: wb = create_account_templates(show_errors=True) parents_ws = wb.get_sheet_by_name("Parents") parents_column_order = [cell.value for cell in parents_ws[2]] for index, row_error in enumerate(parents_error_df): for col in range(len(parents_column_order)): parents_ws.cell( row=4 + index, column=1 + col).value = row_error[parents_column_order[col]] autosize_ws_columns(parents_ws) students_ws = wb.get_sheet_by_name("Students") students_column_order = [cell.value for cell in students_ws[2]] for index, row_error in enumerate(students_error_df): for col in range(len(students_column_order)): students_ws.cell( row=4 + index, column=1 + col).value = row_error[students_column_order[col]] autosize_ws_columns(students_ws) instructors_ws = wb.get_sheet_by_name("Instructors") instructors_column_order = [ cell.value for cell in instructors_ws[2] ] for index, row_error in enumerate(instructors_error_df): for col in range(len(instructors_column_order)): instructors_ws.cell( row=4 + index, column=1 + col).value = row_error[instructors_column_order[col]] autosize_ws_columns(instructors_ws) error_excel = workbook_to_base64(wb) return UploadAccountsMutation( total_success=total - total_failure, total_failure=total_failure, error_excel=error_excel, )
def resolve_error(error: Union[Exception, ServerException], error_resolver: Dict) -> GraphQLError: message = (error.message if isinstance(error, ServerException) else str(error)) status = error_resolver.get(type(error), "UNKNOWN_ERROR") return GraphQLError(message, extensions=dict(status=status))
def mutate_and_get_payload(cls, root, info, **input): date_relation_names = ( 'institution_date', 'department_date', 'class_date', 'section_date', 'subject_teacher_date', 'additional_subject_teacher_date' ) authority = None if input.get('mutation_option') not in (1,3): raise GraphQLError('provide proper options') if input.get('date_relation_name') not in date_relation_names: raise GraphQLError('provide proper options') else: if input.get('date_relation_name') == 'institution_date': try: authority_relation_obj = Institution.objects.get(id=from_global_id(input.get('authority_relation_id'))[1]) except Institution.DoesNotExist: raise GraphQLError('institution ID is incorrect') if input.get('announcement_relation_id') is not None: try: announcement_relation_obj = InstitutionAnnouncementRelation.objects.select_related('institution').get( id=from_global_id(input.get('announcement_relation_id'))[1] ) except InstitutionAnnouncementRelation.DoesNotExist: raise GraphQLError('announcement ID is incorrect') if authority_relation_obj != announcement_relation_obj.institution: raise GraphQLError('announcement doesn\'t not belong to the same institution') if DateInstitutionRelation.objects.filter(announcement=announcement_relation_obj).exists() is True: raise GraphQLError('announcement already linked with an existing date') if input.get('public') is not None: valide_choice = False for choice in PublicDateInstitutionRelation.VISIBILITY_OPTION: if input.get('label') == choice[0]: valide_choice = True break if valide_choice is False: raise GraphQLError('provie valide label value') if input.get('tags') is None: raise GraphQLError('tags can\'t be null') authority = 'adminUser' result = UserAuthorizeTest(info,authority,institution_obj=authority_relation_obj) if input.get('date_relation_name') == 'department_date': try: authority_relation_obj = Department.objects.get(id=from_global_id(input.get('authority_relation_id'))[1]) except Department.DoesNotExist: raise GraphQLError('department ID is incorrect') if input.get('announcement_relation_id') is not None: try: announcement_relation_obj = DepartmentAnnouncementRelation.objects.select_related('department').get( id=from_global_id(input.get('announcement_relation_id'))[1] ) except DepartmentAnnouncementRelation.DoesNotExist: raise GraphQLError('announcement ID is incorrect') if authority_relation_obj != announcement_relation_obj.department: raise GraphQLError('announcement doesn\'t not belong to the same department') if DateDepartmentRelation.objects.filter(announcement=announcement_relation_obj).exists() is True: raise GraphQLError('announcement already linked with an existing date') authority = 'hod' result = UserAuthorizeTest(info,authority,department_obj=authority_relation_obj) if input.get('date_relation_name') == 'class_date': try: authority_relation_obj = Class.objects.get(id=from_global_id(input.get('authority_relation_id'))[1]) except Class.DoesNotExist: raise GraphQLError('class ID is incorrect') if input.get('announcement_relation_id') is not None: try: announcement_relation_obj = ClassAnnouncementRelation.objects.select_related('Class').get( id=from_global_id(input.get('announcement_relation_id'))[1] ) except ClassAnnouncementRelation.DoesNotExist: raise GraphQLError('announcement ID is incorrect') if authority_relation_obj != announcement_relation_obj.Class: raise GraphQLError('announcement doesn\'t not belong to the same class') if DateClassRelation.objects.filter(announcement=announcement_relation_obj).exists() is True: raise GraphQLError('announcement already linked with an existing date') authority = 'classTeacher' result = UserAuthorizeTest(info,authority,class_obj=authority_relation_obj) if input.get('date_relation_name') == 'section_date': try: authority_relation_obj = ClassSectionRelation.objects.get(id=from_global_id(input.get('authority_relation_id'))[1]) except ClassSectionRelation.DoesNotExist: raise GraphQLError('class section ID is incorrect') if input.get('announcement_relation_id') is not None: try: announcement_relation_obj = SectionAnnouncementRelation.objects.select_related('section').get( id=from_global_id(input.get('announcement_relation_id'))[1] ) except SectionAnnouncementRelation.DoesNotExist: raise GraphQLError('announcement ID is incorrect') if authority_relation_obj != announcement_relation_obj.section: raise GraphQLError('announcement doesn\'t not belong to the same class') if DateSectionRelation.objects.filter(announcement=announcement_relation_obj).exists() is True: raise GraphQLError('announcement already linked with an existing date') authority = 'sectionTeacher' result = UserAuthorizeTest(info,authority,class_section_obj=authority_relation_obj) if input.get('date_relation_name') == 'subject_teacher_date': try: authority_relation_obj = ClassSubjectTeacherRelation.objects.get(id=from_global_id(input.get('authority_relation_id'))[1]) except ClassSubjectTeacherRelation.DoesNotExist: raise GraphQLError('subject teacher ID is incorrect') if input.get('announcement_relation_id') is not None: try: announcement_relation_obj = SubjectTeacherAnnouncementRelation.objects.select_related('section_subject').get( id=from_global_id(input.get('announcement_relation_id'))[1] ) except SubjectTeacherAnnouncementRelation.DoesNotExist: raise GraphQLError('announcement ID is incorrect') if authority_relation_obj != announcement_relation_obj.section_subject: raise GraphQLError('announcement doesn\'t not belong to the same class') if DateSubjectTeacherRelation.objects.filter(announcement=announcement_relation_obj).exists() is True: raise GraphQLError('announcement already linked with an existing date') authority = 'sectionSubjectTeacher' result = UserAuthorizeTest(info,authority,class_subject_teacher_obj=authority_relation_obj) if input.get('date_relation_name') == 'additional_subject_teacher_date': try: authority_relation_obj = AdditionalSubjectTeacherRelation.objects.get( id=from_global_id(input.get('authority_relation_id'))[1] ) except AdditionalSubjectTeacherRelation.DoesNotExist: raise GraphQLError('additional subject teacher ID is incorrect') if input.get('announcement_relation_id') is not None: try: announcement_relation_obj = AdditionalSubjectTeacherAnnouncementRelation.objects.select_related( 'section_additional_subject' ).get( id=from_global_id(input.get('announcement_relation_id'))[1] ) except AdditionalSubjectTeacherAnnouncementRelation.DoesNotExist: raise GraphQLError('announcement ID is incorrect') if authority_relation_obj != announcement_relation_obj.section_additional_subject: raise GraphQLError('announcement doesn\'t not belong to the same class') if DateAdditionalSubjectTeacherRelation.objects.filter(announcement=announcement_relation_obj).exists() is True: raise GraphQLError('announcement already linked with an existing date') authority = 'sectionAdditionalSubjectTeacher' result = UserAuthorizeTest(info,authority,class_additional_subject_teacher_obj=authority_relation_obj) if result[authority] is not True: raise GraphQLError('you are not a valide user. try different account.') if input.get('mutation_option') == 1: if input.get('date') is None or input.get('label') is None or input.get('short_title') is None: raise GraphQLError('provide all required values to create date') else: json_data = json.loads(input.get('date')) date_string_array = json_data['date_string_array'] date_array = [] date_obj = Date() if len(date_string_array) == 0: raise GraphQLError('date array is empty!!') if len(date_string_array) > 2: raise GraphQLError('only two dates are allowed') else: if input.get('repeat') is not None: date_obj.repeat = input.get('repeat') if input.get('repeat'): for date in date_string_array: try: dateElement = datetime.datetime.strptime(date, '%m-%d').date() date_array.append(dateElement) except ValueError: raise GraphQLError('Incorrect data format, should be MM-DD') else: for date in date_string_array: try: dateElement = datetime.datetime.strptime(date, '%Y-%m-%d').date() date_array.append(dateElement) except ValueError: raise GraphQLError('Incorrect data format, should be YYYY-MM-DD') if len(date_array) == 2: if date_array[0] > date_array[1]: raise GraphQLError('first date can\'t be greater then second date') date_obj.date = date_array valide_choice = False for choice in Date.DATE_TYPE: if input.get('label') == choice[0]: valide_choice = True break if valide_choice is False: raise GraphQLError('provie valide label value') date_obj.label = input.get('label') date_obj.short_title = input.get('short_title') date_obj._date_relation_name = input.get('date_relation_name') if input.get('announcement_relation_id') is not None: date_obj._announcement_relation_obj = announcement_relation_obj if input.get('date_relation_name') == 'institution_date': if input.get('visibility_option') is not None: date_obj._public = True date_obj._visibility_option = input.get('visibility_option') json_data = json.loads(input.get('tags')) tags_array = json_data['tags'] if len(tags_array) > 5: raise GraphQLError('only 5 tags are allowed') date_obj._tags = tags_array date_obj._authority_relation_obj = authority_relation_obj date_obj.save() if input.get('date_relation_name') == 'institution_date': institution_date_obj = DateInstitutionRelation.objects.get(date=date_obj) return DateMutation(institution_date=institution_date_obj) if input.get('date_relation_name') == 'department_date': department_date_obj = DateDepartmentRelation.objects.get(date=date_obj) return DateMutation(department_date=department_date_obj) if input.get('date_relation_name') == 'class_date': class_date_obj = DateClassRelation.objects.get(date=date_obj) return DateMutation(class_date=class_date_obj) if input.get('date_relation_name') == 'section_date': section_date_obj = DateSectionRelation.objects.get(date=date_obj) return DateMutation(section_date=section_date_obj) if input.get('date_relation_name') == 'subject_teacher_date': subject_teacher_date_obj = DateSubjectTeacherRelation.objects.get(date=date_obj) return DateMutation(subject_teacher_date=subject_teacher_date_obj) if input.get('date_relation_name') == 'additional_subject_teacher_date': additional_subject_teacher_date_obj = DateAdditionalSubjectTeacherRelation.objects.get(date=date_obj) return DateMutation(additional_subject_teacher_date=additional_subject_teacher_date_obj) if input.get('mutation_option') == 3: if input.get('date_relation_id') is None: raise GraphQLError('provide prover value') else: if input.get('date_relation_name') == 'institution_date': institution_date_obj = DateInstitutionRelation.objects.select_related('date').get( id=from_global_id(input.get('date_relation_id'))[1] ) institution_date_obj.date.delete() return DateMutation(institution_date=None) if input.get('date_relation_name') == 'department_date': department_date_obj = DateDepartmentRelation.objects.select_related('date').get( id=from_global_id(input.get('date_relation_id'))[1] ) department_date_obj.date.delete() return DateMutation(department_date=None) if input.get('date_relation_name') == 'class_date': class_date_obj = DateClassRelation.objects.select_related('date').get( id=from_global_id(input.get('date_relation_id'))[1] ) class_date_obj.date.delete() return DateMutation(class_date=None) if input.get('date_relation_name') == 'section_date': section_date_obj = DateSectionRelation.objects.select_related('date').get( id=from_global_id(input.get('date_relation_id'))[1] ) section_date_obj.date.delete() return DateMutation(section_date=None) if input.get('date_relation_name') == 'subject_teacher_date': subject_teacher_date_obj = DateSubjectTeacherRelation.objects.select_related('date').get( id=from_global_id(input.get('date_relation_id'))[1] ) subject_teacher_date_obj.date.delete() return DateMutation(subject_teacher_date=None) if input.get('date_relation_name') == 'additional_subject_teacher_date': additional_subject_teacher_date_obj = DateAdditionalSubjectTeacherRelation.objects.select_related('date').get( id=from_global_id(input.get('date_relation_id'))[1] ) additional_subject_teacher_date_obj.date.delete() return DateMutation(additional_subject_teacher_date=None)
def resolve_me(self,info): user = info.context.user if user.is_anonymous: raise GraphQLError('You are not Logged In') return user
def resolve_author(self, info, **kwargs): id = kwargs.get('id') try: return Author.objects.get(pk=id) except Exception: raise GraphQLError('Author not found')
def check_filter_type(self, filter_type): if filter_type not in self.supported_filter_expr: raise GraphQLError( f"{filter_type} is not under supported filter expression")
def validate_data(data: Optional[dict]) -> None: if not isinstance(data, dict): raise GraphQLError("Operation data should be a JSON object") validate_query_body(data.get("query")) validate_variables(data.get("variables")) validate_operation_name(data.get("operationName"))
def resolve_myA(self, info): u = info.context.user if u.is_anonymous: raise GraphQLError("Not Logged In!") return Assignment.objects.filter(student=u).order_by("-added")
def validate_variables(variables) -> None: if variables is not None and not isinstance(variables, dict): raise GraphQLError("Query variables must be a null or an object.")
def resolve_myT(self, info): u = info.context.user if u.is_anonymous: raise GraphQLError("Not Logged In!") return Test.objects.all().order_by("-added")
def resolve_my_profile(self,info): try: profile = Profile.objects.get(user=info.context.user) except Profile.DoesNotExist: raise GraphQLError("You dont have profile") return profile
def receive_after_flush(session, context): if not verify_calendar_id(target.calendar_id): raise GraphQLError("Room calendar Id is invalid") pass
def mutate(root, info, code): token_dict = authenticate(code) if not token_dict: raise GraphQLError("Unsuccessful to obtain the token") authPayload = type_.AuthPayload(token=token_dict["access_token"]) return AuthenticateWithGitHub(authPayload=authPayload)
def resolve_me(self, info): user = info.context.user if user.is_anonymous: raise GraphQLError('Not logged in!') return user
def resolve_generateError(self, info): return GraphQLError( 'Cannot query field "generateError" on type "User".')
def mutate_and_get_payload(cls, root, info, **input_): if not info.context.user.is_authenticated: raise GraphQLError('User not logged in') return super().mutate_and_get_payload(root, info, **input_)
def _single(values): if len(values) == 1: return values[0] else: raise GraphQLError("Expected 1 value but got {}".format(len(values)))
def mutate_and_get_payload(cls, root, info, **input): context = authorityMapping(info, input.get('explanation_for'), input.get('authority'), input.get('authority_model_id')) if context['verified']: json_string = input.get('body') json_data = json.loads(json_string) explanation_obj = Explanation(body=json_data,author=info.context.user.nxtgenuser) if input.get('explanation_for') in ('explanation_topic_form_query','explanation_sub-topic_form_query'): if input.get('status') is not None: valide_choice = False for choice in AbstractFormQueryExplanation.STATUS_CHOICE: if input.get('status') == choice[0]: valide_choice = True explanation_obj._status = input.get('status') break if valide_choice is False: raise GraphQLError('provie proper value') if input.get('explanation_for') == 'explanation_topic_form_query': try: explanation_for_model_obj = TopicFormQuery.objects.get( id=from_global_id(input.get('explanation_for_model_id'))[1] ) except TopicFormQuery.DoesNotExist: raise GraphQLError('form query ID is incorrect') if input.get('explanation_for') == 'explanation_sub-topic_form_query': try: explanation_for_model_obj = SubTopicFormQuery.objects.get( id=from_global_id(input.get('explanation_for_model_id'))[1] ) except SubTopicFormQuery.DoesNotExist: raise GraphQLError('form query ID is incorrect') if input.get('authority') in ('sectionSubjectTeacher','sectionStudentSubjectTeacher'): if explanation_for_model_obj.subject_teacher != context[input.get('authority')]: raise GraphQLError('you don\'t have access to this form query') if input.get('authority') in ('sectionAdditionalSubjectTeacher','sectionStudentAdditionalSubjectTeacher'): if explanation_for_model_obj.additional_subject_teacher != context[input.get('authority')]: raise GraphQLError('you don\'t have access to this form query') #------------------------------------------------------------------------------------------------------------------- if input.get('explanation_for') == 'question': if input.get('status') is not None: valide_choice = False for choice in Question.STATUS_CHOICE: if input.get('status') == choice[0]: valide_choice = True explanation_obj._status = input.get('status') break if valide_choice is False: raise GraphQLError('provie proper value') try: explanation_for_model_obj = Question.objects.get(id=from_global_id(input.get('explanation_for_model_id'))[1]) except Question.DoesNotExist: raise GraphQLError('question ID is incorrect') #--------------------------------------------------------------------------------------------------------------------- if input.get('explanation_for') == 'exam_query': try: explanation_for_model_obj = ExamQuery.objects.get(id=from_global_id(input.get('explanation_for_model_id'))[1]) except ExamQuery.DoesNotExist: raise GraphQLError('exam query ID is incorrect') if input.get('status') is not None: if input.get('status') == 'active': explanation_obj._status = 'active' explanation_obj._explanation_for = input.get('explanation_for') explanation_obj._explanation_for_model_obj = explanation_for_model_obj explanation_obj.save() return ExplanationCreationMutation(explanation=explanation_obj)