'Prepares the GROUP BY and ORDER BY terms for the read_group method. Adds the missing JOIN clause
to the query if order should be computed against m2o field.
:param orderby: the orderby definition in the form "%(field)s %(order)s"
:param aggregated_fields: list of aggregated fields in the query
:param annotated_groupbys: list of dictionaries returned by _read_group_process_groupby
These dictionaries contains the qualified name of each groupby
(fully qualified SQL name for the corresponding field),
and the (non raw) field name.
:param osv.Query query: the query under construction
:return: (groupby_terms, orderby_terms)'

@api.model
def _read_group_prepare(self, orderby, aggregated_fields, annotated_groupbys, query):

    orderby_terms = []
    groupby_terms = [gb['qualified_field'] for gb in annotated_groupbys]
    groupby_fields = [gb['groupby'] for gb in annotated_groupbys]
    if (not orderby):
        return (groupby_terms, orderby_terms)
    self._check_qorder(orderby)
    for order_part in orderby.split(','):
        order_split = order_part.split()
        order_field = order_split[0]
        if ((order_field == 'id') or (order_field in groupby_fields)):
            if (self._fields[order_field.split(':')[0]].type == 'many2one'):
                order_clause = self._generate_order_by(order_part, query).replace('ORDER    BY    ', '')
                if order_clause:
                    orderby_terms.append(order_clause)
                    groupby_terms += [order_term.split()[0] for order_term in order_clause.split(',')]
            else:
                order = ('"%s"    %s' % (order_field, ('' if (len(order_split) == 1) else order_split[1])))
                orderby_terms.append(order)
        elif (order_field in aggregated_fields):
            orderby_terms.append(order_part)
        else:
            _logger.warn('%s:    read_group    order    by    `%s`    ignored,    cannot    sort    on    empty    columns    (not    grouped/aggregated)', self._name, order_part)
    return (groupby_terms, orderby_terms)
