コード例 #1
0
    def create(self):
      view_id = self.params.get('user_view_id')
      view = UserView.get_by_id(int(view_id))

      config = yaml.load(view.config)
      rec = ProfileCore(user_db_id=view.user_db_id,user=users.get_current_user())
      for col in config:
        if col['checked'] == 'checked':
          val = self.params.get(col['name'])
          if val:
            setattr(rec,col['name'],val)

      rec.put()
      data = {'status':'success','flexReload':'true'}
      self.render(json=self.to_json(data))
コード例 #2
0
    def delete(self):
      user=users.get_current_user()
      items = self.params.get('items')
      # split by ','
      msg = {'status':'success'}
      for id in items.split(','):
          if id != None and id != '':
            data = ProfileCore().get_by_id(int(id))
            #data = db.GqlQuery("SELECT * FROM ProfileCore WHERE  user = :1 and id = :2",user,int(id)).get()
            if data and data.user == user:
              data.delete()
            else:
              msg = {'status':'error','msg':'不正な操作です(' + str(data) + ')'}

      self.render(json=self.to_json(msg))
コード例 #3
0
    def update(self):
      id = self.params.get('profile_id')
      v  = self.params.get('user_view_id')
      view = UserView.get_by_id(int(v))

      rec = ProfileCore.get_by_id(int(id))
      #データの所有者が違う場合は共有利用しているデータベースかチェック
      #もでるに隠蔽するべきか。
      # あと、本当に権限があるかShareUser.config を取得してチェックすべき!
      editable = False
      if rec.user != self.user and rec.user_db_id.user != self.user:
       sv = db.GqlQuery("SELECT * FROM ShareUser WHERE email = :1 and share_view_id = :2",self.user.email(), view).get()
       if sv:
         if rec.user_db_id.key() == sv.share_view_id.user_db_id.key():
           editable = True
      else:
           editable = True

      if editable:
        config = yaml.load(view.config)
        for col in config:
          if col['checked'] == 'checked':
            val = self.params.get(col['name'])
            if val and val != '':
              setattr(rec,col['name'],val)
        rec.put()
      data = {'status':'success','flexReload':'true'}
      self.render(json=self.to_json(data))
コード例 #4
0
    def reset_post_at(self):
      for p in ProfileCore.all():
        if p.post_at == None:
          p.post_at = datetime.datetime.now()
          p.put()
        else:
          if isinstance(p.post_at,db.DateTimeProperty) != True:
            p.post_at = datetime.datetime.now()
            p.put()

      self.render(text="done")
コード例 #5
0
ファイル: groups.py プロジェクト: take467/estate-proto-on-gae
    def delete(self):
      if self.request.method.upper() != "POST":
        return 

      id = self.params.get('id')
      g = UserDb.get_by_id(int(id))

      if g.user != self.user:
        data = {'status':'error','msg':'権限がありません'}
        self.render(json=self.to_json(data))
        return

      data = {'status':'success'}
      if g:

        # 紐づくデータは、リンク関係を切るー>ゴミ箱をつくってそこに入れる
        # という仕様は面倒なのでまずは削除してしまう
        q = ProfileCore.all()
        q.filter("user_db_id = ",g)
        for p in q:
          p.delete()
          #p.user_db_id = None
          #p.put()

        q = Inquiry.all()
        q.filter("user_db_id = ",g)
        for p in q:
          p.delete()
          #p.user_db_id = None
          #p.put()

        # 紐づくViewを全て削除
        q = UserView.all()
        q.filter("user_db_id = ",g)
        for p in q:
          p.delete()

        g.delete()
        data = {'status':'success','r':'/'}

        if self.v_id and id == self.v_id:
  	  self.response.headers.add_header('Set-Cookie','cv_id=-1 ;expires=Fri, 5-Oct-1979 08:10:00 GMT')

      self.render(json=self.to_json(data))
コード例 #6
0
    def edit(self):
      self.action_url = "/profile/update"
      id = self.params.get('id')
      v  = self.params.get('v')
      self.fields = []
      if id:
        self.profile_id = id
        self.view = UserView.get_by_id(int(v))
        data = ProfileCore.get_by_id(int(id))


        #データの所有者が違う場合は共有利用しているデータベースかチェック
        editable = False
        if data.user != self.user and data.user_db_id.user != self.user:
         sv = db.GqlQuery("SELECT * FROM ShareUser WHERE email = :1 and share_view_id = :2",self.user.email(), self.view).get()
         if sv:
           #self.dump2=[data.user_db_id.key().id(),sv.share_view_id.user_db_id.key().id()]
           if data.user_db_id.key() == sv.share_view_id.user_db_id.key():
             editable = True
        else:
             editable = True

        if editable:
          self.config = yaml.load(self.view.config)
          for col in self.config:
            if col['checked'] == 'checked':
              col['val'] = getattr(data,col['name'])
              if col['type'] == 'radio' or col['type'] == 'select':
                 result = db.GqlQuery("SELECT * FROM UserDbMaster WHERE name = :1",col['name'])
                 if result.count() > 0: 
                   rec = result.get()
                   items = yaml.load(rec.yaml_data)
                   for item in items:
                     if item['code'] == col['val']:
                       if col['type'] == 'radio':
                         item['checked'] = 'checked'
                       elif col['type'] == 'select':
                         item['selected'] = 'selected'
                   col['items'] = items
           
              self.fields.append(col)
        self.dump = yaml.dump(self.fields)
        self.render(template="new")
コード例 #7
0
    def json(self):
      #id = self.params.get('id')
      #retrive from cookie
      id = self.cookies['cv_id']

      if id == None:
        self.render(json=self.to_json([]))
        return

      self.fields = []
      self.view = UserView.get_by_id(int(id))
      if self.view == None:
        self.render(json=self.to_json([]))
        return

      # ビューの所有者とカレントのユーザが同じでなければ共有されたビュー
      user = self.user
      if self.view.user_db_id.user != self.user:
         sv = db.GqlQuery("SELECT * FROM ShareUser WHERE email = :1 and share_view_id = :2",self.user.email(), self.view).get()
         if sv:
           user = sv.share_view_id.user_db_id.user

      self.config = yaml.load(self.view.config)

      query = self.params.get("query")
      qtype = self.params.get("qtype")

      sortname = self.params.get("sortname")
      if sortname == None or sortname == '':
        sortname = 'id'
      sortorder = self.params.get("sortorder")

      lines = int(self.params.get("rp"))
      page = int(self.params.get("page"))
      offset = (page - 1) * lines

      # 絞り込み項目が選択されていれば追加
      add_filters =[]
      if self.view:
        configs =  yaml.load(self.view.config)
        for col in configs:
          if col['checked'] == 'checked':
            if col['type'] == 'radio' or col['type'] == 'select':
              if isinstance(getattr(ProfileCore,col['name']),db.StringProperty):
                 val = self.params.get(col['name'])
                 if val != None and val != '':
                   add_filters.append({'name':col['name'],'val':val})

      results = []
      if (query != None and query != '' ) and ( qtype != None and qtype != ''):
        if qtype == 'id':
          p = None
          try:
            p  = ProfileCore.get_by_id(int(query))
          except:
            pass
          total = 0
          if p != None and (p.user == user):
            total = 1
            results.append(p)
        else:
          p = ProfileCore.all()
          p.filter(" user_db_id = ",self.view.user_db_id)
          #p.filter(" user = "******" = ",query)
          for f in add_filters:
            p.filter(f['name'] + " = ",f['val'])

          results=p.fetch(lines,offset)
          total = p.count()
      else:
        p = ProfileCore.all()
        p.filter(" user_db_id = ",self.view.user_db_id)
        #p.filter(" user = "******" = ",f['val'])
        is_id_sort = False
        if sortname != 'id' and sortname != '-id' :
          if sortorder.upper() == 'DESC':
            sortname = '-' + sortname
          p.order(sortname)
        else:
          is_id_sort = True

        results = p.fetch(lines,offset)
        total=p.count()
        if is_id_sort and (sortorder != None and sortorder.upper() == 'DESC'):
          results.reverse()

      rows = []
      for rec in results:
        wk = {'id':rec.key().id(),"cell":[rec.key().id()]}
        for col in self.config:
          if col['checked'] == 'checked':
            val = getattr(rec,col['name'])
            if col['type'] == 'radio' or col['type'] == 'select':
              udm = db.GqlQuery("SELECT  * FROM UserDbMaster WHERE name = :1",col['name']).get()
              for item in yaml.load(udm.yaml_data):
                if item['code'] == val:
                  val = item['name']
            if isinstance(getattr(ProfileCore,col['name']),db.DateTimeProperty):
              wk2 = val + datetime.timedelta(hours=9)
              if 'format' in col:
                val = wk2.strftime(col['format'])
              else:
                val = wk2.strftime('%Y/%m/%d %H:%M:%S')
                 
            wk['cell'].append(val)

        rows.append(wk)

      data = {'page':page, 'total': total, 'rows': rows }
      self.render(json=self.to_json(data))
コード例 #8
0
ファイル: groups.py プロジェクト: take467/estate-proto-on-gae
    def import_csv(self):
      if self.request.method.upper() == "GET":
        pass

      if self.request.method.upper() == "POST":
        data={'status':'success','msg':'アップロードが完了しました','r':'/'}
        if not self.user:
          self.render(json=self.to_json({'status':'error','msg':'不正なリクエスト'}))
          return

        # いったんワークエリアにデータをコピー
        bin = self.params.get('file')
        if not bin:
          self.render(json=self.to_json({'status':'error','msg':'ファイルを指定してください'}))
          return

        fname =  self.request.body_file.vars['file'].filename
        udb = UserDb(user=self.user,name=unicode(fname,self.__guess_charset(fname)))
        udb.put()

        # ついでにビューもつくってしまう (viewのカラムのcheckedを一反外す)
        v = UserView(user_db_id = udb)
        v.put()
        # カレントのビューをこれにするためにcv_idをセット
        data['cv_id']=str(v.key().id())

        # viewのカラムのcheckedを一反外し、csvにあるカラムのみ有効にする
        config = copy.deepcopy(ProfileCore.disp_columns)
        for col in config:
          if col['type'] != 'hidden':
            col['checked'] = ''

        #try:
        lines = []
        colinfo = None
        for line in bin.splitlines():
          if line[0] == '#' or line[0:2] == '"#':
            continue

          # カラム情報の取得
          if not colinfo:
            for row in csv.reader(line):
              for e in row:
                if colinfo == None:
                  colinfo = []
                colinfo.append(e)
                # カラムにcheckedをいれる
                for col in config:
                  if col['name'] == e:
                     col['checked'] = 'checked'
                     break

            #data['msg'] = '|'.join(colinfo) 
            v.config = yaml.dump(config)
            v.put()
          else:
            rec = ProfileCore(user_db_id=udb,user=self.user)
            rec.put()
            cols = copy.deepcopy(colinfo)
            wk = []
            for row in csv.reader(line):
              for e in row:
                name = cols.pop(0)
                if name:
                  setattr(rec,name,unicode(e,self.__guess_charset(e)))
                  #wk.append("(%s,%s)" % (name,e))

            #data['msg'] = '|'.join(wk) 
            rec.put()

        #except Exception, ex:
        #  data = {'status':'error','msg':'ファイルの読み込みに失敗しました'}
         
        self.render(json=self.to_json(data))

        pass
コード例 #9
0
ファイル: view.py プロジェクト: take467/estate-proto-on-gae
    def export(self):
        id = self.params.get("id")
        if id == None:
            self.render(text="不正なリクエスト")
            return

        view = UserView.get_by_id(int(id))

        # 所有者 or 権限のあるユーザかチェック
        canDL = False
        if self.user == view.user_db_id.user:
            canDL = True
        else:
            results = db.GqlQuery("SELECT * FROM ShareUser WHERE email = :1", self.user.email())
            # results = ShareUser.all()
            for rec in results:
                if rec.share_view_id.key().id() == view.key().id():
                    if rec.isDownloadable():
                        canDL = True
                        break

        if not canDL:
            self.render(text="不正なリクエスト(permission denied)")
            return

        results = ProfileCore.all().filter(" user_db_id =", view.user_db_id)
        config = yaml.load(view.config)

        # CSVのヘッダ情報
        line = []
        for col in config:
            if col["checked"] == "checked":
                # line.append('"' + col['label']+'"')
                line.append('"' + self.__conv(col["label"], "cp932") + '"')
        header = ",".join(line) + "\r\n"

        self.skip_rendering()
        res = self.getResponse()
        res.headers["Content-Type"] = "application/x-csv;charset:Shift_JIS"
        # res.headers['Content-Type'] = "application/octet-stream"
        if self.params.get("ie", "false") == "true":
            res.headers["Content-Disposition"] = "attachment; filename=" + self.params.get("filename") + ".csv"

        # res.out.write(header.encode('cp932'))
        res.out.write(header)

        for rec in results:
            line = []
            for col in config:
                if col["checked"] == "checked":
                    val = getattr(rec, col["name"])
                    # if col['type'] == 'radio' or col['type'] == 'select':
                    #  udm = db.GqlQuery("SELECT  * FROM UserDbMaster WHERE name = :1",col['name']).get()
                    #  for item in yaml.load(udm.yaml_data):
                    #    if item['code'] == val:
                    #      val = item['name']
                    if isinstance(getattr(ProfileCore, col["name"]), db.DateTimeProperty):
                        wk2 = val + datetime.timedelta(hours=9)
                        if "format" in col:
                            val = wk2.strftime(col["format"])
                        else:
                            val = wk2.strftime("%Y/%m/%d %H:%M:%S")
                    line.append('"' + val.replace('"', '""') + '"')
            wk = ",".join(line) + "\r\n"
            res.out.write(wk.encode("cp932"))