persistor.py 2.66 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
# -*- coding: UTF-8 -*-

# Copyright (C) 2016 Avencall
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from xivo_dao.alchemy.outcall import Outcall
from xivo_dao.alchemy.rightcallmember import RightCallMember
from xivo_dao.alchemy.schedulepath import SchedulePath

from xivo_dao.helpers import errors
from xivo_dao.resources.utils.search import SearchResult, CriteriaBuilderMixin


class OutcallPersistor(CriteriaBuilderMixin):

    _search_table = Outcall

    def __init__(self, session, outcall_search):
        self.session = session
        self.outcall_search = outcall_search

    def find_by(self, criteria):
        query = self._find_query(criteria)
        return query.first()

    def _find_query(self, criteria):
        query = self.session.query(Outcall)
        return self.build_criteria(query, criteria)

    def get_by(self, criteria):
        outcall = self.find_by(criteria)
        if not outcall:
            raise errors.not_found('Outcall', **criteria)
        return outcall

    def find_all_by(self, criteria):
        query = self._find_query(criteria)
        return query.all()

    def search(self, parameters):
        rows, total = self.outcall_search.search(self.session, parameters)
        return SearchResult(total, rows)

    def create(self, outcall):
        self.session.add(outcall)
59
        outcall.fix_context()
60 61 62 63 64
        self.session.flush()
        return outcall

    def edit(self, outcall):
        self.session.add(outcall)
65
        outcall.fix_context()
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
        self.session.flush()

    def delete(self, outcall):
        self._delete_associations(outcall)
        self.session.delete(outcall)
        self.session.flush()

    def _delete_associations(self, outcall):
        (self.session.query(RightCallMember)
         .filter(RightCallMember.type == 'outcall')
         .filter(RightCallMember.typeval == str(outcall.id))
         .delete())

        (self.session.query(SchedulePath)
         .filter(SchedulePath.path == 'outcall')
         .filter(SchedulePath.pathid == outcall.id)
         .delete())