Exemplo n.º 1
0
 def mutate_and_get_payload(self, info, id, **kwargs):
     if kwargs['amount'] < 0:
         raise SngyException('Сумма выплаты меньше нуля')
     if kwargs['advance'] < 0:
         raise SngyException('Аванс меньше нуля')
     SalaryPayment.objects.filter(id=id).update(**kwargs)
     return UpdateSalaryPayment(result=True)
Exemplo n.º 2
0
    def mutate_and_get_payload(root, info, **kwargs):
        try:
            report = Report.objects.get(id=kwargs.get('id'))
            user = info.context.user

            # Проверка, если залогиненный пользователь не является создателем отчета и при этом не является ГИПом
            # и не имеет прав на общее редактирование отчетов.
            user_is_not_gip = report.projects.all(
            )[0].gip != user and not user.has_perm('reports.global_manage')
            if report.user_added != user and user_is_not_gip:
                raise SngyException('Этот отчет вам не принадлежит')

            # Проверка, если отчет проверен или удален и при этом залогиненный пользователь не является ГИПом.
            if (report.checked_by or report.deleted) and user_is_not_gip:
                raise SngyException('Отчет уже проверен или удален')

            # Если "deleted" существует, тогда просто помечаем отчет как удаленный.
            if kwargs.get('deleted'):
                report.deleted = True
                report.save()

            # Если залогиненный пользователь добавил отчет, тогда удаляем его.
            elif report.user_added == user and report.checked_by is None:
                report.delete()

            # Если залогиненный пользователь добавил отчет, отчет проверен и при этом, залогиненный пользователь является
            # гипом проекта, тогда помечаем его как удаленный.
            elif report.user_added == user and report.checked_by and not user_is_not_gip:
                report.deleted = True
                report.save()
            return DeleteReport(result=True)
        except Report.DoesNotExist:
            return DeleteReport(result=False)
Exemplo n.º 3
0
	def mutate_and_get_payload(self, info, id, **kwargs):
		try:
			if Location.objects.get(id=kwargs['location_id']).project.state_id not in (2, 3, 4):
				raise SngyException('Этап проекта не допускает хранение на складе')
		except Location.DoesNotExist:
			raise SngyException('Местоположения не существует')
		try:
			unit = Unit.objects.get(id=kwargs['unit_id'])
		except Exception:
			raise SngyException('Нет такой единицы')
		if not kwargs['defect'] and not unit.restrict_sum:
			same_goods = Good.objects.filter(unit_id=kwargs['unit_id'], good_kind_id=kwargs['good_kind_id'],
			                                 location_id=kwargs['location_id'], defect=kwargs.get('defect'),
			                                 project_id=kwargs.get('project_id'),
			                                 responsible_id=kwargs['responsible_id']). \
				exclude(id=id).values('id', 'count')
			total_count = 0
			ids = list()
			for good in same_goods:
				total_count += good['count']
				ids.append(good['id'])
			if len(same_goods):
				Good.objects.filter(id__in=ids).delete()
				kwargs['count'] += total_count
		Good.objects.filter(id=id).update(**kwargs)
		good = Good.objects.get(id=id)
		return UpdateGood(good=good)
Exemplo n.º 4
0
	def mutate_and_get_payload(self, info, name):
		if name == "":
			raise SngyException("Пустое поле")
		try:
			manufacturer = Manufacturer.objects.create(name=name)
		except Exception:
			raise SngyException('Производитель с таким названием уже существует')
		return CreateManufacturer(manufacturer=manufacturer)
Exemplo n.º 5
0
	def mutate_and_get_payload(self, info, id, name):
		if name == "":
			raise SngyException("Название не заполнено")
		try:
			Manufacturer.objects.filter(id=id).update(name=name)
		except Exception:
			raise SngyException('Производитель с таким названием уже существует')
		return ChangeManufacturer(result=True)
Exemplo n.º 6
0
 def mutate_and_get_payload(self, info, id):
     project = Project.objects.get(id=id)
     if project.projectstate_set.all():
         raise SngyException('The project has reports')
     if project.bonus_set.all():
         raise SngyException('The project has bonus')
     project.delete()
     return DeleteProject(result=True)
Exemplo n.º 7
0
 def mutate_and_get_payload(root, info, name, id_task):
     if name == '':
         raise SngyException('Введите имя задачи')
     item_task = Task.objects.get(id=id_task)
     if item_task.project.gip != info.context.user:
         raise SngyException('Вы не являетесь Главным инженером проекта')
     item_task.name = name
     item_task.save()
     return EditTask(task=item_task)
Exemplo n.º 8
0
 def mutate_and_get_payload(self, info, user, position):
     try:
         user = User.objects.get(id=user)
     except User.DoesNotExist:
         raise SngyException('Нет такого сотрудника')
     if Position.objects.filter(id=position).exists():
         user.positions.add(position)
     else:
         raise SngyException('Нет такой должности')
     return AssignPosition(result=True)
Exemplo n.º 9
0
 def mutate_and_get_payload(self, info, id):
     try:
         notification = Notification.objects.get(id=id)
         if notification.purpose != info.context.user:
             raise SngyException('Это не ваше уведомление')
         notification.confirmed = True
         notification.save()
     except Notification.DoesNotExist:
         raise SngyException('Такого уведомления нет')
     return ConfirmNotification(result=True)
Exemplo n.º 10
0
 def mutate_and_get_payload(self, info, user, position):
     try:
         user = User.objects.get(id=user)
     except User.DoesNotExist:
         raise SngyException('Нет такого пользователя')
     if user.positions.filter(id=position).exists():
         position = Position.objects.get(id=position)
         user.positions.remove(position)
     else:
         raise SngyException('Нет такой должности у сотрудника')
     return RemovePosition(result=True)
Exemplo n.º 11
0
 def mutate_and_get_payload(self, info, name, project):
     proj = Project.objects.get(id=project)
     if proj.gip == info.context.user:
         try:
             task = Task.objects.create(name=name, project=proj)
         except ValidationError:
             raise SngyException(
                 'Задача с таким названием уже существует в проекте {:05d}'.
                 format(proj.number))
     else:
         raise SngyException('Вы не являетесь Главным инженером проекта')
     return AddTask(task=task)
Exemplo n.º 12
0
	def mutate_and_get_payload(self, info, id):
		try:
			if not GoodKind.objects.get(id=id).new:
				if info.context.user.has_perm('warehouse.can_moderate'):
					GoodKind.objects.get(id=id).delete()
				else:
					raise SngyException('Ошибка: Недостаточно прав!')
			else:
				GoodKind.objects.get(id=id).delete()
		except models.ProtectedError:
			raise SngyException('Данный вид товара используется товарами на складе')
		return DeleteGoodKind(result=True)
Exemplo n.º 13
0
 def mutate_and_get_payload(self, info, id):
     bonus = Bonus.objects.get(id=id)
     if bonus.month:
         raise SngyException(
             'Этот бонус или вычет нельзя удалить, т.к. он уже учтен в зарплате'
         )
     if info.context.user.has_perm(
             'users.edit_all_bonuses'
     ) or info.context.user == bonus.user_added:
         bonus.delete()
     else:
         raise SngyException('Вы не можете удалить этот бонус или вычет')
     return DeleteBonus(result=True)
Exemplo n.º 14
0
    def mutate_and_get_payload(self, info, name, object_id, comment, targets):
        if not '.' in name:
            raise SngyException('Неправильное имя')
        app_label, model = name.lower().split('.')
        content_type = ContentType(app_label=app_label, model=model)
        content_object = content_type.get_object_for_this_type(id=object_id)
        Comment.objects.create(content_object=content_object,
                               user=info.context.user,
                               comment=comment)

        users_id = [u.id for u in User.objects.all()]
        if not targets:
            targets = list(
                set([
                    c.user_id for c in Comment.objects.filter(
                        content_type__app_label=app_label,
                        content_type__model=model,
                        object_id=object_id)
                ]))
            if info.context.user.id in targets:
                targets.remove(info.context.user.id)
        for t in targets:
            if t in users_id:
                text = 'Комментарий: ' + comment
                Notification.objects.create(purpose_id=t,
                                            created=info.context.user,
                                            text=text)

        return CreateComments(result=True)
Exemplo n.º 15
0
	def resolve_selected_specification(self, info, specification_id=None):
		try:
			if not specification_id:
				return None
			return Specification.objects.get(id=specification_id)
		except Specification.DoesNotExist:
			raise SngyException('Спецификация не найдена')
Exemplo n.º 16
0
def download(request):
    if not request.user.is_authenticated:
        return HttpResponseRedirect('/')
    kind = request.GET.get('kind')
    id = request.GET.get('id')
    if not kind or not id:
        raise SngyException('Указаны не все параметры')
    try:
        file = Document.objects.get(id=id, document_kind__eng_name=kind).file
        name = os.path.split(file.name)[-1].split('_', maxsplit=1)[1]
        content_type = mimetypes.guess_type(name)[0]
        response = HttpResponse(file.read(), content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename=%s' % name
        return response
    except Document.DoesNotExist:
        raise SngyException('Такого файла не существует')
Exemplo n.º 17
0
	def mutate_and_get_payload(self, info, old_id, new_id):
		if old_id == new_id:
			raise SngyException("Выбраны одинаковые поля")
		# Получили все товары от производителя oldId
		# назначаем этим товарам производителя newId
		goods = GoodKind.objects.filter(manufacturer_id=old_id).update(manufacturer_id=new_id)
		return ChangeManufacturer(result=True)
Exemplo n.º 18
0
 def mutate_and_get_payload(root, info, **kwargs):
     absence = Absence.objects.get(id=kwargs.pop('absence_id'))
     if not absence.locked:
         absence.delete()
     else:
         raise SngyException('Невозможно удалить запись, учтенную в ЗП')
     return DeleteAbsence(success=True)
Exemplo n.º 19
0
 def mutate_and_get_payload(self, info, user_id):
     if not info.context.FILES.get('file'):
         raise SngyException('Отсутствует файл')
     user = User.objects.get(id=user_id)
     user.avatar.delete()
     user.avatar = info.context.FILES['file']
     user.save()
     return SaveUserAvatar(image_path=user.avatar.url)
Exemplo n.º 20
0
	def mutate_and_get_payload(self, info, id, **kwargs):
		fields = ['general', 'welding', 'experience', 'etech', 'schematic', 'initiative', 'discipline']
		for f in fields:
			v = kwargs.get(f, 0)
			if v < 0 or v > 1:
				raise SngyException('value < 0 or value > 1')
		Coefficients.objects.filter(id=id).update(**kwargs)
		return UpdateCoefficients(coefficients=Coefficients.objects.get(id=id))
Exemplo n.º 21
0
 def mutate_and_get_payload(self, info, **kwargs):
     if kwargs['amount'] > 0 and info.context.user.id != 5:
         raise SngyException(
             'Только генеральный директор может устанавливать сумму больше 0'
         )
     if kwargs['installments'] < 1: kwargs['installments'] = 1
     bonus = Bonus.objects.create(user_added=info.context.user, **kwargs)
     return CreateBonus(bonus=bonus)
Exemplo n.º 22
0
	def mutate_and_get_payload(self, info, old_warehouse, new_warehouse, id_good, count, responsible_id,
	                           project_id=None):
		try:
			if Location.objects.get(id=new_warehouse).project.state_id not in (2, 3, 4):
				raise SngyException('Этап проекта не допускает хранение на складе')
		except Location.DoesNotExist:
			raise SngyException('Местоположения не существует')
		if old_warehouse == new_warehouse:
			raise SngyException('Перемещение на тот же склад невозможно')
		good = Good.objects.get(id=id_good)
		if good.count < count:
			raise SngyException('В позиции нет такого количества товаров')
		if good.count == count:
			try:
				if good.defect or good.unit.restrict_sum:
					raise Good.DoesNotExist
				good_to = Good.objects.get(unit_id=good.unit_id, good_kind_id=good.good_kind_id,
				                           location_id=new_warehouse, defect=good.defect, responsible_id=responsible_id,
				                           project_id=project_id)
				good_to.count += count
				good_to.save()
				good.delete()
			except Good.DoesNotExist:
				good.location_id = new_warehouse
				good.responsible_id = responsible_id
				good.project_id = project_id
				good.save()
		else:
			try:
				if good.defect or good.unit.restrict_sum:
					raise Good.DoesNotExist
				good_to = Good.objects.get(unit_id=good.unit_id, good_kind_id=good.good_kind_id,
				                           location_id=new_warehouse, defect=good.defect, responsible_id=responsible_id,
				                           project_id=project_id)
				good_to.count += count
				good_to.save()
				good.count -= count
				good.save()
			except Good.DoesNotExist:
				Good.objects.create(count=count, unit_id=good.unit_id, location_id=new_warehouse, note=good.note,
				                    good_kind_id=good.good_kind_id, defect=good.defect, responsible_id=responsible_id,
				                    project_id=project_id)
				good.count -= count
				good.save()
		return ChangeWarehouse(result=True)
Exemplo n.º 23
0
 def mutate_and_get_payload(self, info, id, **kwargs):
     project = Project.objects.get(id=id)
     if info.context.user.has_perm(
             'user.change_project'
     ) or project.user_created == info.context.user:
         if not kwargs.get('gip_id'):
             kwargs['gip_id'] = info.context.user.id
         kwargs['description'] = kwargs['description'][:70]
         if kwargs[
                 'state_id'] != project.state_id and not info.context.user.has_perm(
                     'projects.change_project_state'):
             raise SngyException(
                 'Недостаточно прав на изменение этапа проекта')
         [setattr(project, f, kwargs[f]) for f in kwargs.keys()]
         project.save()
         return UpdateProject(project=project)
     else:
         raise SngyException('Недостаточно прав')
Exemplo n.º 24
0
	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)
Exemplo n.º 25
0
	def mutate_and_get_payload(self, info, manufacturer_name, analogs=None, **kwargs):
		if kwargs.get('code'):
			kwargs['code'] = kwargs['code'].strip()
			if GoodKind.objects.filter(code=kwargs['code'], manufacturer__name=manufacturer_name).exists():
				raise SngyException('Производитель уже имеет такой артикул')
		manufacturer = Manufacturer.objects.get_or_create(name=manufacturer_name.strip())[0]
		gosts = {g for g in kwargs.pop('gosts', [])}
		try:
			default_unit_id = kwargs.pop('default_unit')
			good_kind = GoodKind.objects.create(manufacturer=manufacturer, default_unit_id=default_unit_id, **kwargs)
			if analogs:
				good_kind.analogs.add(*analogs)
		except Exception as e:
			print(e)
			raise SngyException('Что-то не так')  # Чтобы не показывать ошибку бд
		# Присваиваем ГОСТы
		good_kind.gosts.set(handle_gosts(gosts))
		return CreateGoodKind(good_kind=good_kind)
Exemplo n.º 26
0
    def mutate_and_get_payload(root, info, **kwargs):
        try:
            report = Report.objects.get(id=kwargs.get('id'))

            # Если залогиненный пользователь это не ГИП.
            user = info.context.user
            if report.projects.all()[0].gip != user and not user.has_perm(
                    'reports.global_manage'):
                raise SngyException('Только ГИП может подтверждать отчеты')

            # Если отчет уже проверен или удален.
            if report.checked_by or report.deleted:
                raise SngyException('Отчет уже проверен или удален')
            report.checked_by = user
            report.time_checked = timezone.now()
            report.save()
            return ConfirmReport(report=report)
        except Report.DoesNotExist:
            return ConfirmReport(report=None)
Exemplo n.º 27
0
 def mutate_and_get_payload(root, info, id_task):
     task = Task.objects.get(id=id_task)
     if task.project.gip == info.context.user:
         try:
             task.delete()
             return DeleteTask(result=True)
         except Task.DoesNotExist:
             return DeleteTask(result=False)
     else:
         raise SngyException('Вы не являетесь Главным инженером проекта')
Exemplo n.º 28
0
 def mutate_and_get_payload(self, info, id, **kwargs):
     if kwargs['amount'] > 0 and info.context.user.id != 5:
         raise SngyException(
             'Только генеральный директор может устанавливать сумму больше 0'
         )
     if kwargs['installments'] < 1: kwargs['installments'] = 1
     bonus = Bonus.objects.get(id=id)
     if bonus.month:
         raise SngyException(
             'Этот бонус или вычет нельзя изменять, т.к. он уже учтен в зарплате'
         )
     if info.context.user.has_perm(
             'users.edit_all_bonuses'
     ) or info.context.user == bonus.user_added:
         [setattr(bonus, f, kwargs[f]) for f in kwargs]
         bonus.save()
     else:
         raise SngyException(
             'Вы не можете редактировать этот бонус или вычет')
     return UpdateBonus(bonus=bonus)
Exemplo n.º 29
0
 def mutate_and_get_payload(self, info, name, filters_row):
     if len(name) == 0:
         raise SngyException('Введите название')
     name = name
     filters_schema = filters_row
     user_created = info.context.user
     schema = ProjectAnalysisSchema.objects.get_or_create(
         user_created=user_created, name=name)[0]
     schema.filters_schema = filters_schema
     schema.save()
     return CreateFiltersSchema(schema=schema)
Exemplo n.º 30
0
	def mutate_and_get_payload(self, info, **kwargs):
		try:
			if Location.objects.get(id=kwargs['location_id']).project.state_id not in (2, 3, 4):
				raise SngyException('Этап проекта не допускает хранение на складе')
		except Location.DoesNotExist:
			raise SngyException('Местоположения не существует')
		try:
			try:
				unit = Unit.objects.get(id=kwargs['unit_id'])
			except Exception:
				raise SngyException('Нет такой единицы')
			if not kwargs['defect'] and not unit.restrict_sum:
				good = Good.objects.get(unit_id=kwargs['unit_id'], good_kind_id=kwargs['good_kind_id'],
				                        location_id=kwargs['location_id'], project_id=kwargs.get('project_id'),
				                        defect=kwargs.get('defect'), responsible_id=kwargs['responsible_id'])
				good.count += kwargs['count']
				good.save()
			else:
				raise Good.DoesNotExist
		except Good.DoesNotExist:
			good = Good.objects.create(**kwargs)
		return CreateGood(good=good)