Example #1
0
    def share(self):
        id = self.params.get("id")
        if id == None:
            self.render(text="不正なリクエスト")
            return

        self.view = UserView.get_by_id(int(id))
Example #2
0
    def search_refinement(self):
        
        self.view = None
        if self.v_id:
          self.view = UserView.get_by_id(int(self.v_id))

        self.fields = []
        self.width = 33

        i = 1 
        if self.view and self.view.user_db_id.user == self.user:

          configs =  yaml.load(self.view.config)
          for col in configs:
            if col['checked'] == 'checked':
              if 'hidden' not in col:
                col['hidden'] = 'false'
              elif col['hidden'] == '':
                col['hidden'] = 'false'

              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()
                  i = i+1
                  col['items'] = yaml.load(rec.yaml_data)
                  self.fields.append(col)
          m = 100 / i
          if m < self.width:
            self.width = m
        else:
          self.view = None
  def create(self):

    id = self.params.get('shared_view_id')
    view = UserView.get_by_id(int(id))

    config = copy.deepcopy(ShareUser.default_config)

    for col in config:
      key = col['name']
      val = self.params.get(key)
      if val == 'yes':
        col['val']= 'true'
      else:
        col['val']= 'false'

    yaml_data = yaml.dump(config)
    wk = self.params.get('share_users')
    # 改行で分解
    email = ''
    try:
      for e  in wk.split("\n"):
        email = e
        res = {'status':'success'}
        su = ShareUser(share_view_id = view,email = email,config = yaml_data)
        # メールで通知する
        m = NoticeMail()
        m.notice_share(self.request,su)
        su.put()
    except:
        res = {'status':'error','msg':u"%sへの共有に失敗しました" % email}

    self.render(json=self.to_json(res))
Example #4
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))
Example #5
0
    def create(self):
        res = {"status": "success"}
        # try:
        udb = UserDb.get_by_id(int(self.params.get("db_id")))
        if udb:
            v = UserView.newInstance(udb)
            res = {"status": "success", "cv_id": v.key().id(), "r": "/"}
        else:
            res = {"status": "error", "msg": "missing user db"}
        # except Exception, ex:
        #   # 例外メッセージを表示する
        #  res= {"status":"error","msg":"Exception: %s" % ex}

        self.render(json=self.to_json(res))
Example #6
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))
Example #7
0
    def update(self):
        id = self.params.get("edit_view_id")
        name = self.params.get("view_name")

        logging.debug("[ViewController#update] (params)=" + self.to_json(self.params) + ")")

        # build yaml for config
        if not id:
            return

        self.view = UserView.get_by_id(int(self.params.get("edit_view_id")))
        config = yaml.load(self.view.config)

        for col in config:
            if col["type"] == "hidden":
                continue
            if col["name"].startswith("iq_"):
                continue

            key = "disp_%s" % col["name"]
            val = self.params.get(key, "None")

            if val == "yes":
                col["checked"] = "checked"
            else:
                col["checked"] = ""

        self.view.name = name
        self.view.config = yaml.dump(config)
        self.view.put()

        # 問い合わせだったら必須項目が表示されないように削除
        self.config = []
        self.must_config = []
        if self.view.user_db().service_type == "c":
            for c in yaml.load(self.view.config):
                if not c["name"].startswith("iq_"):
                    if c["name"] == "email":
                        self.must_config.append(c)
                    else:
                        self.config.append(c)
                else:
                    if c["name"] != "iq_content":
                        self.must_config.append(c)
            self.render(template="inquiry_update")
Example #8
0
    def edit(self):
        self.view = UserView.get_by_id(int(self.params.get("id")))

        self.config = []
        self.must_config = []
        if self.view.user_db().service_type == "c":
            for c in yaml.load(self.view.config):
                if not c["name"].startswith("iq_"):
                    if c["name"] == "email":
                        self.must_config.append(c)
                    else:
                        if c["form"] == "option":
                            self.config.append(c)
                else:
                    if c["name"] != "iq_content":
                        self.must_config.append(c)

            self.render(template="inquiry_edit")
Example #9
0
    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))
Example #10
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")
Example #11
0
    def shared_member_list(self):
      #自分のDBをとりだす
      dbs = UserDb.all()
      dbs.filter('user ='******'user_db_id = ',db) 
        for v in views:
          # shareしているユーザの取得
          share_users = ShareUser.all()
          share_users.filter(' share_view_id = ',v)
          for su in share_users:
            if su.email in  members:
              members[su.email].append(su)
            else:
              members[su.email]=[su]

          self.member_list = []
          for m in members.keys():
            self.member_list.append({'email':m,'share_views':members[m]})
Example #12
0
    def new(self):
      self.action_url = "/profile/create"
      #id = self.params.get('id')
      id = self.v_id
      self.fields = []
      if id:
        self.view = UserView.get_by_id(int(id))
        self.config = yaml.load(self.view.config)
        data = ProfileCore(user_db_id=self.view.user_db_id,user=self.user,status="active",sex="0")
        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 col['type'] == 'radio' and item['code'] == col['val']:
                     item['checked'] = 'checked'

                 col['items'] = yaml.load(rec.yaml_data)
            self.fields.append(col)
        self.dump = yaml.dump(self.fields)
Example #13
0
    def create(self):
      data = {'status':'success'}
      if self.request.method.upper() != "POST":
        data = {'status':'error','msg':'forbidden method '}
        self.render(json=self.to_json(data))
        return

      udb = UserDb(user=self.user,service_type=self.params.get('service_type','p'))

      udb.put()
      id = udb.key().id()
      name = u'DB(' + str(id) + ')'
      if udb.service_type == 'c':
        name = u'問い合せDB(' + str(id) + ')'
        udb.config = yaml.dump({'recipients':udb.user.email(),'form_config':UserDbMaster.getFormConfig()})
      udb.name = name
      udb.put()

      # ついでにビューもつくってしまう
      v = UserView.newInstance(udb)
      # カレントのビューをこれにするためにクッキーにセット
      data={'status':'success','r':'/','cv_id':str(v.key().id())}

      self.render(json=self.to_json(data))
Example #14
0
    def index(self):
        v_id = None
        if "cv_id" in self.cookies:
            v_id = self.cookies["cv_id"]

        self.colModels = []
        self.searchitems = []
        if v_id:
            self.view = UserView.get_by_id(int(v_id))
            if self.view == None:
                self.response.headers.add_header("Set-Cookie", "cv_id=-1 ;expires=Fri, 5-Oct-1979 08:10:00 GMT")

            self.fields = []

            self.width = 33
            i = 1
            # if self.view and self.view.user_db_id.user == self.user:
            if self.view:
                self.auth = {"w": True, "d": True, "dl": True}
                if self.view.user_db_id.user != self.user:
                    # 共有ビュー?
                    v = db.GqlQuery(
                        "SELECT * FROM ShareUser WHERE email = :1 and share_view_id = :2", self.user.email(), self.view
                    ).get()
                    if v:
                        # 権限の設定
                        config = yaml.load(v.config)
                        for item in config:
                            self.auth[item["name"]] = item["val"]
                    else:
                        self.view = None
                        return

                self.colModels.append(
                    {
                        "display": "ID",
                        "name": "id",
                        "width": "40",
                        "align": "center",
                        "hidden": "false",
                        "sortable": "true",
                    }
                )

                configs = yaml.load(self.view.config)
                names = []
                for col in configs:

                    if col["search_refinement"] and col["checked"] == "checked":
                        result = db.GqlQuery("SELECT * FROM UserDbMaster WHERE name = :1", col["name"])
                        if result.count() > 0:
                            rec = result.get()
                            i = i + 1
                            col["items"] = yaml.load(rec.yaml_data)
                            self.fields.append(col)
                            names.append("#sr_" + col["name"])

                    if col["name"].startswith("iq_") and col["checked"] == "checked":
                        self.colModels.append(
                            {
                                "display": col["label"],
                                "name": col["name"],
                                "width": col["width"],
                                "align": col["align"],
                                "hidden": col["hidden"],
                                "sortable": "false",
                            }
                        )
                        continue
                    if col["name"] == "email":
                        self.colModels.append(
                            {
                                "display": col["label"],
                                "name": col["name"],
                                "width": col["width"],
                                "align": col["align"],
                                "hidden": col["hidden"],
                                "sortable": "false",
                            }
                        )
                        self.searchitems.append({"display": col["label"], "name": col["name"]})
                        continue

                    if col["checked"] == "checked":
                        if "hidden" not in col:
                            col["hidden"] = "false"
                        elif col["hidden"] == "":
                            col["hidden"] = "false"

                        self.colModels.append(
                            {
                                "display": col["label"],
                                "name": col["name"],
                                "width": col["width"],
                                "align": col["align"],
                                "hidden": col["hidden"],
                                "sortable": "false",
                            }
                        )
                        if col["type"] != "radio" and col["type"] != "select":
                            if col["name"].startswith("iq_"):
                                # "iq_{name} => {name}
                                name = col["name"][3:]
                                if isinstance(getattr(Inquiry, name), db.StringProperty):
                                    self.searchitems.append({"display": col["label"], "name": col["name"]})
                            else:
                                if isinstance(getattr(ProfileCore, col["name"]), db.StringProperty):
                                    self.searchitems.append({"display": col["label"], "name": col["name"]})

                self.fields_join = ",".join(names)
                self.colModelsJson = self.to_json(self.colModels)
                m = 100 / i
                if m < self.width:
                    self.width = m

            else:
                self.view = None
                self.colModelsJson = None
Example #15
0
 def delete(self):
     res = {"status": "success", "reload": "true"}
     # logging.debug('deleting view(' + self.params.get('id') + ')')
     v = UserView.get_by_id(int(self.params.get("id")))
     v.delete()
     self.render(json=self.to_json(res))
Example #16
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))
Example #17
0
    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"))
Example #18
0
    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