Пример #1
0
def convert_column_to_string(type, column, registry=None):
    return String(description=column.doc, required=not (column.nullable))
Пример #2
0
def convert_field_to_string(field, registry=None):
    return String(description=field.help_text, required=not field.null)
 class Arguments:
     string = String(required=True)
Пример #4
0
class MiniSeries(RiotGrapheneObject):
    progress = String()
    losses = Int()
    target = Int()
    wins = Int()
Пример #5
0
class LeagueList(RiotGrapheneObject):
    leagueId = String()
    tier = String()
    entries = List(LeagueItem)
    queue = String()
    name = String()
Пример #6
0
class PeopleCountType(ObjectType):
    room = String()
    status_in = Int()
    status_out = Int()
    occupancy = Int()
Пример #7
0
def convert_column_to_string(type, column, registry=None):
    return String(description=getattr(column, 'doc', None),
                  required=not (getattr(column, 'nullable', True)))
Пример #8
0
class AcceptanceInput(InputObjectType):
    date = String()
    time = String()
    pati_id = String()
    pati_sei = String()
    pati_mei = String()
    pati_sei_kana = String()
    pati_mei_kana = String()
    pati_birth = String()
    pati_sex = String()
    status = String()
    depart_code = String()
    depart_name = String()
    physic_code = String()
    physic_name = String()
    appoint_id = String()
    appoint_time = String()
    account_time = String()
    medi_contents = String()
    place = String()
    memo = String()
Пример #9
0
class Query(ObjectType):
    node = relay.Node.Field()

    # Acceptance List
    acceptances = List(Acceptance, status=List(String))

    def resolve_acceptances(self,
                            info,
                            status=["診療待ち", "会計待ち", "会計済み"],
                            **kwargs):
        query = Acceptance.get_query(info)
        wait_post_d = req_to_xml(
            req_key="tmedicalgetreq",
            req_data={
                "Perform_Date": "",
            },
        )

        wait_json_d = post_request(
            api_uri=orca.wait_accounting,
            res_key="tmedicalgetres",
            post_data=wait_post_d,
        )
        if "Tmedical_List_Information" in wait_json_d:
            pprint(wait_json_d)
            for dd in wait_json_d["Tmedical_List_Information"]:
                query.filter(AcceptanceModel.date == date_to_string(
                    datetime.now())).filter(
                        AcceptanceModel.pati_id == dd["Patient_Information"]
                        ["Patient_ID"]).filter(
                            AcceptanceModel.depart_code ==
                            dd["Department_Code"]).filter(
                                AcceptanceModel.physic_code ==
                                dd["Physician_Code"]).update(
                                    {"status": "会計待ち"})

        all_data = (
            query.filter(AcceptanceModel.status.in_(status), ).filter(
                AcceptanceModel.date == date_to_string(datetime.now())).all()
            if len(status) != 0 else query.filter(
                AcceptanceModel.date == date_to_string(datetime.now())).all())
        result = [dd for dd in all_data if dd.status != "会計済み"]
        for rslt in result:
            ended_json_d = post_request(
                api_uri=orca.ended_account,
                res_key="medicalget01res",
                post_data=req_to_xml(
                    req_key="medicalgetreq",
                    req_data={
                        "Patient_ID": rslt.pati_id,
                        "Perform_Date": "",
                    },
                ),
            )
            if ended_json_d["Api_Result"] == "K1":
                # rslt.status = "会計済み"
                today = date_to_string(datetime.now())
                pati_id = ended_json_d["Patient_Information"]["Patient_ID"]
                for medi in ended_json_d["Medical_List_Information"]:
                    if medi["Perform_Date"] == today:
                        query.filter(AcceptanceModel.date == today).filter(
                            AcceptanceModel.pati_id == pati_id).filter(
                                AcceptanceModel.depart_code ==
                                medi["Department_Code"]).update(
                                    {"status": "会計済み"})
        database.SessionLocal.commit()

        return all_data

    # Patient List
    patients = List(Patient, pati_id=List(String))

    def resolve_patients(self, info, pati_id=[], **kwargs):
        query = Patient.get_query(info)
        result = (query.filter(PatientModel.Patient_ID.in_(pati_id), ).all()
                  if len(pati_id) != 0 else query.all())
        return result

    # New Patient List
    new_pati_list = List(ORPatient,
                         start_date=String(required=True),
                         end_date=String(required=True))

    def resolve_new_pati_list(self, info, start_date, end_date, **kwargs):
        data = diff_new(start_date, end_date)
        return data

    # Patient Detail
    pati_detail = Field(ORPatiDetail, pati_id=String(required=True))

    def resolve_pati_detail(self, info, pati_id, **kwargs):
        orp = ORPatientClass(pati_id=pati_id)
        p_info = orp.get_info()
        data = (p_info["Patient_Information"]
                if "Patient_Information" in p_info.keys() else {})
        return {"data": data}

    #
    #
    # Department

    get_department = List(Department, code=List(String))

    def resolve_get_department(self, info, code=[], **kwargs):
        query = Department.get_query(info)
        result = (query.filter(DepartmentModel.code.in_(code), ).all()
                  if len(code) != 0 else query.all())
        return result

    #
    #
    # Physician

    get_physician = List(Physician, code=List(String))

    def resolve_get_physician(self, info, code=[], **kwargs):
        query = Physician.get_query(info)
        result = (query.filter(PhysicianModel.code.in_(code), ).all()
                  if len(code) != 0 else query.all())
        return result

    #
    #
    # Physician

    get_account_data = String(data=String())

    def resolve_get_account_data(self, info, data="", **kwargs):
        result = data
        print(data)
        # query = Physician.get_query(info)
        # result = (
        #     query.filter(
        #         PhysicianModel.code.in_(code),
        #     ).all()
        #     if len(code) != 0
        #     else query.all()
        # )
        return result
Пример #10
0
class Extra(ObjectType):
    name = String()
    value = String()
Пример #11
0
class TopicListQuery(ObjectType):
    topics = Field(
        TopicList,
        slug=String(required=True),
        year=Int(),
        page=Int(),
        search_keys=String(),
        refresh=Boolean(),
        tab=String(),
        exclusions=List(String),
        extra=JSONString(),
    )

    @staticmethod
    def resolve_topics(_parent, info, slug, **kwargs):
        # Convert string query parameters to actual dictionary to use it in TopicListHandler
        search_keys = dict(parse_qsl(
            kwargs.get("search_keys"))) if kwargs.get("search_keys") else {}
        manager = TopicListManager(
            slug,
            info.context.user,
            kwargs.get("year"),
            search_keys,
            kwargs.get("tab"),
            kwargs.get("exclusions"),
            extra=kwargs.get("extra"),
        )

        if kwargs.get("refresh"):
            manager.delete_cache(delimiter=True)

        frame = LeftFrame(manager, kwargs.get("page"))
        page = frame.page  # May raise PermissionDenied or Http404

        object_list = [
            Topic(title=t["title"],
                  slug=t["slug"],
                  count=humanize_count(t.get("count")))
            for t in page["object_list"]
        ]

        paginator = {
            "num_pages": page["paginator"]["num_pages"],
            "page_range": page["paginator"]["page_range"]
        }

        tabs = (Tabs(
            current=frame.tabs["current"],
            available=[
                Tab(name=key, safename=value)
                for key, value in frame.tabs["available"].items()
            ],
        ) if frame.tabs else None)

        exclusions = (Exclusions(active=frame.exclusions["active"],
                                 available=frame.exclusions["available"])
                      if frame.exclusions else None)

        extra = [
            Extra(name=key, value=value) for key, value in frame.extra.items()
        ] if frame.extra else None

        page_data = {
            "has_next": page.get("has_next"),
            "has_other_pages": page.get("has_other_pages"),
            "has_previous": page.get("has_previous"),
            "number": page.get("number"),
            "object_list": object_list,
            "paginator": Paginator(**paginator),
        }

        data = {
            "page": Page(**page_data),
            "parameters": frame.parameters,
            "refresh_count": frame.refresh_count,
            "year": frame.year,
            "year_range": frame.year_range,
            "safename": frame.safename,
            "slug": frame.slug,
            "slug_identifier": frame.slug_identifier,
            "tabs": tabs,
            "exclusions": exclusions,
            "extra": extra,
        }

        return TopicList(**data)
Пример #12
0
class Tabs(ObjectType):
    current = String()
    available = List(Tab)
Пример #13
0
class Tab(ObjectType):
    name = String()
    safename = String()
Пример #14
0
class Topic(ObjectType):
    title = String()
    slug = String()
    count = String()
Пример #15
0
class User(GrokObjectType):
    id = ID()
    name = String()
Пример #16
0
class Query(ObjectType):
    hello = String()

    def resolve_hello(root, info):
        return "Hello, world!"
Пример #17
0
class StreamRendition(ObjectType):
    name = String()
Пример #18
0
 class Query(ObjectType):
     hello = String()
Пример #19
0
class MediaStreamingEpisode(ObjectType):
    title = String()
    thumbnail = String()
    url = String()
    site = String()
Пример #20
0
class Query(object):
    accountSearch = Field(
        AccountSearchResults,
        query=String(required=True),
        profile=String(),
        grade=Int(),
        sort=String(),
        page=Int(),
        page_size=Int(),
    )

    courseSearch = Field(
        CourseSearchResults,
        query=String(required=True),
        course_type=String(),
        course_size=Int(),
        availability=String(),
        sort=String(),
        page=Int(),
        page_size=Int(),
    )

    sessionSearch = Field(
        SessionSearchResults,
        query=String(required=True),
        time=String(),
        sort=String(),
        page=Int(),
        page_size=Int(),
    )

    @login_required
    def resolve_accountSearch(self, info, **kwargs):
        # access control results based on user type
        user_id = info.context.user.id

        is_student = Student.objects.filter(user=user_id).exists()
        is_instructor = Instructor.objects.filter(user=user_id).exists()
        is_parent = Parent.objects.filter(user=user_id).exists()
        if is_student:
            profiles = ["ADMIN", "INSTRUCTOR", "PARENT"]
        elif is_instructor:
            profiles = ["ADMIN", "INSTRUCTOR", "PARENT", "STUDENT"]
        elif is_parent:
            profiles = ["ADMIN", "INSTRUCTOR", "STUDENT"]
        else:  # admin
            profiles = ["ADMIN", "PARENT", "INSTRUCTOR", "STUDENT"]

        # query on profile filter if set else all account types
        profile = kwargs.get("profile", None)
        if profile in profiles:  # only use profile if accessible
            profiles = [profile]

        # define filter param to django manager/object mappings
        filterToSearch = {
            "STUDENT": getattr(StudentManager, "search"),
            "INSTRUCTOR": getattr(InstructorManager, "search"),
            "PARENT": getattr(ParentManager, "search"),
            "ADMIN": getattr(AdminManager, "search"),
        }
        filterToModel = {
            "STUDENT": Student.objects,
            "INSTRUCTOR": Instructor.objects,
            "PARENT": Parent.objects,
            "ADMIN": Admin.objects,
        }
        # set results and query
        results = Student.objects.none()
        query = kwargs.get("query")

        # iterate over account types to search
        for profile in profiles:
            profile_results = filterToModel[profile].none()

            # filter for ADMIN if profile is admin type
            admin_profile = None
            if profile.lower() in [t[0] for t in Admin.TYPE_CHOICES]:
                admin_profile = profile.lower()
                profile = "ADMIN"

            for token in query.split():
                if filterToSearch.get(profile):
                    profile_results = filterToSearch[profile](
                        filterToModel[profile], token, profile_results)

            # filter for admin types
            if admin_profile is not None:
                profile_results = profile_results.filter(
                    admin_type=admin_profile)

            if profile == "STUDENT":
                # filter for grade if STUDENT
                try:
                    grade = int(kwargs.get("grade", None))
                    if 1 <= grade and grade <= 13:
                        profile_results = profile_results.filter(grade=grade)
                except:
                    pass

                # students in instructor's courses
                if is_instructor:
                    courses = Course.objects.filter(instructor=user_id)
                    student_ids = set()
                    for course in courses:
                        student_ids.update(course.enrollment_list)
                    profile_results = profile_results.filter(
                        user_id__in=student_ids)

                # parent's students
                if is_parent:
                    parent = Parent.objects.get(user=user_id)
                    profile_results = profile_results.filter(
                        user_id__in=parent.student_list)

            # parent
            if profile == "PARENT":
                # parents of students in instructor's courses
                if is_instructor:
                    # find students
                    courses = Course.objects.filter(instructor=user_id)
                    student_ids = set()
                    for course in courses:
                        student_ids.update(course.enrollment_list)

                    # students' parents
                    parent_ids = set()
                    for student_id in student_ids:
                        student = Student.objects.get(user_id=student_id)
                        if student.primary_parent:
                            parent_ids.add(student.primary_parent.user.id)
                        if student.secondary_parent:
                            parent_ids.add(student.secondary_parent.user.id)
                    profile_results = profile_results.filter(
                        user_id__in=parent_ids)

                # student's parents
                if is_student:
                    student = Student.objects.get(user=user_id)
                    primary_parent_id = (None if not student.primary_parent
                                         else student.primary_parent.user.id)
                    secondary_parent_id = (None if not student.secondary_parent
                                           else student.primary_parent.user.id)
                    profile_results = profile_results.filter(
                        user_id__in=[primary_parent_id, secondary_parent_id])

            results = chain(results, profile_results)

        # sort results
        sort = kwargs.get("sort", None)
        if sort is not None:
            if sort == "alphaAsc":
                results = sorted(results,
                                 key=attrgetter("user.first_name",
                                                "user.last_name"))
            elif sort == "alphaDesc":
                results = sorted(
                    results,
                    key=attrgetter("user.first_name", "user.last_name"),
                    reverse=True,
                )
            elif sort == "idAsc":
                results = sorted(results, key=lambda obj: obj.user.id)
            elif sort == "idDesc":
                results = sorted(results,
                                 key=lambda obj: obj.user.id,
                                 reverse=True)
            elif sort == "updateAsc":
                results = sorted(results, key=lambda obj: obj.updated_at)
            elif sort == "updateDesc":
                results = sorted(results,
                                 key=lambda obj: obj.updated_at,
                                 reverse=True)

        results = list(results)
        total = len(results)
        results = paginate(results, kwargs.get("page", None),
                           kwargs.get("page_size", None))

        return AccountSearchResults(results=results, total=total)

    @login_required
    def resolve_courseSearch(self, info, **kwargs):
        results = Course.objects.none()
        query = kwargs.get("query")

        for word in query.split():
            dayOfWeekDic = {
                "monday": "MON",
                "tuesday": "TUE",
                "wednesday": "WED",
                "thursday": "THU",
                "friday": "FRI",
                "saturday": "SAT",
                "sunday": "SUN",
            }
            # date check
            if dayOfWeekDic.get(word.lower()):
                word = dayOfWeekDic.get(word.lower())
            results = Course.objects.search(word, results)

        # course filter
        course_type = kwargs.get("course_type", None)
        if course_type is not None:
            if course_type == "tutoring":
                results = results.filter(max_capacity=1)
            if course_type == "group":
                results = results.filter(max_capacity__lte=5,
                                         max_capacity__gt=1)
            if course_type == "class":
                results = results.filter(max_capacity__gt=5)

        # size filter
        course_size = kwargs.get("course_size", None)
        if course_size is not None:
            course_size = int(course_size)
            course_ids = []
            for course in results:
                curr_size = len(Enrollment.objects.filter(course=course.id))
                if curr_size <= course_size:
                    course_ids.append(course.id)
            results = Course.objects.filter(id__in=course_ids)

        # availability filter
        availability = kwargs.get("availability", None)
        if availability is not None and (availability == "open"
                                         or availability == "filled"):
            # calculate availability
            course_ids = []
            for course in results:
                capacity = len(Enrollment.objects.filter(course=course.id))
                if availability == "open" and capacity < course.max_capacity:
                    course_ids.append(course.id)
                if availability == "filled" and capacity >= course.max_capacity:
                    course_ids.append(course.id)
            results = Course.objects.filter(id__in=course_ids)

        # sort results
        sort = kwargs.get("sort", None)
        if sort is not None:
            sortToParameter = {
                "dateAsc": "start_date",
                "dateDesc": "-start_date",
                "timeAsc": "start_time",
                "timeDesc": "-start_time",
            }
            if sortToParameter.get(sort):
                results = results.order_by(sortToParameter[sort])

        results = list(results)
        total = len(results)
        results = paginate(results, kwargs.get("page", None),
                           kwargs.get("page_size", None))

        return CourseSearchResults(results=results, total=total)

    @login_required
    def resolve_sessionSearch(self, info, **kwargs):
        results = Session.objects.all()

        query = kwargs.get("query", None)
        if query is not None:
            for word in query.split():
                results = Session.objects.search(word, results)

        # time filter
        time = kwargs.get("time", None)
        if time is not None:  # all is default
            if time == "future":
                results = results.filter(start_datetime__gte=datetime.utcnow())
            elif time == "past":
                results = results.filter(start_datetime__lte=datetime.utcnow())
            elif time == "today":
                results = results.filter(
                    start_datetime__date=datetime.utcnow())

        # sort results
        sort = kwargs.get("sort", None)
        if sort is not None:
            sortToParameter = {
                "timeAsc": "start_datetime",
                "timeDesc": "-start_datetime",
            }
            if sortToParameter.get(sort):
                results = results.order_by(sortToParameter[sort])

        results = list(results)
        total = len(results)
        results = paginate(results, kwargs.get("page", None),
                           kwargs.get("page_size", None))

        return SessionSearchResults(results=results, total=total)
Пример #21
0
 class Arguments:
     name = String()
     email = String()
     city = String()
     state = String()
Пример #22
0
class Query(ObjectType):
	all_orders = List(OrderType)
	all_salary_in_month = Field(UsersMonthsType, user_id=IntID(), date=String(required=True), company_filter=IntID())
	user_salary_info = Field(UserSalaryInfoType, date=String(required=True))
	user_salary_bonus_info = List(BonusType, date=String())
	last_salary_month = String()
	all_grade_coefficients = List(GradeCoefficientType)
	b7_export = String()
	paged_salary_payments = Field(PagedSalaryPayments, paged=PagedInput())
	accruals = List(CompanyAccrualType)
	user_salary_sum_avg_year = Field(SumAvgYearType, date=String())

	def resolve_all_salary_in_month(self, info, user_id=None, date=None, company_filter=None):
		if user_id != info.context.user.id and not info.context.user.has_perm('users.view_salary'):
			raise SngyException('Недостаточно прав')

		flush_cache()
		date = Date(int('20' + date[-2:]), int(date[:-2]), 1)
		if date > get_last_salary_month().date():
			calculation_result = calculation_all_salary_in_month(user_id, company_filter)
			users = calculation_result['users']
			classifier = calculation_result['classifier']
			attributes = calculation_result['attributes']
		else:
			users = {}
			r_totals = {}
			if user_id:
				try:
					users[user_id] = pickle.loads(SalaryArchive.objects.get(worker_id=user_id, date=date).object)
				except SalaryArchive.DoesNotExist:
					pass
			else:
				archive = SalaryArchive.objects.filter(date=date)
				users = {a.worker_id: pickle.loads(a.object) for a in archive}
				for u in users:
					for obj in users[u][1].items():
						try:
							r_totals[obj[0]] += float(obj[1])
						except KeyError:
							r_totals[obj[0]] = 0
							r_totals[obj[0]] += float(obj[1])
				for k in r_totals:
					r_totals[k] = '{0:.2f}'.format(r_totals[k])

				r_totals = TotalsType(**r_totals)

		result = []
		db_users = {u.id: u for u in User.objects.select_related('occupation')}
		for u in users:
			user = db_users[u]
			months = []
			for m in users[u][0]:
				totals = TotalsType(**users[u][0][m])
				months.append(MonthType(month=m, totals=totals))
			totals = TotalsType(**users[u][1])
			bonus = users[u][2]
			advance = users[u][3]
			result.append(UserMonthsType(user=user, months=months, totals=totals, bonus=bonus, advance=advance))

		if date > get_last_salary_month().date():
			r_totals = {}
			for a in attributes:
				if isinstance(getattr(classifier.storage.totals, a), timedelta):
					r_totals[a] = '{0:.2f}'.format(getattr(classifier.storage.totals, a).total_seconds() / 3600)
				else:
					r_totals[a] = getattr(classifier.storage.totals, a)
			r_totals = TotalsType(**r_totals)

		return UsersMonthsType(users=result, totals=r_totals)

	def resolve_user_salary_info(self, info, date):
		fields = ['general', 'welding', 'experience', 'etech', 'schematic', 'initiative', 'discipline']
		date = Date(int('20' + date[-2:]), int(date[:-2]), 1)
		if date > get_last_salary_month().date():
			date = get_salary_limits(get_last_salary_month())[1]
			str_month = str(date.year) + str(date.month)
			work_hours = work_hours_in_month(str_month)
			costs = cost_hours(info.context.user, str_month)
			salary = info.context.user.occupation.salary
			base = info.context.user.occupation.base
			advance = info.context.user.occupation.advance
			if not salary:
				coefficients = {obj.name: obj.value for obj in GlobalCoefficient.objects.all() if obj.name in fields}
				my_coefficients = info.context.user.coefficients
				for f in fields:
					coefficients['my_' + f] = getattr(my_coefficients, f)
				base_cost_hour = my_coefficients.avg * my_coefficients.max_hour
				return UserSalaryInfoType(salary=salary, base=base, cost_hour=costs['salary'], advance=advance,
				                          work_hours_in_month=work_hours, avg=my_coefficients.avg,
				                          base_cost_hour=base_cost_hour, **coefficients)
			return UserSalaryInfoType(salary=salary, base=base, cost_hour=costs['salary'], advance=advance,
			                          work_hours_in_month=work_hours)
		else:
			user_data = pickle.loads(SalaryArchive.objects.get(date=date, worker=info.context.user).object)
			if len(user_data) > 4:
				salary = user_data[4]
				base = user_data[5]
				advance = user_data[3]
				cost_hour = user_data[13]
				base_cost_hour = user_data[14]
				str_month = str(date.year) + str(date.month)
				work_hours = work_hours_in_month(str_month)
				my_coefficients = user_data[10]
				if my_coefficients:
					coefficients = pickle.loads(CoefficientsArchive.objects.get(date=date).global_coefficients)
					coefficients = {c['name']: c['value'] for c in coefficients if c['name'] in fields}
					for f in fields:
						coefficients['my_' + f] = my_coefficients[f]
					avg = user_data[12]
					return UserSalaryInfoType(salary=salary, base=base, advance=advance, cost_hour=cost_hour,
					                          base_cost_hour=base_cost_hour, work_hours_in_month=work_hours, avg=avg,
					                          **coefficients)
				return UserSalaryInfoType(salary=salary, base=base, advance=advance, cost_hour=cost_hour,
					                          base_cost_hour=base_cost_hour, work_hours_in_month=work_hours)
			else:
				return UserSalaryInfoType()

	def resolve_user_salary_bonus_info(self, info, date=None):
		if date:
			last_day = monthrange(year=int('20' + date[-2:]), month=int(date[:-2]))[1]
			date = Date(year=int('20' + date[-2:]), month=int(date[:-2]), day=last_day)
		bonuses = Bonus.objects.filter(user=info.context.user, month=date)
		return bonuses

	def resolve_user_salary_sum_avg_year(self, info, date):
		end = Date.today()
		year = int('20' + date[-2:])
		if year < end.year:
			end = end.replace(year=year, month=12, day=31)
		begin = end.replace(day=1, month=1)
		sum_year = 0
		archive = SalaryArchive.objects.filter(worker=info.context.user, date__range=(begin, end))
		for d in archive:
			data = pickle.loads(d.object)
			totals = data[1]
			sum_year += sum(totals[mn] for mn in totals if mn.endswith('_money') and mn not in ('ideal_grade_money', 'negative_grade_money'))
			sum_year -= totals['negative_grade_money']
			sum_year += data[2] # бонус
			sum_year += totals['private_car'] + totals['duty_car']
		avg_year = sum_year / end.month
		return SumAvgYearType(sum_year=sum_year, avg_year=avg_year)

	@permission_required('users.view_order')
	def resolve_all_orders(self, info):
		return Order.objects.all()

	def resolve_last_salary_month(self, info):
		date = get_salary_limits(get_last_salary_month())[1]
		return str(date.year) + str(date.month)

	def resolve_all_grade_coefficients(self, info):
		return GradeCoefficient.objects.all()

	@permission_required('salary.generate_b7_export')
	def resolve_b7_export(self, info):
		return generate_b7_export()

	@permission_required('salary.can_view_salarypayment')
	def resolve_paged_salary_payments(self, info, paged, **kwargs):
		paged = {k: v for k, v in paged.items() if v is not None}
		result = SalaryPayment.objects.list_paged_payments(**kwargs, **paged)
		keys = ('salary_payments', 'total_count')
		return PagedSalaryPayments(**dict(zip(keys, result)))

	@permission_required('users.view_salary')
	def resolve_accruals(self, info):
		users = calculation_all_salary_in_month()['users']

		companies = {c.id: [] for c in Company.objects.all()}
		companies['cash'] = []

		user_objects = {u.id: u for u in User.objects.all()}

		for id in users:
			advance = users[id][3]
			bonus = users[id][2]
			# users[id][1] - totals по пользователю
			main_part = sum(users[id][1][m] for m in users[id][1] if m.endswith('_money') and m not in
			                ('ideal_grade_money', 'negative_grade_money', 'vacation_money')) + bonus - advance - \
			            users[id][1]['negative_grade_money']
			auto = users[id][1]['private_car'] + users[id][1]['duty_car']
			other = users[id][1]['vacation_money']

			salary_payments = SalaryPayment.objects.filter(user_id=id, company__minimize_salary=True)
			for sp in salary_payments:
				if sp.company == user_objects[id].occupation.main_company:
					main_part = main_part - sp.amount
				else:
					main_part = main_part - (sp.advance + sp.amount)
				if main_part < 0:
					main_part_result = main_part
				else:
					main_part_result = sp.amount
				companies[sp.company_id].append(AccrualType(user=user_objects[id].short_name, bonus=0,
				                                                advance=sp.advance, main_part=main_part_result))

			positions = Position.objects.filter(user=id, company__minimize_salary=False)
			if positions:
				companies[positions[0].company_id].append(AccrualType(user=user_objects[id].short_name,
							bonus=bonus, advance=advance, main_part=main_part))
			else:
				if not auto and not other and main_part < 0:
					pass
				else:
					companies['cash'].append(AccrualType(user=user_objects[id].short_name, auto=auto, other=other,
				                                      bonus=bonus, advance=advance, main_part=main_part))

		result = []

		for c_id in companies:
			companies[c_id] = sorted(companies[c_id], key=lambda obj: obj.user) # Сортировка
			if c_id != 'cash':
				result.append(CompanyAccrualType(id=c_id, name=Company.objects.get(id=c_id).client.name, accruals=companies[c_id]))
			else:
				result.append(CompanyAccrualType(id=c_id, name='Наличными', accruals=companies[c_id]))

		return result
Пример #23
0
class LeagueEntry(LeagueItem):
    queueType = String()
    leagueId = String()
    tier = String()
Пример #24
0
 class Input(object):
     """
     Input to create a trading account. Right now it's only a name.
     """
     name = String()
Пример #25
0
 class Arguments:
     username = String()
     password = String()
Пример #26
0
class GDataPoint(ObjectType):
    """
    GraphQL definition of the DataPoint above
    """
    date = String()
    value = Float()
Пример #27
0
class Viewer(ObjectType, PollQueries):
    id = GlobalID()
    user = Field(UserNode, jwt_token=String())

    class Meta:
        interfaces = (TokensInterface, )
Пример #28
0
class GUserBank(DjangoObjectType):
    """
    GraphQL representation of a UserBank
    """
    balance = Float()
    income = Float()
    name = String()
    outcome = Float()
    history = List(GDataPoint, args={'start': Argument(NonNull(String))})

    class Meta(object):
        """
        Meta Model for UserBank
        """
        model = UserBank
        only_fields = ('id', 'balance', 'income', 'outcome')
        interfaces = (relay.Node, )

    @staticmethod
    def resolve_history(data, args, context, _info):
        """
        Builds the financial history for the user
        """
        start = args['start']
        end = datetime.datetime.now().strftime("%Y-%m-%d")
        response = context.plaid.Transactions.get(data.access_token,
                                                  start_date=start,
                                                  end_date=end)
        transactions = response['transactions']
        value = GUserBank.resolve_balance(data, {}, context, None)
        value_list = [DataPoint(end, value)]
        for transaction in transactions:
            value = value - transaction['amount']
            if not value_list[-1].date == transaction['date']:
                value_list.append(DataPoint(transaction['date'], value))
        return value_list

    @staticmethod
    def resolve_balance(data, _args, context, _info):
        """
        Finds the current balance of the user
        """
        balances = context.plaid.Accounts.balance.get(
            data.access_token)['accounts']
        extracted_balances = [
            ((b['balances']['available'] if b['balances']['available']
              is not None else b['balances']['current']) *
             (1 if b['subtype'] == 'credit card' else -1)) for b in balances
        ]
        balance = sum(extracted_balances)
        return float(balance)

    @staticmethod
    def resolve_name(data, _args, context, _info):
        """
        Returns the name of the bank account
        """
        name = context.plaid.Accounts.get(
            data.access_token)['accounts'][0]['name']
        return name

    @staticmethod
    def resolve_income(data, _args, context, _info):
        """
        Calculates the income a user has per month
        """
        start = (datetime.datetime.now() -
                 datetime.timedelta(days=30)).strftime("%Y-%m-%d")
        end = datetime.datetime.now().strftime("%Y-%m-%d")
        response = context.plaid.Transactions.get(
            data.access_token,
            start_date=start,
            end_date=end,
        )
        transactions = response['transactions']
        plus = sum(
            filter(lambda x: x > 0, [tx['amount'] for tx in transactions]))
        return float(plus)

    @staticmethod
    def resolve_outcome(data, _args, context, _info):
        """
        Calculates the expenses a user has
        """
        start = (datetime.datetime.now() -
                 datetime.timedelta(days=30)).strftime("%Y-%m-%d")
        end = datetime.datetime.now().strftime("%Y-%m-%d")
        response = context.plaid.Transactions.get(
            data.access_token,
            start_date=start,
            end_date=end,
        )
        transactions = response['transactions']
        plus = sum(
            filter(lambda x: x < 0, [tx['amount'] for tx in transactions]))
        return float(plus)
 def mutate(self, info, string):
     storage.append(string)
     return String(string=string)
Пример #30
0
class QueryType(ObjectType):
    class Meta:
        name = "Query"
        description = "..."

    # User
    login = Field(Login,
                  email=String(required=True),
                  password=String(required=True),
                  remember_me=Boolean(),
                  required=True)

    # Company
    company = Field(CompanyType, _id=ID(required=True))
    company_list = List(CompanyType)
    company_members = List(UserType, company_id=ID(required=True))

    # Product
    product_category_list = List(ProductCategoryType)
    product_category = Field(ProductCategoryType, _id=ID(required=True))
    product = Field(ProductType, _id=ID(required=True))
    product_list = List(ProductType, company_id=ID(required=True))

    # Contact
    customer = Field(CustomerType, _id=ID(required=True))
    customer_list = List(CustomerType, company_id=ID(required=True))

    # Campaign
    campaign = Field(CampaignType, _id=ID(required=True))
    campaign_list = List(CampaignType, company_id=ID(required=True))

    # RESOLVERS
    @staticmethod
    def resolve_login(root, info, email, password, remember_me=False):
        user = UserModel.find_by_email(email)
        if user and check_password_hash(user.password, password):
            return Login(user=user, token=create_tokens(user, remember_me))
        raise Exception("email or password were incorrect")

    @staticmethod
    def resolve_company(root, info, _id):
        return CompanyModel.find_by_id(_id)

    @staticmethod
    def resolve_company_list(root, info):
        return CompanyModel.find_all()

    @staticmethod
    def resolve_company_members(root, info, company_id):
        return UserModel.find_many_by("company", company_id)

    @staticmethod
    def resolve_product_category_list(root, info):
        return ProductCategoryModel.find_all()

    @staticmethod
    def resolve_product_category(root, info, _id):
        return ProductCategoryModel.find_by_id(_id)

    @staticmethod
    def resolve_product_list(root, info, company_id):
        return ProductModel.find_many_by(company_id)

    @staticmethod
    def resolve_product(root, info, _id):
        return ProductModel.find_by_id(_id)

    @staticmethod
    def resolve_customer(root, info, _id):
        return CustomerModel.find_by_id(_id)

    @staticmethod
    def resolve_customer_list(root, info, company_id):
        return CustomerModel.find_many_by(company_id)

    @staticmethod
    def resolve_campaign(root, info, _id):
        return CampaignModel.find_by_id(_id)

    @staticmethod
    def resolve_campaign_list(root, info, company_id):
        return CampaignModel.find_many_by(company_id)