event.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Odoo, Open Source Management Solution
  5. # Copyright (C) 2016-TODAY Prime Consulting SA, Cape Verde (<http://prime.cv>).
  6. #
  7. ##############################################################################
  8. from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
  9. from odoo import api, fields, models, _
  10. from odoo import tools
  11. import time,calendar,requests
  12. import datetime
  13. from odoo.exceptions import UserError, ValidationError
  14. import urlparse
  15. import json
  16. import logging
  17. _logger = logging.getLogger(__name__)
  18. from odoo.addons.mail.models.mail_template import format_tz
  19. import werkzeug
  20. from urlparse import urljoin
  21. def callFireFunction(url,data):
  22. r = requests.post(
  23. url,
  24. headers={'Content-Type': 'application/json'},
  25. data=data)
  26. if r.status_code == 200:
  27. return r.text
  28. else:
  29. raise ValidationError(r.text)
  30. class EventEvent(models.Model):
  31. _inherit = "event.event"
  32. #JCF - 06-04-2018
  33. @api.one
  34. @api.depends('island_id')
  35. def _get_island_name(self):
  36. island_name = ''
  37. if self.island_id:
  38. island_name=self.island_id.name
  39. self.island_name = island_name
  40. @api.one
  41. @api.depends('county_id')
  42. def _get_county_name(self):
  43. county_name = ''
  44. if self.county_id:
  45. county_name=self.county_id.name
  46. self.county_name = county_name
  47. @api.one
  48. @api.depends('island_id')
  49. def _get_enterprise_island_name(self):
  50. enterprise_island_name = ''
  51. if self.env.uid:
  52. enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
  53. enterprise_island_name=enterprise_id.ebusiness_id.island_id.name
  54. self.enterprise_island_name = enterprise_island_name
  55. @api.one
  56. @api.depends('island_id')
  57. def _get_advertise_data(self):
  58. advertise_script = ''
  59. if self.id:
  60. advertise_script="""<script>$("#checkme_%s").click(function() {
  61. $('#button_%s').prop('disabled', function(i, v) { return !v; });
  62. });</script>"""%(self.id,self.id)
  63. self.advertise_script = advertise_script
  64. def action_advertise_now(self):
  65. for event in self:
  66. if self.env.uid:
  67. enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
  68. if enterprise_id:
  69. event_enterprise = self.env['event.enterprise'].create({
  70. 'event_id': event.id,
  71. 'enterprise_id': enterprise_id.id,
  72. 'origin': 'registration'
  73. })
  74. return self.env['warning'].info(title=_('Info!'), message=_('Your request was registered'))
  75. event_image = fields.Binary('Event image')
  76. show_dates = fields.Boolean('Show dates',default=False)
  77. show_location = fields.Boolean('Show location',default=False)
  78. island_id = fields.Many2one('ecom.location', related="address_id.island_id", string='Island', store=True)
  79. county_id = fields.Many2one('ecom.location', related="address_id.county_id", string='County', store=True)
  80. enterprise_line = fields.One2many('event.enterprise', 'event_id', string="Enterprises")
  81. sequence = fields.Integer(default=1, help="Gives the sequence order when displaying a list of Projects.")
  82. featured = fields.Boolean(string='Featured',default=False)
  83. island_name = fields.Char(string='Island Name', compute='_get_island_name', store=True)
  84. county_name = fields.Char(string='County Name', compute='_get_county_name', store=True)
  85. num_tourists_expected = fields.Integer(string='Number of Tourists Expected')
  86. advertise_script = fields.Char(string='Advertise Script', compute='_get_advertise_data', store=True, size=4000)
  87. is_advertising = fields.Char("Is Advertising on the event", compute="_compute_is_advertising")
  88. enterprise_island_name = fields.Char(string='Enterprise Island Name', compute='_get_enterprise_island_name')
  89. event_price = fields.Float(string='Price Event')
  90. embed_map_src = fields.Text(string='Google Map Embed URL', store=True)
  91. @api.one
  92. def _compute_is_advertising(self):
  93. is_advertising,is_advertising_value = 0,'no'
  94. # we don't allow public user to see advertising label
  95. if self.env.user != self.env.ref('base.public_user'):
  96. enterprise_id = self.env.user.enterprise_id.id
  97. if enterprise_id:
  98. for event in self:
  99. domain = [('event_id', '=', event.id),('enterprise_id', '=', enterprise_id),('state','in',['open','done'])]
  100. is_advertising = self.env['event.enterprise'].search_count(domain)
  101. if is_advertising > 0:
  102. is_advertising_value='yes'
  103. else:
  104. domain = [('event_id', '=', event.id),('enterprise_id', '=', enterprise_id),('state','in',['draft'])]
  105. is_advertising = self.env['event.enterprise'].search_count(domain)
  106. if is_advertising > 0:
  107. is_advertising_value='pending'
  108. else:
  109. is_advertising_value='no'
  110. self.is_advertising = is_advertising_value
  111. @api.multi
  112. def get_image_url(self, model, field, rec_id):
  113. url = ''
  114. if model and rec_id:
  115. base_url = self.env['ir.config_parameter'].get_param('web.base.url')
  116. url = "%s" % urlparse.urljoin(base_url, 'web/image/%s/%s/%s'%(model, rec_id, field))
  117. return url
  118. @api.multi
  119. def get_min_amount(self, enterprise_id, date_begin, date_end):
  120. amount = 0
  121. if enterprise_id and date_begin and date_end:
  122. checkin_date = str(date_begin) + str(' 15:00:00')
  123. checkout_date = str(date_end) + str(' 13:00:00')
  124. self._cr.execute("""select v2.amount,(select rooms_availability_by_categ('%s','%s',%s,v2.room_type_id)) as num_rooms_categ
  125. from (select v.*,rooms_availability_no_limit('%s', '%s', %s, v.room_type_id) as num_rooms
  126. from view_fares v
  127. where v.enterprise_id=%s and '%s' between v.start_date and v.end_date) v2 where v2.num_rooms > 0 order by v2.amount limit 1;
  128. """ %
  129. (checkin_date, checkout_date, enterprise_id,checkin_date, checkout_date, enterprise_id, enterprise_id, checkin_date)
  130. )
  131. fare = self._cr.fetchone()
  132. if fare:
  133. amount = fare[0]
  134. return amount
  135. @api.one
  136. def button_publish(self):
  137. result,island_name,island_code,enterprise_info,enterprises_info,date_begin_str,date_end_str,event_image = [],'','',{},[],'','',''
  138. print "########################### PUBLISH EVENT ###########################: "
  139. if self.featured and self.featured == True:
  140. print "########################### IF ###########################: "
  141. if self.island_id:
  142. island_name = self.island_id.name
  143. island_code = self.island_id.code
  144. enterprise_id = False
  145. min_amount = 0
  146. if self.date_begin:
  147. date_begin = datetime.datetime.strptime(self.date_begin, '%Y-%m-%d %H:%M:%S').date()
  148. date_begin_str = date_begin.strftime('%Y-%m-%d')
  149. if self.date_end:
  150. date_end = datetime.datetime.strptime(self.date_end, '%Y-%m-%d %H:%M:%S').date()
  151. date_end_str = date_end.strftime('%Y-%m-%d')
  152. if self.event_image:
  153. event_image = self.get_image_url('event.event', 'event_image', self.id)
  154. if self.enterprise_line:
  155. for ent in self.enterprise_line:
  156. if ent.state == 'open' or ent.state == 'done':
  157. enterprise_id = ent.enterprise_id.id
  158. amenities_info, images_count, sold_out = [], 0, False
  159. print "ENTERPRISE ID::::::::::::::::::::: ",enterprise_id
  160. enterprise_logo = False
  161. if enterprise_id:
  162. enterprise_logo = self.get_image_url('etourism.enterprise', 'logo', enterprise_id)
  163. min_amount = self.get_min_amount(enterprise_id,date_begin_str,date_end_str)
  164. if min_amount == 0:
  165. sold_out = True
  166. if ent.enterprise_id.amenities_ids:
  167. for amenity in ent.enterprise_id.amenities_ids:
  168. if amenity.image_url and images_count < 5:
  169. amenities_icons = {}
  170. amenity_name = amenity.name
  171. amenity_image_url = amenity.image_url
  172. amenities_icons = {
  173. 'name':amenity_name,
  174. 'image_url':amenity_image_url
  175. }
  176. amenities_info.append(amenities_icons)
  177. images_count += 1
  178. #print "AMENITIES INFO::::::::::::::::::::::::::::::::::: ",amenities_info
  179. enterprise_info = {
  180. 'name': ent.enterprise_id.name,
  181. 'parish': ent.enterprise_id.parish_id.name,
  182. 'local': ent.enterprise_id.local_id.name,
  183. 'NeighBorHood': ent.enterprise_id.neighborhood_id.name,
  184. 'locations': {
  185. 'lat': ent.enterprise_id.latitude,
  186. 'long': ent.enterprise_id.longitude
  187. },
  188. 'description': {
  189. 'pt': ent.enterprise_id.comment,
  190. 'en': ent.enterprise_id.comment_en,
  191. 'fr': ent.enterprise_id.comment_fr
  192. },
  193. 'amount': min_amount,
  194. 'soldOut': sold_out,
  195. 'logo': enterprise_logo or '',
  196. 'key': ent.enterprise_id.ebusiness_id.api_key,
  197. 'rating': ent.enterprise_id.rating,
  198. 'amenities': amenities_info
  199. }
  200. enterprises_info.append(enterprise_info)
  201. event_res = {
  202. 'eventId': self.id,
  203. 'name': self.name,
  204. 'island': island_name,
  205. 'islandCode': island_code,
  206. 'date': {
  207. 'begin': date_begin_str,
  208. 'end': date_end_str
  209. },
  210. 'eventImage': event_image,
  211. 'hotels': enterprises_info
  212. }
  213. result.append(event_res)
  214. req_hash = callFireFunction(
  215. "https://us-central1-hotelsgroup-cv-prod.cloudfunctions.net/eTourismEvents",
  216. json.dumps(event_res)
  217. )
  218. class EventEnterprise(models.Model):
  219. _name = 'event.enterprise'
  220. _description = "Event Enterprises"
  221. event_id = fields.Many2one('event.event', 'Event', required=True)
  222. enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise', required=True)
  223. type_id = fields.Many2one('ecom.ebusiness.type', related="enterprise_id.ebusiness_id.ebusiness_type_id", string='Ebusiness Type', store=True)
  224. country_id = fields.Many2one('ecom.location', related="enterprise_id.ebusiness_id.country_id", string='Country', store=True)
  225. island_id = fields.Many2one('ecom.location', related="enterprise_id.ebusiness_id.island_id", string='Island', store=True)
  226. county_id = fields.Many2one('ecom.location', related="enterprise_id.ebusiness_id.county_id", string='County', store=True)
  227. logo = fields.Binary(string='Logo', related="enterprise_id.logo", track_visibility='onchange', store=True)
  228. enterprise_state = fields.Selection(string='Enterprise State', related='enterprise_id.ebusiness_state', readonly=True, store=True)
  229. reservation_no = fields.Char('Reservation No', size=64, readonly=True)
  230. state = fields.Selection([
  231. ('draft', 'Unconfirmed'), ('cancel', 'Cancelled'),
  232. ('open', 'Confirmed'), ('done', 'Done')],
  233. string='Status', default='draft', readonly=True, copy=False, track_visibility='onchange')
  234. origin = fields.Selection([
  235. ('event', 'Event'), ('registration', 'Registration')],
  236. string='Origin', default='event', readonly=True, copy=False, track_visibility='onchange')
  237. @api.one
  238. def do_draft(self):
  239. self.state = 'draft'
  240. @api.one
  241. def confirm_registration(self):
  242. _logger.info('Sending Email notification on registration confirmation. Event Id: %s'%(self.event_id.id))
  243. #self.send_email_notification('mail_template_etourism_event_confirmation')
  244. self.state = 'open'
  245. @api.one
  246. def button_reg_cancel(self):
  247. _logger.info('Sending Email notification on registration cancellation. Event Id: %s'%(self.event_id.id))
  248. #self.send_email_notification('mail_template_etourism_event_cancellation')
  249. self.state = 'cancel'
  250. def get_event_enterprise_emails(self):
  251. for event in self:
  252. ebusiness_id = event.enterprise_id.ebusiness_id
  253. contact_emails = []
  254. for contact in ebusiness_id.contacts_line:
  255. if contact.send_email:
  256. contact_emails.append(contact.email)
  257. return ', '.join(contact_emails)
  258. @api.multi
  259. def get_current_date(self):
  260. today_dt_str = ''
  261. today_dt = datetime.date.today()
  262. today_dt_str = today_dt.strftime('%d/%m/%Y')
  263. return today_dt_str
  264. @api.model
  265. def create(self, vals):
  266. print "########################### CREATE EVENT ENTERPRISE ###########################"
  267. """
  268. Overrides orm create method.
  269. @param self: The object pointer
  270. @param vals: dictionary of fields value.
  271. """
  272. if not vals:
  273. vals = {}
  274. if self._context is None:
  275. self._context = {}
  276. vals['reservation_no'] = self.env['ir.sequence'].get('event.enterprise')
  277. res = super(EventEnterprise, self).create(vals)
  278. origin = res.origin
  279. if origin == 'registration':
  280. _logger.info('Sending Email notification on event registration. Event Id: %s'%(res.event_id.id))
  281. #res.send_email_notification('mail_template_etourism_event_registration')
  282. return res
  283. @api.multi
  284. def send_email_notification(self, email_template=False):
  285. print "SEND EVENT EMAIL NOTIFICATION:::::::::::::::::::::::::::::::::"
  286. if email_template:
  287. ir_model_data = self.env['ir.model.data']
  288. try:
  289. template_id = ir_model_data.get_object_reference('etourism_event', email_template)[1]
  290. except ValueError:
  291. template_id = False
  292. if template_id:
  293. mail_template = self.env['mail.template']
  294. template_ids = mail_template.browse(template_id)
  295. template_ids.with_context({'ltgt_replace': True, 'enterprise_name': self.enterprise_id.name}).send_mail(self.id, force_send=True)
  296. else:
  297. _logger.error('Email template not found. Template: %s Event Id: %s'%(email_template, self.event_id.id))
  298. return False
  299. class ViewEvents(models.Model):
  300. _name = 'view.events'
  301. _auto = False
  302. _description = "View Events"
  303. id = fields.Integer('Id')
  304. name = fields.Char(string='Site',index=True)
  305. state = fields.Selection([
  306. ('draft', 'Unconfirmed'), ('cancel', 'Cancelled'),
  307. ('confirm', 'Confirmed'), ('done', 'Done')],
  308. string='Status', index=True)
  309. date_begin = fields.Date(string='Start Date', index=True)
  310. date_end = fields.Date(string='End Date', index=True)
  311. featured = fields.Boolean(string='Featured',index=True)
  312. island_id = fields.Many2one('ecom.location', string='Island id',index=True)
  313. county_id = fields.Many2one('ecom.location', string='County id',index=True)
  314. island = fields.Char(string='Island',index=True)
  315. county = fields.Char(string='County',index=True)
  316. def init(self):
  317. cr = self._cr
  318. tools.drop_view_if_exists(cr, 'view_events')
  319. cr.execute("""
  320. CREATE OR REPLACE VIEW view_events AS (
  321. select e.id,e.name,e.state,e.date_begin::DATE,e.date_end::DATE,e.featured,e.island_id,e.county_id
  322. ,l.name as island, l2.name as county
  323. from event_event e, ecom_location l, ecom_location l2
  324. where e.island_id=l.id and e.county_id=l2.id
  325. )""")