示例#1
0
def add_component():
    name = request.form.get('name')

    if not name:
        return jsonify({'success': False})

    p = Project.query.first()

    if len(Component.query.filter(Component.project_id == p.id, Component.name == name).all()) != 0 \
            or len(name) < 3:
        return jsonify({'success': False})

    c = Component(name=name, project_id=p.id)
    db.session.add_all([c])
    db.session.commit()

    return jsonify({'success': True, 'newComp': c.to_json_dict()})
示例#2
0
  def onGetStatus(self,method,payload):
    from django.utils import simplejson
    import logging
    import model
    from model import product_types
    from model.models import Item,Component,ConfigDB
    from model import resource_types
    from model import spreadsheet
    from model import component_states

    status = payload['status']
    order_id = payload['order_id']
    logging.debug('onGetStatus: order_id: %s' % order_id)
    
    result = {'method':method}
    result['content'] = {
                         'status':'settled',
                         'order_id':order_id
                         }
    
    if status == 'placed':
      # just return settled status to Facebook, this may be called twice
      order_details = simplejson.loads(payload['order_details'])
      logging.debug('placed: order_details: %s' % payload['order_details'])
      # check and log here
    elif status == 'settled':
      
      order_details = simplejson.loads(payload['order_details'])
      logging.debug('settled: order_details %s' % payload['order_details'])
      # order_details:{order_id:0,buyer:0,app:0,receiver:0,amount:0,update_time:0,time_placed:0,data:'',items:[{}],status:'placed'}
      buyer = order_details['buyer']
      logging.debug('buyer %s' % buyer)
      order_item = order_details['items'][0]
      data = simplejson.loads(order_item['data'])
      
      logging.debug('data dump: %s' % simplejson.dumps(data))
      logging.debug('order_item dump: %s' % simplejson.dumps(order_item))
      
      type = data['type']
      player = model.getFacebookPlayer(str(buyer))
      
      # must have been resource purchase
      if type == product_types.TOKENS:
        tokens = int(data.get('tokens',0))
        logging.debug('settled %s tokens order for player %s' % (tokens,player.key().name()))
        if getattr(player, 'credits'):
          player.credits += tokens
        else:
          player.credits = tokens
        player.put()
      elif type == product_types.RESOURCES:
        for name in [resource_types.CASH,resource_types.STEEL,resource_types.FUEL]:
          value = data.get(name,0)
          logging.debug('settled resource order for %s %s' % (value,name))
          has = getattr(player, name,0)  
          setattr(player, name, has + value)
        player.put()
      elif type == product_types.SPEED_UPS:
        component = Component.get_by_id(order_item['c_id'])
        logging.debug('settled speed up order for component %s' % component.key().id())
        model.completeBuilding(component)
    else:
      # may be refunded, canceled, log the activity
      result['content']['status'] = status
    return result
示例#3
0
  def onGetItems(self,method,payload):
    """
      Facebook calls this method to get details about an item
    """
    from django.utils import simplejson
    import model
    from math import ceil
    from model.models import Item,Component
    from model import product_types
    from model import resource_types
    from model import component_states
    import datetime
    import logging
    
    result = {'method':method}
    logging.debug('method %s' % method)
    logging.debug(payload['order_info'])
    order_info = simplejson.loads(payload['order_info'])[0]
    logging.debug('order_info %s' % order_info)
    # research component
    # building
    #     we know it's repair if health is < 100%
    #     if it's upgrading if timeLeft = item.buildtime - ( now() - building.created ) <= 0 it has been built
    #     else its constructed
    # unit
    # a component is always only speed up
    # what kind of product is this?
    product_type = order_info['type']
    test = order_info.get('test')
    price = 0
    title = ''
    product_url = self.request.host_url
    image_url = ''
    desc = ''
    product_data = {'type':product_type}
    
    if product_type == product_types.TOKENS:
      from model import math_util
      image_url = self.request.host_url + '/static/tokens.png'
      amount = order_info['amount']
      tokenPacks = [int(s) for s in config.dynamic['tokenPacks'].split(',')]
      if amount not in tokenPacks:
        logging.debug('amount not in tokenPacks')
        return None # can't order less
      
      tokens = amount
      if tokenPacks.index(amount) != 0:
        bonus = config.dynamic['tokenBasePrice'] * amount
        tokens += bonus
      
      title = '%s Air Tokens' % math_util.splitthousands(str(int(tokens)))
      desc = title
      price = int(config.dynamic['tokenBasePrice'] * amount)
      product_data['tokens'] = int(tokens)
      logging.debug('total price of tokens: %s' % price)
    elif product_type == product_types.RESOURCES:
      title = 'Get Resources'
      image_url = self.request.host_url + '/static/resources.png'
      amounts = order_info['resources']
      for type,amt in amounts.iteritems():
        logging.debug('ordered %s of rsrc %s ' % (amt,type))
        if type == resource_types.CASH:
          conversion_rate = config.dynamic['cashCreditRatio']
        elif type == resource_types.FUEL:
          conversion_rate = (amt / config.dynamic['fuelCashRatio']) * config.dynamic['cashCreditRatio']
        elif type == resource_types.STEEL:
          conversion_rate = (amt / config.dynamic['steelCashRatio']) * config.dynamic['cashCreditRatio']
        product_data[type] = amt
        price += int(round(conversion_rate * amt))
      logging.debug('total price of resources: %s' % price)
    elif product_type == product_types.SPEED_UPS:
      c_id = order_info['cId']
      if test:
        logging.debug('is test')
        c_id = self.getTestComponent()
      image_url = self.request.host_url + '/static/speedup.png'
      # get the component Id
      
      logging.debug('cId %s' % c_id)
      component = Component.get_by_id(int(c_id))
      # is the component still constructing?
      is_complete = model.isComponentComplete(component)
      logging.debug('expires %s' % component.expires)
      logging.debug('now %s' % datetime.datetime.now())
      logging.debug('is_complete %s' % is_complete)
      
      if not is_complete:
        time_left = (component.expires - datetime.datetime.now()).seconds * 1000
        logging.debug('time_left %s' % time_left)
        if time_left > config.dynamic['freeSpeedMax']:
          mins_left = time_left/1000/60 # convert milliseconds to minutes
          price = int(ceil(config.dynamic['costPerMinute'] * mins_left))
          
          if component.state == component_states.CONSTRUCT:
            title = 'Finishing Construction'
            desc = "Buy this item"
          elif component.state == component_states.REPAIR:
            title = 'Finish Repair'
            desc = "Buy this item"
          elif component.state == component_states.RESEARCH:
            title = 'Finish Research'
            desc = "Buy this item"
          elif component.state == component_states.UPGRADE:
            title = 'Finish Upgrade'
            desc = "Buy this item"
            
#          price = 5

    product = {
               'item_id':24107,
               'title':title,
               'description':desc,
               'price':int(price * config.dynamic['creditsToDollars']),
               'image_url':image_url,
               'product_url':product_url,
               'data':simplejson.dumps(product_data)
               }
    
    result['content'] = [product]
    return result