You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.8 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. #
  4. # Authors: Guewen Baconnier
  5. # Copyright 2015 Camptocamp SA
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. #
  21. import base64
  22. from StringIO import StringIO
  23. import unicodecsv
  24. from openerp.osv import orm, fields
  25. class SQLViewCSVPreview(orm.TransientModel):
  26. _name = 'sql.view.csv.preview'
  27. _columns = {
  28. 'limit': fields.integer(string='Limit',
  29. help='Number of records. 0 means infinite.'),
  30. 'data': fields.binary('CSV', readonly=True),
  31. 'filename': fields.char('File Name', readonly=True),
  32. }
  33. _defaults = {
  34. 'filename': 'csv-preview.csv',
  35. 'limit': 100,
  36. }
  37. def _query(self, cr, uid, form, sql_view, context=None):
  38. view_name = sql_view.complete_sql_name
  39. query = "SELECT * FROM {view_name} "
  40. if form.limit:
  41. query += "LIMIT {limit}"
  42. return query.format(view_name=view_name, limit=form.limit)
  43. def export_csv(self, cr, uid, ids, context=None):
  44. if context is None:
  45. return
  46. sql_view_ids = context.get('active_ids', [])
  47. assert len(ids) == 1, "1 wizard ID expected"
  48. assert len(sql_view_ids) == 1, "1 active ID expected"
  49. form = self.browse(cr, uid, ids[0], context=context)
  50. sql_view = self.pool['sql.view'].browse(cr, uid, sql_view_ids[0],
  51. context=context)
  52. query = self._query(cr, uid, form, sql_view, context=context)
  53. cr.execute(query)
  54. headers = [desc[0] for desc in cr.description]
  55. records = cr.fetchall()
  56. filedata = StringIO()
  57. try:
  58. writer = unicodecsv.writer(filedata, encoding='utf-8')
  59. writer.writerow(headers)
  60. writer.writerows(records)
  61. form.write({'data': base64.encodestring(filedata.getvalue())})
  62. finally:
  63. filedata.close()
  64. return {
  65. 'type': 'ir.actions.act_window',
  66. 'res_model': self._name,
  67. 'view_mode': 'form',
  68. 'view_type': 'form',
  69. 'res_id': ids[0],
  70. 'views': [(False, 'form')],
  71. 'target': 'new',
  72. }