from appPublic.timeUtils import curDateString, dateadd
from ahserver.serverenv import get_serverenv

async def set_program(request, program_type, quota):
	db = DBPools()
	dbname = get_serverenv('get_module_dbname')('rag')
	async with db.sqlorContext(dbname) as sor:
		u = await get_session_userinfo(request)
		sql="select * from ragquote where orgid = ${orgid}$ order by enabled_date"
		qs = await sor.sqlExe(sql, {'orgid': u.userorgid})
		today = curDateString()
		if len(qs) == 0:
			if params_kw.program_type == 'free':
				expired_date = dateadd(today, months=1)
			else:
				expired_date = '9999-12-31'
			ns = {
				"id": uuid(),
				"orgid": u.userorgid,
				"enabled_date": today,
				"expired_date": expired_date,
				'quota': params_kw.quota
			}
			await sor.C('ragquota', ns)
		else:
			lastq = qs[-1]
			lastq.expired_date = today
			await sor.U('ragquote', lastq.copy())
			ns = {
				"id": uuid(),
				"orgid": u.userorgid,
				"enabled_date": today,
				"expired_date": expired_date,
				'quota': params_kw.quota
			}
			await sor.C('ragquota', ns)


async def get_rag_programs(request):
	db = DBPools()
	dbname = get_serverenv('get_module_dbanme')('rag')
	async with db.sqlorContext(dbname) as sor:
		recs = await sor.R('ragprogram', {})
		return recs
	return []

