Ejemplo n.º 1
0
def getMessage2(msgidx, readStamp=True):
	""" 쪽지를 읽어온다 """
	
	msg_q = Session.query(Msg).filter(Msg.idx == msgidx).first()
	if None == msg_q:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")

	outText = msg_q.Content
  
	# 첨부파일 가져오기
	msgAttach_q = Session.query(MsgAttach).filter_by(Msg_IDX = msg_q.idx).all()

	attach_text = []

	if len(msgAttach_q) > 0:
		attach_text.append("<table class=\"filedownBox\">")
		attach_text.append(u"<tr><td rowspan=\"%d\">첨부</td><td>" % len(msgAttach_q))

		for attach_item in msgAttach_q:
			attach_text.append("<a href=\"/getfile/nmessage/%d\">%s</a><br />" % (attach_item.idx, attach_item.OriginalFileName) )

		attach_text.append("</td></tr></table>")

	attach_text = "".join(attach_text)

	return "<p>%s</p>%s" % (outText, attach_text)
Ejemplo n.º 2
0
Archivo: base.py Proyecto: onetera/sp
	def __call__(self, environ, start_response):
		""" Invoke the Controller """
		
		# WSGIController.__call__ dispatches to the Controller method the request is routed to. 
		# This routing information is available in environ['pylons.routes_dict']
		
		try:
			return WSGIController.__call__(self, environ, start_response)
		finally:
			Session.remove()
Ejemplo n.º 3
0
def init_model( engine ):
	"""Call me before using any of the tables or classes in the model"""

	logging.getLogger(__name__).debug("CALL: init_model")

	Session.configure( bind=engine )
	Base.metadata.bind = engine
	Base.metadata.reflect( bind=engine )

	# 쿼리까지 로그 남길때 사용 (개발용)	
	Base.metadata.bind.echo = False
Ejemplo n.º 4
0
Archivo: take.py Proyecto: onetera/sp
    def delete(self, id="json"):
        # 필수 입력 인자
        client_request_key = request.params.keys()

        # 태이크 고유 번호
        if "takeNo" not in client_request_key:
            response.status_int = 403
            return "Required variable Not Exists - takeNo"

        takeNo = request.params["takeNo"]

        # Take Attr Delete
        take_attr_sql = "delete from Take_Attr where ParentIDX = %d" % int(takeNo)
        Session.execute(take_attr_sql)

        Session.commit()

        # Take Delete
        take_sql = "delete from Take where IDX = %d" % int(takeNo)
        Session.execute(take_sql)

        Session.commit()

        if "json" == id:
            return '{"success": true}'
        else:
            return "<success>true</success>"
Ejemplo n.º 5
0
	def unit_remove(self):
		unit_idx = request.params["idx"]
		print unit_idx
		
		if unit_idx != None:
			query = Session.query(Task_Unit).filter(Task_Unit.idx == unit_idx)
			
			fetchrow = query.first()
			
			Session.delete(fetchrow)
			Session.commit()
			
			return "{success: true}"
		else:
			return "{success: false, errorMessage: \"none data\"}"
Ejemplo n.º 6
0
	def unit_write(self):
		if ("unit_idx" in request.params) and (request.params["unit_idx"] != ""):
			query = Session.query(Task_Unit).filter(Task_Unit.idx == request.params["unit_idx"])
			unit_record = query.first()
		else:
			unit_record = Task_Unit()
		
		unit_record.unit_name = request.params["unit_name"]
		# todo: unit_desc
		unit_record.unit_kind = ",".join(request.params.getall("usedTask"))
		
		Session.add(unit_record)
		Session.commit()
		
		return "{success: true}"
Ejemplo n.º 7
0
Archivo: board.py Proyecto: onetera/sp
	def remove(self, id, id2):
		# [SH] -------------------------------
		board_attach_q = Session.query(BoardAttach)
		board_attach = board_attach_q.filter_by(article_idx = id2).all()
		
		# 파일이 있을때만 삭제하도록 변경
		for attach_item in board_attach:
			if os.path.exists(attach_item.new_path):
				os.unlink(attach_item.new_path)
				Session.delete(attach_item)
		
		Session.commit()
		# ---------------------- [SH] 
		Archive("Board").Remove( id2 )
		return okMessage("삭제되었습니다.")
Ejemplo n.º 8
0
def setMsgReceiver(receivers, msg_id, receiver_type):
	for receiver in receivers:
		msg_receiver = MsgReceiver()
		msg_receiver.Msg_IDX = msg_id
		msg_receiver.ReceiverType = unicode(receiver_type)
		if type(receiver) == dict and receiver.has_key("Name"):
			msg_receiver.ReceiverID = unicode(receiver["UserID"])
			msg_receiver.ReceiverName = unicode(receiver["Name"])
		else:
			msg_receiver.ReceiverID = receiver
			msg_receiver.ReceiverName = ""
		msg_receiver.IsRead = unicode(0)
		
		Session.add(msg_receiver)
	Session.commit()
Ejemplo n.º 9
0
	def list(self, id="json"):
		department_q = Session.query(
				mUser_Team.Code.label("deptNo"),
				mUser_Team.Name.label("deptName")
			)
		
		return Response(department_q, id)
Ejemplo n.º 10
0
	def listCode(self, id="json"):
		project_q = Session.query(
				mProject.IDX.label("projectNo"),
				mProject.Code.label("projectCode")
			)
		
		return Response(project_q, id)
Ejemplo n.º 11
0
def removeMessage(msgidx):
	
	msg_receiver_q = Session.query(MsgReceiver).filter_by(idx = msgidx).first()
	
	if None == msg_receiver_q:
		raise SpartaUserError("존재하지 않는 쪽지입니다")

	# 로그인한 사용자가 메시지를 받은 사용자가 아닌 경우 삭제할 수 없다는 메시지를 출력하게 한다.
	if msg_receiver_q.ReceiverID != Login.getID() and (not CheckAdmin()):
		raise SpartaAccessError("메시지를 삭제할 수 있는 권한이 없습니다")

	msg_receiver_q.IsDelete = u"1"

	Session.commit()

	# 항상 1을 반환한다.
	return 1
Ejemplo n.º 12
0
	def available_task(self):
		query = Session.query(
			Task_Type.Code.label("task")
		).order_by("task")
		
		ext = ExtGridStore(query)
		
		return ext.buildStore()
Ejemplo n.º 13
0
	def nmessage(self, id):
		import paste.fileapp
		import urllib

		attach_q = Session.query(MsgAttach).filter(MsgAttach.idx == id)
		if attach_q.count() > 0:
			attach = attach_q.first()
			receiver_q = Session.query(MsgReceiver).filter(MsgReceiver.Msg_IDX == attach.Msg_IDX).filter(MsgReceiver.ReceiverID == sv.Login.getID())
			if receiver_q.count() == 0:
				return "첨부를 열어볼 권한이 없습니다"

			if not os.path.exists(attach.NewFileName):
				return "해당 파일이 서버에 존재하지 않습니다"

			fapp = paste.fileapp.FileApp(attach.NewFileName, **{"content-disposition": 'attachment; filename="%s"' % attach.OriginalFileName.encode("utf-8")})
			return fapp(request.environ, self.start_response)

		return "access failed to attachments"
Ejemplo n.º 14
0
	def listup_unit(self):
		query = Session.query(
			Task_Unit.idx.label("Task_Unit_idx"),
			Task_Unit.unit_name.label("Task_Unit_Name"),
			Task_Unit.unit_kind.label("Task_Unit_Kind")
		).order_by("Task_Unit_Name")
		
		ext = ExtGridStore(query)
		
		return ext.buildStore()
Ejemplo n.º 15
0
def ExistsCode(TblName, Code):
    task_stat = Session.query("Code").from_statement(
        "select Code from " + TblName + " where Code = :code"
    ).params(code = Code)
            
    first_record = task_stat.first()
    if None == first_record:
        return False
    else:
        return True
Ejemplo n.º 16
0
Archivo: board.py Proyecto: onetera/sp
	def getArticleAttach(self, id):
		# 첨부파일 데이터 가져오기
		attach_q = Session.query(BoardAttach)
		attach = attach_q.filter_by(article_idx=id).all()
		
		# { boxLabel: 'Item 1', name:'cb-col-1' },
		attachItem = list()
		
		for row in attach:
			attachItem.append({ "boxLabel": "%s(%s)" % (row.org_path, row.filesize), "name" : "delete_file", "inputValue" : row.id})
		
		return json.dumps(attachItem)
Ejemplo n.º 17
0
def getMessage(msgReceiver_idx, readStamp=True):
	""" 쪽지를 읽어온다 """

	msgReceiver_q = Session.query(MsgReceiver).outerjoin(Msg).add_entity(Msg)

	msg = msgReceiver_q.filter(MsgReceiver.idx == msgReceiver_idx).first()

	if None == msg:
		raise SpartaUserError("존재하지 않는 쪽지입니다")

	# 로그인 중인 사용자와 메시지를 받은 사용자 ID를 비교하여 일치하지 않으면 권한 오류를 발생시킨다.
	if Login.getID() != msg[0].ReceiverID:
		raise SpartaUserError("메시지를 볼 수 있는 권한이 없습니다")
   
	# 읽음여부 수정
	if u"0" == msg[0].IsRead:
		msg[0].IsRead = u"1"

	Session.commit()

	outText = msg[1].Content

	# 첨부파일 가져오기
	msgAttach_q = Session.query(MsgAttach).filter_by(Msg_IDX = msg[1].idx).all()

	attach_text = []

	if len(msgAttach_q) > 0:
		attach_text.append("<table class=\"filedownBox\">")
		attach_text.append(u"<tr><td rowspan=\"%d\">첨부</td><td>" % len(msgAttach_q))

		for attach_item in msgAttach_q:
			attach_text.append("<a href=\"/getfile/nmessage/%d\">%s</a><br />" % (attach_item.idx, attach_item.OriginalFileName) )

		attach_text.append("</td></tr></table>")

	attach_text = "".join(attach_text)

	return "<p>%s</p>%s" % (outText, attach_text)
Ejemplo n.º 18
0
def getReceiverExt(msg_idx, receiver_type):
	msg_receiver_q = Session.query(MsgReceiver).filter(MsgReceiver.Msg_IDX == msg_idx).filter(MsgReceiver.ReceiverType == receiver_type).all()

	receiver_list = []

	for person in msg_receiver_q:
		cssIsRead = ""
		if u"1" == person.IsRead:
			cssIsRead = " style=\"color: red;\""
			
		receiver_list.append("<span%s>\"%s\" &lt;%s&gt;</span>" % (cssIsRead, person.ReceiverName, person.ReceiverID))

	return ", ".join(receiver_list)
Ejemplo n.º 19
0
	def inbox_listup(self, id=None):
		try:
			msg_q = Session.query(MsgReceiver).outerjoin(Msg).add_entity(Msg).filter(
				MsgReceiver.ReceiverID == session["UserID"]
			).filter(MsgReceiver.IsDelete == u"0").order_by(desc(Msg.CreateDate))
		
			objJson = extJson(msg_q)
			objJson.setColumns(("MsgReceiver.idx", "Msg.SenderID", "Msg.SenderName", "Msg.Subject", "MsgReceiver.IsRead", "Msg.CreateDate"))
			objJson.setOrder_by("Msg_CreateDate DESC")

			return objJson.export()
		except Exception as err:
			traceback.print_exc(file=sys.stdout)
			return errMessage( "쪽지함 조회중 오류가 발생하였습니다 \n\n"+str(err) )
Ejemplo n.º 20
0
	def unit_load(self):
		unit_idx = request.params["idx"]
		
		if unit_idx != None:
			query = Session.query(
				Task_Unit.idx.label("unit_idx"),
				Task_Unit.unit_name.label("unit_name")
				# Task_Unit.unit_desc.label("unit_desc")
			).filter(Task_Unit.idx == unit_idx)
			
			ext = ExtDataLoadStore(query)
			
			return ext.buildStore()
		return "{success: false, errorMessage: \"None Data\"}"
Ejemplo n.º 21
0
	def board(self, id):
		import paste.fileapp
		import urllib
		
		attach_q = Session.query(BoardAttach).filter(BoardAttach.id == id)
		if attach_q.count() > 0:
			attach = attach_q.first()
				
			if (attach):
				if not os.path.exists(attach.new_path):
					return "해당 파일이 서버에 존재하지 않습니다 "
			
				fapp = paste.fileapp.FileApp(attach.new_path, **{"Content-Type":"application/download","content-disposition": 'attachment; filename="%s"' % attach.org_path.encode("utf-8")})
				return fapp(request.environ, self.start_response)
		return
Ejemplo n.º 22
0
	def unit_usedtask_load(self):
		unit_idx = request.params["idx"]
		
		if unit_idx != None:
			query = Session.query(
				Task_Unit.unit_kind.label("unit_kind")
			).filter(Task_Unit.idx == unit_idx)
			
			fetchrow = query.first()
			used_task_lst = fetchrow[0].split(",")
			
			ext = ExtArrayLoadStore(used_task_lst)
			
			return ext.buildStore()
		return "[]"
Ejemplo n.º 23
0
	def list(self, id="json"):
		
		project_q = Session.query(
				mProject.IDX.label("projectNo"),
				mProject.Name.label("projectName")
			)
		
		# base_columns
		#base_columns = getattr(project_q.statement.columns, "projectNo").base_columns
		#base_columns = project_q.statement.columns["projectNo"].base_columns
		#column = base_columns.pop()
		#print column.name, column.table.name
		
		#assert 1 == 2
		
		return Response(project_q, id)
Ejemplo n.º 24
0
	def getMsgHeader(self, id=None, id2="yes"):
		try:
			if "no" == id2:
				# 받은 쪽지함에서 이 메소드를 호출하기 때문에 id 값은 덮어 씌워져야 한다.
				q = Session.query(MsgReceiver).filter(MsgReceiver.idx == id).first()
				id = q.Msg_IDX

			sfReceiverTo = sv.nMessage.getReceiverExt(id, u"0")
			sfReceiverCc = sv.nMessage.getReceiverExt(id, u"1")
			sfReceiverBcc = sv.nMessage.getReceiverExt(id, u"2")

			sfReceiver = u"<br />받는사람: %s" % sfReceiverTo
			if len(sfReceiverCc) != 0:
				sfReceiver += u"<br />참조: %s" % sfReceiverCc
			if "no" != id2 and len(sfReceiverBcc) != 0:
				sfReceiver += u"<br />숨은 참조: %s" % sfReceiverBcc

		except Exception as err:
			traceback.print_exc(file=sys.stdout)
			return errMessage("쪽지 수신자 조회에 실패했습니다")

		return sfReceiver
Ejemplo n.º 25
0
def removeSendMessage(sendidx):

	# 메시지 정보를 가져온다.
	msg_q = Session.query(Msg).filter(Msg.idx == sendidx)
	if msg_q.count() == 0:
		raise SpartaUserError("존재하지 않는 쪽지입니다")

	msg = msg_q.first()

	if msg.SenderID != Login.getID() and (not CheckAdmin()):
		raise SpartaAccessError("메시지를 삭제할 수 있는 권한이 없습니다") 

	# 수신자 지우기
	receiver_q = Session.query(MsgReceiver).filter(MsgReceiver.Msg_IDX == sendidx)
	if receiver_q.count() > 0:
		# 수신자중에 한명이라도 메시지를 읽지 않았다면 쪽지를 삭제하지 못하게 한다.
		for receiver_user in receiver_q.all():
			if receiver_user.IsDelete == u"0":
				return u"%s 사용자가 아직 쪽지를 읽지 않았습니다" % receiver_user.ReceiverID
		
		receiver_q.delete()
		Session.commit()

	# 우선 첨부파일 정보를 가져온다.
	attach_q = Session.query(MsgAttach).filter(MsgAttach.Msg_IDX == sendidx).all()
	if len(attach_q) > 0:
		for attach_info in attach_q:
			# File Exists
			if os.path.exists(attach_info.NewFileName):
				os.unlink(attach_info.NewFileName)
		Session.delete(attach_info)
		Session.commit()

	# 본 메시지 삭제
	msg_q = Session.delete(msg)
	Session.commit()
	
	return 1
Ejemplo n.º 26
0
Archivo: board.py Proyecto: onetera/sp
	def write(self, id, id2=None):
		""" 게시물 작성 처리 """
		
		dSave = {}
		bData = Archive("AdminBoard").getValues("AdminBoard.BCode == "+str(id), "IDX,AccessWrite" )
		
		if bData:
			if bData["AccessWrite"] == "" or bData["AccessWrite"].find(session["UserType"]) > -1:
				
				CopyDict( srcDic=request.params, destDic=dSave, keyList="IDX,Category,Status")#, prefix="Board.")
				
				dSave["BoardID"] = str(id)
				dSave["BoardIDX"] = bData["IDX"]
				dSave["Title"] = request.params["Title"]
				dSave["Content"] = request.params["Content"]
				
# [SH] 이 아래줄 부터 쭈욱 
				article_id = Archive("Board").New( **dSave )
				
				# File Upload
				objUpload = Upload()
				objUpload.BoardDir(dSave["BoardID"])
				upload_files = request.params.getall("bf_file")
				
				# 업로드한 파일 목록 가져오기(수정 모드일때)
				if dSave.has_key("IDX"):
					
					# File Delete
					selDeletedCheck = request.params.getall("delete_file")
					
					from sqlalchemy import and_
					
					board_attach_q = Session.query(BoardAttach)
					board_attach = board_attach_q.filter(
						and_(
							BoardAttach.article_idx == dSave["IDX"],
							BoardAttach.id.in_(selDeletedCheck)
						)
					).all()
					
					# 파일이 있을때만 삭제하도록 변경
					for attach_item in board_attach:
						if os.path.exists(attach_item.new_path):
							os.unlink(attach_item.new_path)
							Session.delete(attach_item)
					
					Session.commit()
				
				for upload_file in upload_files:
					if type(upload_file) == unicode:
						# 빈 문자열이 넘어온 경우 처리를 건너뛴다.
						continue
					
					# 실제 파일 업로드를 여기에서 수행한다.
					new_file = objUpload.upload_file_move(upload_file)
					
					board_attach_row = BoardAttach()
					board_attach_row.board_code = unicode(dSave["BoardID"])
					if dSave.has_key("IDX"):
						board_attach_row.article_idx = dSave["IDX"]
					else:
						board_attach_row.article_idx = article_id
					board_attach_row.org_path = unicode(new_file["O_PATH"])
					board_attach_row.new_path = new_file["D_PATH"]
					board_attach_row.filesize = unicode(new_file["SIZE"])
					
					Session.add(board_attach_row)
					Session.commit()
# ------------------------------------------------------------				  
				return okMessage("작성되었습니다.")
			else:
				return errMessage("작성 권한이 없습니다.")
		else:
			return errMessage("게시판 구분아이디가 잘못 전달되었습니다")
Ejemplo n.º 27
0
Archivo: board.py Proyecto: onetera/sp
	def view(self, id, id2):
		""" 게시물 읽기. 템플릿에 직접 값을 넣는 다 """
		boardID = str( id )		#[NOTE] unicode to string
		tName = None
		
		# 게시판 형태를 맞추기 위한 게시판 설정을 읽어온다.
		rx = Archive("AdminBoard").getRecords("AdminBoard.BCode == " + boardID, "BName,DisplayCate,DisplayStat,DisplayReply,AccessReply", "AdminBoard.SortNumber ASC" )
		
		for board1 in rx:
			tName	= board1["BName"]
			DsCate	= board1["DisplayCate"]
			DsStat	= board1["DisplayStat"]
			DsReply = board1["DisplayReply"]
			AlReply = board1["AccessReply"]
				
		# 게시물 레코드 읽기 
		colStr = "CreateBy,CreateByName,Title,BoardID,Content,ViewCount,CreateDate,UploadName1,UploadLink1"		   
		row = Archive("Board").getValues("Board.IDX == " + id2, colStr )
		
		if not tName: return HTML(u'<font color="red">잘못된 게시판 코드 입니다.</font>')
		if not row: return HTML(u'<font color="red">존재하지 않는 게시물입니다</font>')
		if boardID != row["BoardID"]:  return HTML(u'<font color="red">잘못된 접근 입니다.</font>')
		
		#[TODO] 아래주석 확인
		# 권한 채킹 if CheckLevel("AdminBoard", "AccessRead", "AdminBoard.BCode == " + boardID):
		# else:c.Content = HTML(u'<font color="red">볼수 있는 권한이 없습니다.</font>')
		
		# 여기서부터 게시물 출력
		c.IDX = id2
		c.PNID = "PN_Board_%s" % id2
		c.BoardCode = boardID
		c.BoardName = tName
		c.DisplayCate = DsCate
		c.DisplayStat = DsStat
		c.DisplayReply = DsReply
		c.AllowReply = AlReply
		
		# 첨부파일 개수 가져오기 [SH]
		attach_q = Session.query(BoardAttach)
		c.attach_cnt = attach_q.filter_by(article_idx=id2).count()
		
		if c.attach_cnt > 0:
			c.article_list = self.getArticleAttach(id2)
		else:
			c.article_list = "[]"
		# --------------------------------

		c.WriterName = u"%s (%s)" % ( unicode(row["CreateByName"]), unicode(row["CreateBy"]) )
		c.WriterID = row["CreateBy"] # 삭제할때 사용됨
		
		# Template Pasting
		for cname in colStr.split(","):
			if str( type( row[cname] ) ) == "<type 'datetime.datetime'>":
				setattr( c, cname, row[cname].strftime("%Y-%m-%d %H:%M") )
			else:
				setattr( c, cname, HTML(row[cname]) )
		
		# 첨부 파일 표시, Jpg, png 파일인 경우, 컨텐츠에 직접 디스플레이
		if row["UploadName1"]:
		#	 c.UploadFile1 = HTML('<a href="%s">%s</a>' %( row["UploadLink1"], row["UploadName1"]) )
			if row["UploadName1"][-4:].lower() in (".jpg", ".png"):
				c.Content = HTML('<a href="%s" rel="lightbox"  title="%s"><img src="%s" width="400" /></a><br/><br/>%s' %( row["UploadLink1"], row["UploadName1"], row["UploadLink1"], row["Content"]) )
		#else:
		#	 c.UploadFile1 = u"첨부없음"
			
		# 보기 카운트 증가 ( [TODO] 나중에 이벤트로 처리해야할 부분 )
		if row["CreateBy"] != session["UserID"]:
			# Pass 0은 Archive의 추가이벤트를 발생하지않는 단순 변경하라는 플래그
			newVC = int(row["ViewCount"]) + 1
			dSave = {"IDX": id2, "ViewCount":  newVC,  "_pass_": 0 }
			Archive("Board").New( **dSave )
			c.ViewCount = newVC
			
		return render("Board_View.html")
Ejemplo n.º 28
0
Archivo: task.py Proyecto: onetera/sp
	def list(self, id="json"):
		# Request Varialble
		client_request_key = request.params.keys()
		
		# 필수 지정 필드 검사
		
		# projectNo : 프로젝트 고유번호
		if "projectNo" not in client_request_key:
			response.status_int = 403
			return "Required variable Not Exists - projectNo"
		
		# assignUser : 사용자 ID(할당된 사용자)
		if "assignUser" not in client_request_key:
			response.status_int = 403
			return "Required variable Not Exists - assignUser"
		
		projectNo = request.params['projectNo']
		assignUser = request.params['assignUser']
		
		extract_column = ["projectNo", "seqNo", "taskNo", "taskName", "taskType", "assignUser", "taskStatus", "taskThumb"]
		
		task_sql = """
			select
				Parent1 as projectNo,
				Parent2 as seqNo,
				IDX as taskNo,
				Name as taskName,
				TypeCode as taskType,
				AssignUser as assignUser,
				StatCode as taskStatus,
				Thumb as taskThumb
			from Task 
			where Parent1=:projectNo
			and AssignUser=:assignUser
		"""
		
		task_req_params = {
			"projectNo" : projectNo,
			"assignUser" : assignUser
		}
		
		# taskStatus : 태스크 상태
		# taskSrchStrtDay : 태스크 시작일(YYYY-MM-DD)
		# taskSrchEndDay : 태스크 종료일(YYYY-MM-DD)
		taskStatus = None
		taskSrchStrtDay = None
		taskSrchEndDay = None
		
		if "taskStatus" in client_request_key:
			taskStatus	= request.params['taskStatus']
			
			# taskStatus값이 실제 데이터베이스에 존재하는지 확인하여 없으면 에러를 발생시킨다.
			task_stat = ExistsCode("Task_Stat", taskStatus)
			if not task_stat:
				response.status_int = 403
				return "An invalid status code."
			
			task_sql += " and StatCode = :StatCode"
			task_req_params["StatCode"] = taskStatus
		
		import re
		srchday_pattern = re.compile("\d{4}-\d{2}-\d{2}")
		
		if "taskSrchStrtDay" in client_request_key:
			taskSrchStrtDay = request.params['taskSrchStrtDay']
			
			# 잘못된 날짜 형식이 들어오면 에러를 발생시킨다.
			if None == srchday_pattern.match(taskSrchStrtDay):
				response.status_int = 403
				return "The date format is incorrect"
		
		if "taskSrchEndDay" in client_request_key:
			taskSrchEndDay = request.params['taskSrchEndDay']
			
			# 잘못된 날짜 형식이 들어오면 에러를 발생시킨다.
			if None == srchday_pattern.match(taskSrchEndDay):
				response.status_int = 403
				return "The date format is incorrect"
		
		# 검색 시작일자와 종료일자가 어느한쪽이라도 None인 경우 날짜에 따른 검색을
		# 수행하면 안된다.
		if None != taskSrchStrtDay or None != taskSrchEndDay:
			task_sql += " and DATE(EstStart) >= :EstStart and "
			task_sql += " DATE_ADD(EstStart, INTERVAL EstDay Day) "
			task_sql += " <= DATE(:EstDue)"
			task_req_params["EstStart"] = taskSrchStrtDay
			task_req_params["EstDue"] = taskSrchEndDay
		
		task_result = Session.query(*extract_column).from_statement(
			task_sql
		).params(task_req_params)
		
		# Output Variable
		# Name			type		Description
		# projectNo		number		프로젝트 고유번호
		# seqNo			number		시퀀스 고유번호
		# taskNo		number		태스크 고유번호
		# taskName		string		태스크명
		# takeType		string		태스크 타입
		# assignUser	string		태스크에 할당된 사용자 ID
		# taskStatus	string		태스크 상태
		# taskThumb		string		태스크 썸네일 이미지
		
		return Response(task_result, id)
Ejemplo n.º 29
0
def sendMessage( receiver, receiverCC, receiverBCC, subject, content, attachments=None, withSMS=None ):
	""" 쪽지함에 쪽지를 발송"""
	
	#[TODO] IF not logined !!

	withEmail = True

	emailList = []
	smsList = []
	msgIDXs = []

	receiverTo = getReceiver(receiver)
	receiverCc = getReceiver(receiverCC)
	receiverBcc = getReceiver(receiverBCC)
	
	# 쪽지 내용 저장
	msg = Msg()
	msg.SenderID = unicode(Login.getID())
	msg.SenderName = unicode(Login.getName())
	msg.Subject = unicode(subject)
	msg.Content = unicode(content)
	msg.withSMS = unicode(withSMS)
	msg.CreateDate = datetime.datetime.now() 
	
	Session.add(msg)
	Session.commit()
	
	# To들에게 보내기
	setMsgReceiver(receiverTo, msg.idx, "0")
	# CC들에게 보내기
	setMsgReceiver(receiverCc, msg.idx, "1")
	# BCC들에게 보내기
	setMsgReceiver(receiverBcc, msg.idx, "2")

	# SMS 발송 관련 처리
	if withSMS:
		smsList = list()
		receiverList = receiverTo + receiverCc +receiverBcc
		for msg_receiver in receiverList:
			if type(msg_receiver) != dict:
				continue
			smsList.append(msg_receiver["HandPhone"])

		if len(smsList) > 0:
			SMS.send(sendMsg=u"[sparta] %s" % msg.Content[:70], recvList=smsList)
	
	if withEmail:
		senderData = getReceiver("<%s>" % Login.getID())[0]["GwID"]
		emailList = list()
		receiverList = receiverTo + receiverCc +receiverBcc
		for msg_receiver in receiverList:
			if type(msg_receiver) != dict:
				continue			
			if str(msg_receiver["GwID"]).startswith("D"):
				emailList.append( str(msg_receiver["GwID"])+"@idea.co.kr" )
		if len(emailList) > 0:
			sendEmail("*****@*****.**" % senderData, msg.Subject, msg.Content, recvList=emailList)
   
	if attachments:
		objUpload = Upload()
		objUpload.MsgInitialize()
		
		for attach_item in attachments:
			new_file = objUpload.upload_file_move(attach_item)

			rowMsgAttach = MsgAttach()
			rowMsgAttach.Msg_IDX = unicode(msg.idx)
			rowMsgAttach.OriginalFileName = unicode(new_file["O_PATH"])
			rowMsgAttach.NewFileName = unicode(new_file["D_PATH"])
			rowMsgAttach.FileSize = unicode(new_file["SIZE"])

			Session.add(rowMsgAttach)

		Session.commit()
	return len(receiverTo)
Ejemplo n.º 30
0
def getNoReadCount():
	""" 읽지않은 쪽지 갯수를 반환한다 """
	return Session.query(MsgReceiver).filter(and_(MsgReceiver.IsRead == u'0', MsgReceiver.ReceiverID == Login.getID())).count()