def delete_issue(linked_projects, issue):

        # ----------------------------------------------- ПОДГОТОВКА -----------------------------------------------

        # дополнительная проверка, что проекты связаны
        if (linked_projects.count() == 0):

            error_text = "ERROR: process_payload_from_gh.delete_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but the project is not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_projects = linked_projects[0]

        linked_issues = linked_projects.get_issue_by_id_gh(issue['issue_id'])

        # дополнительная проверка, что issue связаны
        if (linked_issues.count() == 0):

            error_text = "ERROR: process_payload_from_gh.delete_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but it's not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_issues = linked_issues[0]

        # -------------------------------------- УДАЛЕНИЕ ДАННЫХ В РЕДМАЙНЕ ----------------------------------------

        issue_url_rm = url_rm.replace(
            '.json', '/' + str(linked_issues.issue_id_rm) + '.json')

        request_result = requests.delete(issue_url_rm, headers=headers_rm)

        # удаление linked_issues из базы данных
        linked_issues.delete()

        # ДЕБАГГИНГ
        log_issue_gh(request_result, issue, linked_issues,
                     linked_projects.project_id_rm)

        return request_result
    def label_issue(linked_projects, issue):

        # ----------------------------------------------- ПОДГОТОВКА -----------------------------------------------

        # дополнительная проверка, что проекты связаны
        if (linked_projects.count() == 0):

            error_text = "ERROR: process_payload_from_gh.label_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but the project is not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_projects = linked_projects[0]

        project_id_rm = linked_projects.project_id_rm

        linked_issues = linked_projects.get_issue_by_id_gh(issue['issue_id'])

        # дополнительная проверка, что issue связаны
        if (linked_issues.count() == 0):

            error_text = "ERROR: process_payload_from_gh.label_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but it's not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_issues = linked_issues[0]

        priority_id_rm = None
        status_id_rm = None
        tracker_id_rm = None
        incorrect_labels = False
        labels = issue['labels']
        for label in labels:

            label_gh = match_label_to_rm(label['name'])

            #если label известный
            if (label_gh != None):

                if (label_gh['type'] == 'Priority'):

                    if (priority_id_rm == None):

                        priority_id_rm = label_gh['id_rm']

                        if (priority_id_rm != linked_issues.priority_id_rm):
                            incorrect_labels = True

                    else:
                        incorrect_labels = True

                elif (label_gh['type'] == 'Status'):

                    if (status_id_rm == None):

                        status_id_rm = label_gh['id_rm']

                        if (status_id_rm != linked_issues.status_id_rm):
                            incorrect_labels = True

                    else:
                        incorrect_labels = True

                elif (label_gh['type'] == 'Tracker'):

                    if (tracker_id_rm == None):
                        tracker_id_rm = label_gh['id_rm']

                    # пользователь выбрал новый трекер, но не удалил старый -> выбираем новый
                    else:
                        if (tracker_id_rm == linked_issues.tracker_id_rm):
                            tracker_id_rm = label_gh['id_rm']

        # проверяем, был ли изменён трекер
        if (tracker_id_rm == None):
            tracker_id_rm = linked_issues.tracker_id_rm

        # ------------------------------------------ ОБРАБОТКА ФРАЗЫ БОТА -----------------------------------------

        #title = '[From Github] ' + issue['issue_title']
        title = issue['issue_title']

        # проверяем, если автор issue - бот
        if (chk_if_gh_user_is_our_bot(issue['issue_author_id'])):
            issue_body = del_bot_phrase(
                issue['issue_body'])  # удаляем фразу бота

        else:
            issue_body = add_bot_phrase(issue,
                                        'issue_body')  # добавляем фразу бота

        comment_body = add_bot_phrase(
            issue, 'comment_body_action'
        )  # добавляем фразу бота в комментарий к действию

        # обработка спец. символов
        title = align_special_symbols(title)
        issue_body = align_special_symbols(issue_body)
        comment_body = align_special_symbols(comment_body)

        # --------------------------------------- ЗАГРУЗКА ДАННЫХ В РЕДМАЙН ----------------------------------------

        # корректируем label-ы в гитхабе
        tracker = match_tracker_to_gh(tracker_id_rm)
        request_result = correct_gh_labels(
            issue, tracker, linked_issues)  # корректируем label-ы в гитхабе

        if (request_result.status_code != 200):

            # сообщаем об ошибке
            error_text = "ERROR: process_payload_from_gh.label_issue\n" +\
                         "Encountered some error while trying to correct labels in Github"

            return LOGICAL_ERR(error_text)

        # TODO: похоже, он не успевает изменить linked_issues.tracker_id_rm: вебхуки приходят почти одновременно
        # проверяем, был ли изменён трекер и предотвращаем множественную отправку сообщений в гитхаб
        if ((tracker_id_rm != linked_issues.tracker_id_rm) &
            (issue['action'] == 'labeled')):

            # обновляем информацию в таблице
            update_linked_issues(linked_issues, tracker_id_rm,
                                 linked_issues.status_id_rm,
                                 linked_issues.priority_id_rm, True)

            issue_templated = issue_redmine_template.render(
                project_id=project_id_rm,
                issue_id=linked_issues.issue_id_rm,
                tracker_id=tracker_id_rm,
                status_id=linked_issues.status_id_rm,
                priority_id=linked_issues.priority_id_rm,
                subject=title,
                description=issue_body,
                notes=comment_body)

            # кодировка Latin-1 на некоторых задачах приводит к ошибке кодировки в питоне
            issue_templated = issue_templated.encode('utf-8')

            issue_url_rm = url_rm.replace(
                '.json', '/' + str(linked_issues.issue_id_rm) + '.json')
            request_result = requests.put(issue_url_rm,
                                          data=issue_templated,
                                          headers=headers_rm)

        # проверяем, корректные ли label-ы
        if (incorrect_labels):

            # сообщаем об ошибке
            error_text = "ERROR: process_payload_from_gh.label_issue\n" +\
                         "incorrect labels in GITHUB"

            return LOGICAL_ERR(error_text)

        else:

            # ДЕБАГГИНГ
            log_issue_gh(request_result, issue, linked_issues,
                         linked_projects.project_id_rm)

            return request_result
    def reject_issue(linked_projects, issue):

        # ----------------------------------------------- ПОДГОТОВКА ----------------------------------------------

        # дополнительная проверка, что проекты связаны
        if (linked_projects.count() == 0):

            error_text = "ERROR: process_payload_from_gh.reject_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but the project is not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_projects = linked_projects[0]

        project_id_rm = linked_projects.project_id_rm
        repos_id_gh = linked_projects.repos_id_gh
        url_gh = make_gh_repos_url(repos_id_gh)

        linked_issues = linked_projects.get_issue_by_id_gh(issue['issue_id'])

        # дополнительная проверка, что issue связаны
        if (linked_issues.count() == 0):

            error_text = "ERROR: process_payload_from_gh.reject_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but it's not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_issues = linked_issues[0]

        # обновляем информацию в таблице
        update_linked_issues(
            linked_issues,
            linked_issues.tracker_id_rm,
            status_ids_rm[4],  # 4 - rejected
            linked_issues.priority_id_rm,
            False)

        # ------------------------------------------ ОБРАБОТКА ФРАЗЫ БОТА -----------------------------------------

        #title = '[From Github] ' + issue['issue_title']
        title = issue['issue_title']

        # проверяем, если автор issue - бот
        if (chk_if_gh_user_is_our_bot(issue['issue_author_id'])):
            issue_body = del_bot_phrase(
                issue['issue_body'])  # удаляем фразу бота

        else:
            issue_body = add_bot_phrase(issue,
                                        'issue_body')  # добавляем фразу бота

        comment_body = add_bot_phrase(
            issue, 'comment_body_action'
        )  # добавляем фразу бота в комментарий к действию

        # обработка спец. символов
        title = align_special_symbols(title)
        issue_body = align_special_symbols(issue_body)
        comment_body = align_special_symbols(comment_body)

        # --------------------------------------- ЗАГРУЗКА ДАННЫХ В РЕДМАЙН ----------------------------------------

        issue_templated = issue_redmine_template.render(
            project_id=project_id_rm,
            issue_id=linked_issues.issue_id_rm,
            tracker_id=linked_issues.tracker_id_rm,
            status_id=status_ids_rm[4],  # 4 - rejected
            priority_id=linked_issues.priority_id_rm,
            subject=title,
            description=issue_body,
            notes=comment_body)

        # кодировка Latin-1 на некоторых задачах приводит к ошибке кодировки в питоне
        issue_templated = issue_templated.encode('utf-8')

        issue_url_rm = url_rm.replace(
            '.json', '/' + str(linked_issues.issue_id_rm) + '.json')
        request_result = requests.put(issue_url_rm,
                                      data=issue_templated,
                                      headers=headers_rm)

        # удаление linked_issues из базы данных
        linked_issues.delete()

        # ДЕБАГГИНГ
        log_issue_gh(request_result, issue, linked_issues,
                     linked_projects.project_id_rm)

        return request_result
    def edit_issue(linked_projects, issue, is_opened):

        # ----------------------------------------------- ПОДГОТОВКА ----------------------------------------------

        # дополнительная проверка, что проекты связаны
        if (linked_projects.count() == 0):

            error_text = "ERROR: process_payload_from_gh.edit_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but the project is not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_projects = linked_projects[0]

        project_id_rm = linked_projects.project_id_rm
        repos_id_gh = linked_projects.repos_id_gh
        url_gh = make_gh_repos_url(repos_id_gh)

        linked_issues = linked_projects.get_issue_by_id_gh(issue['issue_id'])

        # дополнительная проверка, что issue связаны
        if (linked_issues.count() == 0):

            error_text = "ERROR: process_payload_from_gh.edit_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but it's not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_issues = linked_issues[0]

        # проверка: что issue был отклонён (запрещаем открывать вновь)
        """
        if (linked_issues.status_id_rm == status_ids_rm[4]):

            if (is_opened == True):

                return close_gh_issue(linked_issues, url_gh)
        """

        # настройка label-ов
        tracker_id_rm = None

        for label in issue['labels']:

            tracker_rm = match_label_to_rm(label['name'])

            # если label известный
            if (tracker_rm != None):

                if (tracker_rm['type'] == 'Tracker'):

                    if (tracker_id_rm == None):
                        tracker_id_rm = tracker_rm['id_rm']

                    # если пользователь выбрал более одного трекера -> значение по умолчанию
                    else:
                        tracker_id_rm = tracker_ids_rm[0]

        # проверяем, был ли установлен трекер
        if (tracker_id_rm == None):
            tracker_id_rm = tracker_ids_rm[0]

        # корректируем label-ы в гитхабе
        tracker = match_tracker_to_gh(linked_issues.tracker_id_rm)
        correct_gh_labels(issue, tracker, linked_issues)

        # обновляем информацию в таблице
        update_linked_issues(linked_issues, tracker_id_rm,
                             linked_issues.status_id_rm,
                             linked_issues.priority_id_rm, is_opened)

        # ------------------------------------------ ОБРАБОТКА ФРАЗЫ БОТА -----------------------------------------

        #title = '[From Github] ' + issue['issue_title']
        title = issue['issue_title']

        # проверяем, если автор issue - бот
        if (chk_if_gh_user_is_our_bot(issue['issue_author_id'])):
            issue_body = del_bot_phrase(
                issue['issue_body'])  # удаляем фразу бота

        else:
            issue_body = add_bot_phrase(issue,
                                        'issue_body')  # добавляем фразу бота

        comment_body = add_bot_phrase(
            issue, 'comment_body_action'
        )  # добавляем фразу бота в комментарий к действию

        # обработка спец. символов
        title = align_special_symbols(title)
        issue_body = align_special_symbols(issue_body)
        comment_body = align_special_symbols(comment_body)

        # --------------------------------------- ЗАГРУЗКА ДАННЫХ В РЕДМАЙН ----------------------------------------

        if (is_opened):
            status_id = linked_issues.status_id_rm

        else:
            status_id = status_ids_rm[5]  # closed

        issue_templated = issue_redmine_template.render(
            project_id=project_id_rm,
            issue_id=linked_issues.issue_id_rm,
            tracker_id=linked_issues.tracker_id_rm,
            status_id=status_id,
            priority_id=linked_issues.priority_id_rm,
            subject=title,
            description=issue_body,
            notes=comment_body)

        # кодировка Latin-1 на некоторых задачах приводит к ошибке кодировки в питоне
        issue_templated = issue_templated.encode('utf-8')

        issue_url_rm = url_rm.replace(
            '.json', '/' + str(linked_issues.issue_id_rm) + '.json')
        request_result = requests.put(issue_url_rm,
                                      data=issue_templated,
                                      headers=headers_rm)

        # ДЕБАГГИНГ
        log_issue_gh(request_result, issue, linked_issues,
                     linked_projects.project_id_rm)

        return request_result
    def post_issue(linked_projects, issue):

        # ----------------------------------------------- ПОДГОТОВКА ----------------------------------------------

        # дополнительная проверка, что проекты связаны
        if (linked_projects.count() == 0):

            error_text = "ERROR: process_payload_from_gh.post_issue\n" +\
                         "issue " + str(issue['action']) + " in GITHUB, but the project is not linked to REDMINE"

            return PREPARATION_ERR(error_text)

        linked_projects = linked_projects[0]

        project_id_rm = linked_projects.project_id_rm

        # настройка label-ов
        tracker_id_rm = None
        status_id_rm = status_ids_rm[0]
        priority_id_rm = priority_ids_rm[0]

        for label in issue['labels']:

            tracker_rm = match_label_to_rm(label['name'])

            # если label известный
            if (tracker_rm != None):

                if (tracker_rm['type'] == 'Tracker'):

                    if (tracker_id_rm == None):
                        tracker_id_rm = tracker_rm['id_rm']

                    # если пользователь выбрал более одного трекера -> значение по умолчанию
                    else:
                        tracker_id_rm = tracker_ids_rm[0]

        # проверяем, был ли установлен трекер
        if (tracker_id_rm == None):
            tracker_id_rm = tracker_ids_rm[0]

        # ------------------------------------------ ОБРАБОТКА ФРАЗЫ БОТА -----------------------------------------

        #title = '[From Github] ' + issue['issue_title']
        title = issue['issue_title']
        issue_body = add_bot_phrase(issue,
                                    'issue_body')  # добавляем фразу бота

        # обработка спец. символов
        title = align_special_symbols(title)
        issue_body = align_special_symbols(issue_body)

        # --------------------------------------- ЗАГРУЗКА ДАННЫХ В РЕДМАЙН ----------------------------------------

        issue_templated = issue_redmine_template.render(
            project_id=project_id_rm,
            tracker_id=tracker_id_rm,
            status_id=status_id_rm,
            priority_id=priority_id_rm,
            subject=title,
            description=issue_body)

        # кодировка по умолчанию (Latin-1) на некоторых задачах приводит к ошибке кодировки в питоне
        issue_templated = issue_templated.encode('utf-8')

        request_result = requests.post(url_rm,
                                       data=issue_templated,
                                       headers=headers_rm)

        # ------------------------------------------ СОХРАНЕНИЕ ДАННЫХ --------------------------------------------

        posted_issue = json.loads(request_result.text)

        # занесение в базу данных информацию о том, что данные issues связаны
        linked_issues = Linked_Issues.objects.create_linked_issues(
            posted_issue['issue']['id'],  # id issue в редмайне
            issue['issue_id'],  # id issue в гитхабе
            issue['repos_id'],  # id репозитория в гитхабе
            issue['issue_number'],  # номер issue  в репозитории гитхаба
            tracker_id_rm,  # id трекера в редмайне
            status_id_rm,  # id статуса в редмайне
            priority_id_rm,  # id приоритета в редмайне
            True)  # открыт

        # добавляем linked_issues в linked_projects
        linked_projects.add_linked_issues(linked_issues)

        # корректируем label-ы в гитхабе
        tracker = match_tracker_to_gh(linked_issues.tracker_id_rm)
        correct_gh_labels(issue, tracker, linked_issues)

        # ДЕБАГГИНГ
        log_issue_gh(request_result, issue, linked_issues,
                     linked_projects.project_id_rm)

        return request_result