def get_months(self, months, sponsorships):
        """
        Given the list of months to print,
        returns the list of months grouped by the frequency payment
        of the contract group and only containing unpaid sponsorships.
        :param months: list of dates (date, datetime or string)
        :param sponsorships: recordset of included sponsorships
        :return: list of dates grouped in string format
        """
        self.ensure_one()
        freq = self.advance_billing_months
        payment_mode = self.with_context(lang="en_US").payment_mode_id
        # Take first open invoice or next_invoice_date
        open_invoice = min(
            [i for i in sponsorships.mapped("first_open_invoice") if i])
        if open_invoice:
            first_invoice_date = open_invoice.replace(day=1)
        else:
            raise odooWarning(_("No open invoice found !"))

        for i, month in enumerate(months):
            if isinstance(month, str):
                months[i] = fields.Date.from_string(month)
            if isinstance(month, datetime):
                months[i] = month.date()

        # check if first invoice is after last month
        if first_invoice_date > months[-1]:
            raise odooWarning(_(f"First invoice is after Date Stop"))

        # Only keep unpaid months
        valid_months = [
            fields.Date.to_string(month) for month in months
            if month >= first_invoice_date
        ]
        if "Permanent" in payment_mode.name:
            return valid_months[:1]
        if freq == 1:
            return valid_months
        else:
            # Group months
            result = list()
            count = 1
            month_start = ""
            for month in valid_months:
                if not month_start:
                    month_start = month
                if count < freq:
                    count += 1
                else:
                    result.append(month_start + " - " + month)
                    month_start = ""
                    count = 1
            if not result:
                result.append(month_start + " - " + month)
            return result
 def update(self):
     """ Refresh the texts of communications given the new template. """
     self.ensure_one()
     communications = self._get_communications()
     event = communications.mapped("event_id")
     if event:
         config = communications.mapped("config_id")
         if len(config) != 1:
             raise odooWarning(
                 _("You can only update text on one communication type at "
                   "time."))
         if self.event_text != event.thank_you_text:
             event.thank_you_text = self.event_text
         partner = self.ambassador_id
         if (partner and self.ambassador_text !=
                 partner.advocate_details_id.thank_you_quote):
             partner.advocate_details_id.thank_you_quote = self.ambassador_text
         template = config.email_template_id
         new_texts = template._render_template(template.body_html,
                                               template.model,
                                               communications.ids)
         for comm in communications:
             comm.body_html = new_texts[comm.id].replace(
                 event.name, self.event_name)
             if partner:
                 comm.body_html = comm.body_html.replace(
                     partner.full_name, self.ambassador_name or "")
         return True
     else:
         return super().update()
 def _default_state(self):
     communications = self._get_communications()
     event = communications.mapped("event_id")
     if event:
         if len(event) > 1:
             raise odooWarning(
                 _("You can only change one event at a time."))
         return "event"
     else:
         return "edit"
Esempio n. 4
0
    def get_report(self):
        """
        Prepare data for the report and call the selected report
        (single bvr / 2 bvr / 3 bvr).
        :return: Generated report
        """
        product_search = list()
        if self.birthday_gift:
            product_search.append(GIFT_REF[0])
        if self.general_gift:
            product_search.append(GIFT_REF[1])
        if self.family_gift:
            product_search.append(GIFT_REF[2])
        if self.project_gift:
            product_search.append(GIFT_REF[3])
        if self.graduation_gift:
            product_search.append(GIFT_REF[4])
        if not product_search:
            raise odooWarning(_("Please select at least one gift type."))

        products = self.env["product.product"].search([("default_code", "in",
                                                        product_search)])
        data = {
            "doc_ids": self.env.context.get("active_ids"),
            "product_ids": products.ids,
            "background": self.draw_background,
            "preprinted": self.preprinted,
        }
        records = self.env[self.env.context.get("active_model")].browse(
            data["doc_ids"])
        report_name = "report_compassion.report_" + self.paper_format.split(
            ".")[1]
        report_ref = self.env.ref(report_name)
        if self.pdf:
            name = records.name if len(records) == 1 else _(
                "gift payment slips")
            self.pdf_name = name + ".pdf"
            pdf_data = report_ref.with_context(
                must_skip_send_to_printer=True).render_qweb_pdf(
                    data["doc_ids"], data=data)[0]
            self.pdf_download = base64.encodebytes(pdf_data)
            self.state = "pdf"
            return {
                "name": "Download report",
                "type": "ir.actions.act_window",
                "res_model": self._name,
                "res_id": self.id,
                "view_mode": "form",
                "target": "new",
                "context": self.env.context,
            }
        return report_ref.report_action(data["doc_ids"],
                                        data=data,
                                        config=False)
    def print_report(self):
        """
        Prepare data for the report and call the selected report
        (single bvr / 3 bvr).
        :return: Generated report
        """
        product_search = list()
        if self.birthday_gift:
            product_search.append(GIFT_NAMES[0])
        if self.general_gift:
            product_search.append(GIFT_NAMES[1])
        if self.family_gift:
            product_search.append(GIFT_NAMES[2])
        if self.project_gift:
            product_search.append(GIFT_NAMES[3])
        if self.graduation_gift:
            product_search.append(GIFT_NAMES[4])
        if not product_search:
            raise odooWarning(_("Please select at least one gift type."))

        products = self.env['product.product'].with_context(
            lang='en_US').search([('name', 'in', product_search)])
        data = {
            'doc_ids': self.env.context.get('active_ids'),
            'product_ids': products.ids,
            'background': self.draw_background,
            'preprinted': self.preprinted,
        }
        records = self.env[self.env.context.get('active_model')].browse(
            data['doc_ids'])
        if self.pdf:
            data['background'] = True
            name = records.name if len(records) == 1 else \
                _('gift payment slips')
            self.pdf_name = name + '.pdf'
            self.pdf_download = base64.b64encode(
                self.env['report'].with_context(
                    must_skip_send_to_printer=True).get_pdf(
                        records.ids, self.paper_format, data=data))
            self.state = 'pdf'
            return {
                'name': 'Download report',
                'type': 'ir.actions.act_window',
                'res_model': self._name,
                'res_id': self.id,
                'view_mode': 'form',
                'target': 'new',
                'context': self.env.context,
            }
        return self.env['report'].get_action(
            records.ids, self.paper_format, data
        )
Esempio n. 6
0
    def get_months(self, months, sponsorships):
        """
        Given the list of months to print,
        returns the list of months grouped by the frequency payment
        of the contract group and only containing unpaid sponsorships.
        :param months: list of dates in string format
        :param sponsorships: recordset of included sponsorships
        :return: list of dates grouped in string format
        """
        self.ensure_one()
        freq = self.advance_billing_months
        payment_mode = self.with_context(lang='en_US').payment_mode_id
        # Take first open invoice or next_invoice_date
        open_invoice = min([
            fields.Date.from_string(i)
            for i in sponsorships.mapped('first_open_invoice') if i
        ])
        if open_invoice:
            first_invoice_date = open_invoice.replace(day=1)
        else:
            raise odooWarning(_("No open invoice found !"))

        # Only keep unpaid months
        valid_months = [
            month for month in months
            if fields.Date.from_string(month) >= first_invoice_date
        ]
        if 'Permanent' in payment_mode.name:
            return valid_months[:1]
        if freq == 1:
            return valid_months
        else:
            # Group months
            result = list()
            count = 1
            month_start = ""
            for month in valid_months:
                if not month_start:
                    month_start = month
                if count < freq:
                    count += 1
                else:
                    result.append(month_start + " - " + month)
                    month_start = ""
                    count = 1
            if not result:
                result.append(month_start + " - " + month)
            return result
Esempio n. 7
0
    def _get_report_values(self, docids, data=None):
        report = self._get_report()
        final_data = self._get_default_data()
        if data:
            if data.get("date_start") and isinstance(data["date_start"], str):
                data["date_start"] = fields.Date.from_string(data["date_start"])
            if data.get("date_stop") and isinstance(data["date_stop"], str):
                data["date_stop"] = fields.Date.from_string(data["date_stop"])
            final_data.update(data)
            if not docids and data["doc_ids"]:
                docids = data["doc_ids"]

        start = final_data["date_start"]
        stop = final_data["date_stop"]

        # Months will contain all months we want to include for payment.
        months = list()
        while start <= stop:
            months.append(start)
            start = start + relativedelta(months=1)

        sponsorships = self.env["recurring.contract"].browse(docids)
        sponsorships = sponsorships.filtered(
            lambda s: s.state not in ("terminated", "cancelled")
        )
        groups = sponsorships.mapped("group_id")
        if not groups or not months:
            raise odooWarning(_("Selection not valid. No active sponsorship found."))

        # Docs will contain the groups for which we have to print the payment
        # slip : {'recurring.contract.group': 'recurring.contract' recordset}
        docs = dict()
        for group in groups:
            docs[group] = sponsorships.filtered(lambda s: s.group_id == group)
        final_data.update(
            {
                "doc_model": report.model,  # recurring.contract.group
                "doc_ids": groups.ids,
                "docs": docs,
                "months": months,
            }
        )
        return final_data
 def print_report(self):
     """
     Prepare data for the report and call the selected report
     (single bvr / 3 bvr).
     :return: Generated report
     """
     if fields.Date.from_string(self.date_start) >= \
             fields.Date.from_string(self.date_stop):
         raise odooWarning(_("Date stop must be after date start."))
     data = {
         'date_start': self.date_start,
         'date_stop': self.date_stop,
         'gifts': self.include_gifts,
         'doc_ids': self.env.context.get('active_ids'),
         'background': self.draw_background,
         'preprinted': self.preprinted
     }
     records = self.env[self.env.context.get('active_model')].browse(
         data['doc_ids'])
     if self.pdf:
         data['background'] = True
         name = records.name if len(records) == 1 else \
             _('sponsorship payment slips')
         self.pdf_name = name + '.pdf'
         self.pdf_download = base64.b64encode(
             self.env['report'].with_context(
                 must_skip_send_to_printer=True).get_pdf(records.ids,
                                                         self.paper_format,
                                                         data=data))
         self.state = 'pdf'
         return {
             'name': 'Download report',
             'type': 'ir.actions.act_window',
             'res_model': self._name,
             'res_id': self.id,
             'view_mode': 'form',
             'target': 'new',
             'context': self.env.context,
         }
     return self.env['report'].get_action(records.ids, self.paper_format,
                                          data)
    def render_html(self, docids, data=None):
        """
        Construct the data for printing Payment Slips.
        :param data: data collected from the print wizard.
        :return: html rendered report
        """
        report = self._get_report()
        final_data = self._get_default_data()
        if data:
            final_data.update(data)

        start = fields.Datetime.from_string(final_data['date_start'])
        stop = fields.Datetime.from_string(final_data['date_stop'])

        # Months will contain all months we want to include for payment.
        months = list()
        while start <= stop:
            months.append(fields.Datetime.to_string(start))
            start = start + relativedelta(months=1)

        sponsorships = self.env['recurring.contract'].browse(docids)
        sponsorships = sponsorships.filtered(lambda s: s.state not in
                                             ('terminated', 'cancelled'))
        groups = sponsorships.mapped('group_id')
        if not groups or not months:
            raise odooWarning(
                _("Selection not valid. No active sponsorship found."))

        # Docs will contain the groups for which we have to print the payment
        # slip : {'recurring.contract.group': 'recurring.contract' recordset}
        docs = dict()
        for group in groups:
            docs[group] = sponsorships.filtered(lambda s: s.group_id == group)
        final_data.update({
            'doc_model': report.model,  # recurring.contract.group
            'doc_ids': groups.ids,
            'docs': docs,
            'months': months
        })
        return self.env['report'].render(report.report_name, final_data)
Esempio n. 10
0
class DbBackup(models.Model):
    _name = 'db.backup'

    @api.multi
    def get_db_list(self, host, port):
        uri = 'http://' + host + ':' + port
        conn = xmlrpclib.ServerProxy(uri + '/xmlrpc/db')
        db_list = execute(conn, 'list')
        return db_list

    @api.multi
    def _get_db_name(self):
        db_name = self._cr.dbname
        return db_name

    # Columns for local server configuration
    host = fields.Char('Host', size=100, required=True, default='localhost')
    port = fields.Char('Port', size=10, required=True, default=8069)
    name = fields.Char('Database',
                       size=100,
                       required=True,
                       help='Database you want to schedule backups for',
                       default=_get_db_name)
    folder = fields.Char('Backup Directory',
                         size=100,
                         help='Absolute path for storing the backups',
                         required='True',
                         default='/odoo/backups')
    backup_type = fields.Selection([('zip', 'Zip'), ('dump', 'Dump')],
                                   'Backup Type',
                                   required=True,
                                   default='dump')
    autoremove = fields.Boolean('Auto. Remove Backups',
                                help='If you check this option you can '
                                'choose to automaticly remove the '
                                'backup after xx days')
    days_to_keep = fields.Integer(
        'Remove after x days',
        help="Choose after how many days the backup should be deleted. For "
        "example:\nIf you fill in 5 the backups will be removed after "
        "5 days.",
        required=True)

    # Columns for external server (SFTP)
    sftp_write = fields.Boolean('Write to external server with sftp',
                                help="If you check this option you can "
                                "specify the details needed to write to "
                                "a remote server with SFTP.")
    sftp_path = fields.Char(
        'Path external server',
        help='The location to the folder where the dumps should be written '
        'to. For example /odoo/backups/.\nFiles will then be written to '
        '/odoo/backups/ on your remote server.')
    sftp_host = fields.Char('IP Address SFTP Server',
                            help='The IP address from your remote server. '
                            'For example 192.168.0.1')
    sftp_port = fields.Integer(
        'SFTP Port',
        help='The port on the FTP server that accepts SSH/SFTP calls.',
        default=22)
    sftp_user = fields.Char(
        'Username SFTP Server',
        help='The username where the SFTP connection should be made with. '
        'This is the user on the external server.')
    sftp_password = fields.Char(
        'Password User SFTP Server',
        help='The password from the user where the SFTP connection should be '
        'made with. This is the password from the user on the external '
        'server.')
    days_to_keep_sftp = fields.Integer(
        'Remove SFTP after x days',
        help='Choose after how many days the backup should be deleted from the'
        ' FTP server. For example:\nIf you fill in 5 the backups will be '
        'removed after 5 days from the FTP server.',
        default=30)
    send_mail_sftp_fail = fields.Boolean(
        'Auto. E-mail on backup fail',
        help='If you check this option you can choose to automaticly get '
        'e-mailed when the backup to the external server failed.')
    email_to_notify = fields.Char(
        'E-mail to notify',
        help='Fill in the e-mail where you want to be '
        'notified that the backup failed on the FTP.')

    @api.multi
    def _check_db_exist(self):
        self.ensure_one()

        db_list = self.get_db_list(self.host, self.port)
        if self.name in db_list:
            return True
        return False

    _constraints = [(_check_db_exist, _('Error ! No such database exists!'),
                     [])]

    @api.multi
    def test_sftp_connection(self, context=None):
        self.ensure_one()

        # Check if there is a success or fail and write messages
        message_title = ""
        message_content = ""

        for rec in self:
            try:
                ip_host = rec.sftp_host
                post_host = rec.sftp_port
                username_login = rec.sftp_user
                password_login = rec.sftp_password
                # Connect with external server over SFTP, so we know sure that
                # everything works.
                srv = pysftp.Connection(host=ip_host,
                                        username=username_login,
                                        password=password_login,
                                        port=post_host)
                srv.close()
                # We have a success.
                message_title = "Connection Test Succeeded!"
                message_content = "Everything seems properly set up for " \
                                  "FTP back-ups!"
            except Exception, e:
                message_title = "Connection Test Failed!"
                if len(rec.sftp_host) < 8:
                    message_content += "\nYour IP address seems to be too " \
                                       "short.\n"
                message_content += "Here is what we got instead:\n"
        if "Failed" in message_title:
            raise odooWarning(
                _(message_title + '\n\n' + message_content + "%s") %
                tools.ustr(e))
        else:
            raise odooWarning(_(message_title + '\n\n' + message_content))