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.

83 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. _description = 'SQL View CSV Preview'
  28. _columns = {
  29. 'limit': fields.integer(string='Limit',
  30. help='Number of records. 0 means infinite.'),
  31. 'data': fields.binary('CSV', readonly=True),
  32. 'filename': fields.char('File Name', readonly=True),
  33. }
  34. _defaults = {
  35. 'filename': 'csv-preview.csv',
  36. 'limit': 100,
  37. }
  38. def _query(self, cr, uid, form, sql_view, context=None):
  39. view_name = sql_view.complete_sql_name
  40. query = "SELECT * FROM {view_name} "
  41. if form.limit:
  42. query += "LIMIT {limit}"
  43. return query.format(view_name=view_name, limit=form.limit)
  44. def export_csv(self, cr, uid, ids, context=None):
  45. if context is None:
  46. return
  47. sql_view_ids = context.get('active_ids', [])
  48. assert len(ids) == 1, "1 wizard ID expected"
  49. assert len(sql_view_ids) == 1, "1 active ID expected"
  50. form = self.browse(cr, uid, ids[0], context=context)
  51. sql_view = self.pool['sql.view'].browse(cr, uid, sql_view_ids[0],
  52. context=context)
  53. query = self._query(cr, uid, form, sql_view, context=context)
  54. cr.execute(query)
  55. headers = [desc[0] for desc in cr.description]
  56. records = cr.fetchall()
  57. filedata = StringIO()
  58. try:
  59. writer = unicodecsv.writer(filedata, encoding='utf-8')
  60. writer.writerow(headers)
  61. writer.writerows(records)
  62. form.write({'data': base64.encodestring(filedata.getvalue())})
  63. finally:
  64. filedata.close()
  65. return {
  66. 'type': 'ir.actions.act_window',
  67. 'res_model': self._name,
  68. 'view_mode': 'form',
  69. 'view_type': 'form',
  70. 'res_id': ids[0],
  71. 'views': [(False, 'form')],
  72. 'target': 'new',
  73. }