proposal_database.rkt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. #lang racket/base
  2. ;; This program updates an entry in a proposals database.
  3. (require racket/cmdline
  4. racket/date
  5. racket/list
  6. racket/format
  7. db
  8. "config.rkt") ; load configuration file
  9. (define progname "proposal_database.rkt")
  10. ; give us the date in YYYY-MM-DD format
  11. (date-display-format 'iso-8601)
  12. ; parameters
  13. ; start and end date to sub-select proposals within a given range
  14. (define start-date (make-parameter #f))
  15. (define end-date (make-parameter #f))
  16. ; if #t, use proposal type, submitting organiation, solicitation/call, and
  17. ; telescope name from the most recently submitted (i.e., highest ID) proposal
  18. (define reuse-params (make-parameter #f))
  19. ; Set up the mode as a parameter to be provided by command line switches
  20. (define mode (make-parameter #f))
  21. ; set up an error handler
  22. (define (error-handler msg)
  23. (error (string-append "Error: ")
  24. msg))
  25. ; set up command line arguments
  26. (command-line
  27. #:program progname
  28. #:once-each
  29. [("-s" "--start-date") sd "Start of date range (YYYY-MM-DD)"
  30. (start-date sd)]
  31. [("-e" "--end-date") ed "End of date range (YYYY-MM-DD)"
  32. (end-date ed)]
  33. [("-r" "--reuse-parameters") "Reuse/auto-fill proposal type, submitting organization, solicitation/call and telescope name from the most recently added proposal."
  34. (reuse-params #t)]
  35. #:once-any
  36. [("--create-database") "Create a new database" (mode "create-database")]
  37. [("-a" "--add") "Add a new proposal" (mode "add")]
  38. [("-u" "--update") "Update a proposal outcome" (mode "update")]
  39. [("--stats") "Calculate and display summary statistics" (mode "stats")]
  40. [("--list-open") "Show all submitted (but not resolved) proposals" (mode "list-open")]
  41. [("--list-closed") "Show all resolved (accepted and rejected) proposals" (mode "list-closed")]
  42. [("--list-accepted") "Show accepted proposals" (mode "list-accepted")]
  43. [("--list-rejected") "Show rejected proposals" (mode "list-rejected")]
  44. [("--list-open-calls") "Show calls that have submitted (but not resolved) proposals" (mode "list-open-calls")]
  45. #:ps "Copyright 2019-2020, 2022-2025 George Privon")
  46. ; set up a condensed prompt for getting information
  47. (define (getinput prompt)
  48. (write-string prompt)
  49. (write-string ": ")
  50. (read-line))
  51. ; decide whether to use singular or plural "proposal" based on the number of proposals
  52. (define (proposal-plurals Nprop)
  53. (cond [(= Nprop 1) "proposal"]
  54. [else "proposals"]))
  55. ; take a proposal result from the SQL search and write it out nicely
  56. (define (printentry entry issub)
  57. (displayln (string-append
  58. (number->string (vector-ref entry 0))
  59. ": "
  60. (vector-ref entry 1)
  61. "("
  62. (vector-ref entry 2)
  63. "; PI: "
  64. (vector-ref entry 4)
  65. (if (not issub)
  66. (string-append "; "
  67. (vector-ref entry 5))
  68. "")
  69. ") \""
  70. (vector-ref entry 3)
  71. "\"")))
  72. ; take an open proposal call result from the SQL search and write it out nicely
  73. (define (print-call-entry entry Nprop Nprop-PI)
  74. (define have-PI (> Nprop-PI 0))
  75. (define have-CoI (> (- Nprop Nprop-PI) 0))
  76. (displayln (string-append
  77. (vector-ref entry 1)
  78. " "
  79. (vector-ref entry 2)
  80. " ("
  81. (vector-ref entry 0)
  82. ") - "
  83. (if have-PI
  84. (string-append (number->string Nprop-PI)
  85. " PI "
  86. (proposal-plurals Nprop-PI))
  87. "")
  88. (if (and have-PI have-CoI)
  89. ", "
  90. "")
  91. (if have-CoI
  92. (string-append (number->string (- Nprop Nprop-PI))
  93. " CoI "
  94. (proposal-plurals Nprop))
  95. "")
  96. " pending.")))
  97. (define (get-last-proposal-call conn)
  98. (displayln "Adopting proposal information from last submission")
  99. (last-proposal-call conn))
  100. ; get information from the most recent proposal submission
  101. (define (last-proposal-call conn)
  102. (vector->list (query-row conn "SELECT type, organization, solicitation, telescope FROM proposals ORDER BY id DESC LIMIT 1")))
  103. ; create the database and create the table
  104. (define (createdb dbloc)
  105. ; make sure we can use the sqlite3 connection
  106. (cond [(not (sqlite3-available?)) (error-handler "Sqlite3 library not available.")])
  107. ; create the database and add the `proposals` table if it doesn't exist
  108. (cond [(file-exists? dbloc) (error-handler "Database exists. Exiting.")])
  109. (write-string (string-append "Creating database " dbloc "\n"))
  110. (define conn (sqlite3-connect #:database dbloc
  111. #:mode 'create))
  112. (query-exec conn "CREATE TABLE proposals (ID INTEGER PRIMARY KEY,
  113. type TEXT NOT NULL,
  114. organization TEXT NOT NULL,
  115. solicitation TEXT NOT NULL,
  116. telescope TEXT DEFAULT '',
  117. orgpropID TEXT NOT NULL,
  118. PI TEXT NOT NULL,
  119. title TEXT NOT NULL,
  120. CoI TEXT NOT NULL,
  121. status TEXT NOT NULL,
  122. submitdate TEXT NOT NULL,
  123. resultdate TEXT DEFAULT '')")
  124. (disconnect conn)
  125. (write-string (string-append "Database created at " dbloc "\n")))
  126. ; check to see if we can access the database
  127. (define (checkdb conn)
  128. (cond [(connected? conn) (write-string "Database created successfully.")]
  129. [else (write-string "Could not connect to database.")]))
  130. ; add a new proposal to the database
  131. (define (addnew conn)
  132. ; full list of input fileds that we will need (these will be the prompts
  133. ; to the user)
  134. (define input-fields (list "Proposal type"
  135. "Submitting Organization"
  136. "Solicitation/Call"
  137. "Telescope"
  138. "Proposal Title"
  139. "PI"
  140. "CoIs"
  141. "Submit date (YYYY-MM-DD)"
  142. "Organization's propsal ID"))
  143. ; assume all these proposals are submitted, don't ask the user
  144. (define status "submitted")
  145. (displayln "Adding new proposal to database.")
  146. ; get the proposal information
  147. (define propinfo
  148. (cond
  149. ; if we're re-using parameters, get info from the most recent submission
  150. ; and append the user input for the remaining fields
  151. [(reuse-params) (append (get-last-proposal-call conn)
  152. (map getinput (list-tail input-fields 4)))]
  153. ; if not using previous information, ask the user for all inputs
  154. [else (map getinput input-fields)]))
  155. ; do the INSERT into the Sqlite database
  156. (let ([add-proposal-info
  157. (prepare conn "INSERT INTO proposals (type, organization, solicitation, telescope, title, PI, CoI, submitdate, orgpropID, status) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")])
  158. (query-exec conn (bind-prepared-statement add-proposal-info
  159. (flatten (list propinfo status))))))
  160. ; update an entry with new status (accepted, rejected, etc.)
  161. (define (update conn ID)
  162. (displayln (string-append "Updating entry " (number->string ID)))
  163. (define entry (query-maybe-row conn "SELECT * FROM proposals WHERE ID=?" ID))
  164. (cond
  165. [(eq? #f entry) (error-handler "Invalid ID. Row not found")])
  166. (displayln (string-append "Current status is: "
  167. (vector-ref entry 9)
  168. " ("
  169. (vector-ref entry 10)
  170. ")"))
  171. (write-string "Please enter new status: ")
  172. (define newstatus (read-line))
  173. ;(write-string "Please enter date of updated status (leave blank to use current date): ")
  174. ;(define resdate (read-line))
  175. (define resdate (date->string (seconds->date (current-seconds))))
  176. ; now update that entry
  177. (query-exec conn "UPDATE proposals SET status=?, resultdate=? WHERE ID=?"
  178. newstatus
  179. resdate
  180. ID)
  181. (displayln "Entry updated."))
  182. ; if the user selects a date range we need to decide which date to filter on
  183. ; If they're looking at submitted (i.e., open) proposals, use the submitted
  184. ; date.
  185. ; If they're looking at closed/resolved proposals, use the dates proposals
  186. ; were resolved.
  187. (define (date-for-selection submitted)
  188. (if submitted
  189. "submitdate"
  190. "resultdate"))
  191. ; generate a SQL date clause selection
  192. (define (dateclause start-date end-date issub)
  193. (string-append
  194. (if (or (start-date) (end-date))
  195. " AND "
  196. "")
  197. (if (start-date)
  198. (string-append
  199. " DATE("
  200. (date-for-selection issub)
  201. ") >= DATE('"
  202. (start-date)
  203. "') ")
  204. "")
  205. (if (and (start-date) (end-date))
  206. " AND "
  207. "")
  208. (if (end-date)
  209. (string-append
  210. " DATE("
  211. (date-for-selection issub)
  212. ") <= DATE('"
  213. (end-date)
  214. "') ")
  215. "")))
  216. ; retrieve and print proposals based on status
  217. (define (printprop conn
  218. #:submitted issub
  219. #:accepted [isaccept #f]
  220. #:rejected [isrej #f])
  221. (define selclause (string-append
  222. (if issub
  223. "status='submitted'"
  224. "status!='submitted'")
  225. ; find things that are "accepted" or "funded"
  226. (if isaccept
  227. " AND (status LIKE '%Accepted%' OR status LIKE '%Funded%')"
  228. "")
  229. ; find things that are "rejected"
  230. (if isrej
  231. " AND status LIKE '%Rejected%'"
  232. "")))
  233. ; generate a selection clause if the user requested a restricted range
  234. (define props (query-rows conn (string-append "SELECT ID,telescope,solicitation,title,PI,status FROM proposals WHERE "
  235. selclause
  236. (dateclause start-date end-date issub))))
  237. (display (string-append (number->string (length props))
  238. (cond [issub " pending "]
  239. [isaccept " accepted "]
  240. [isrej " rejected "])
  241. (proposal-plurals (length props))
  242. " found."))
  243. (newline)
  244. ; print all the unresolved proposals to the screen
  245. (map (lambda (prop)
  246. (printentry prop issub))
  247. props))
  248. ; retrieve and print proposal calls
  249. (define (print-open-calls conn)
  250. (define call-entries (query-rows conn (string-append "SELECT DISTINCT organization,telescope,solicitation FROM proposals WHERE status='submitted'")))
  251. (displayln (string-append (number->string (length call-entries))
  252. " pending calls found."))
  253. (newline)
  254. ; print all the unresolved proposals to the screen
  255. (map (lambda (call-entry)
  256. (define Nprop (query-value conn (string-append "SELECT COUNT(DISTINCT ID) from proposals WHERE status='submitted' AND solicitation='"
  257. (vector-ref call-entry 2)
  258. "'")))
  259. (define Nprop-PI
  260. (query-value conn (string-append "SELECT COUNT(DISTINCT ID) from proposals WHERE status='submitted' AND solicitation='"
  261. (vector-ref call-entry 2)
  262. "' AND PI LIKE '%"
  263. PIname
  264. "%'")))
  265. (print-call-entry call-entry Nprop Nprop-PI))
  266. call-entries))
  267. ; find proposals waiting for updates
  268. (define (findpending conn)
  269. (write-string "Updating proposals. ")
  270. (printprop conn #:submitted #t)
  271. (write-string "Please enter a proposal number to edit (enter 0 or nothing to exit): ")
  272. (define upID (read-line))
  273. (cond
  274. [(eq? (string->number upID) 0) (exit)]
  275. [(string->number upID) (update conn (string->number upID))]
  276. [else (exit)]))
  277. ; compute and print some statistics about proposals:
  278. ; - total number of proposals (since earliest date)
  279. ; - number of pending proposals
  280. ; - number of successful proposals and corresponding fraction of the total that are not pending
  281. ; - number of rejected proposals and corresponding fraction of the total that are not pending
  282. ; - do the above two for all proposals and for proposals that I PI'ed. (TODO: PI'ed separation not yet implemented)
  283. (define (proposal-stats conn)
  284. (displayln "Proposal statistics to date.\n")
  285. ; do statistics for all proposals
  286. (displayln "\tAll proposals")
  287. (let-values ([(Nprop Npending Nrejected) (get-stats conn)])
  288. (print-stats Nprop Npending Nrejected))
  289. ; do statistics for proposals as PI
  290. (displayln (string-append "\n\tPI'ed Proposals (by "
  291. PIname
  292. ")"))
  293. (let-values ([(Nprop Npending Nrejected) (get-stats conn #:selclause (string-append "PI LIKE '%"
  294. PIname
  295. "%'"))])
  296. (print-stats Nprop Npending Nrejected))
  297. )
  298. ; given numbers, format somewhat pretty output of proposal statistics
  299. (define (print-stats Nprop Npending Nrejected)
  300. ; total proposal stats
  301. (displayln (string-append (number->string Nprop)
  302. "\ttotal "
  303. (proposal-plurals Nprop)
  304. " entered ("
  305. (number->string (- Nprop Npending))
  306. " "
  307. (proposal-plurals (- Nprop Npending))
  308. " resolved; "
  309. (number->string Npending)
  310. " "
  311. (proposal-plurals Npending)
  312. " pending)."))
  313. ; statistics on accepted proposals
  314. (define Naccepted (- Nprop Npending Nrejected))
  315. (displayln (string-append (number->string Naccepted)
  316. "\t"
  317. (proposal-plurals Naccepted)
  318. " accepted (f="
  319. (~r (/ Naccepted
  320. (- Nprop Npending))
  321. #:precision `(= 3))
  322. " of resolved proposals)."))
  323. ; statistcs on other proposals
  324. (displayln (string-append (number->string Nrejected)
  325. "\t"
  326. (proposal-plurals Nrejected)
  327. " rejected (f="
  328. (~r (/ Nrejected
  329. (- Nprop Npending))
  330. #:precision `(= 3))
  331. " of resolved proposals).")))
  332. ; retrieve proposal numbers from the database, for statistics
  333. (define (get-stats conn #:selclause [extrasel ""])
  334. (define get_prop_count_base "SELECT COUNT(DISTINCT ID) FROM proposals ")
  335. (define mysel (if (eq? 0 (string-length extrasel))
  336. ""
  337. (string-append " AND "
  338. extrasel)))
  339. (define mysel-one (if (eq? 0 (string-length extrasel))
  340. ""
  341. (string-append " WHERE "
  342. extrasel)))
  343. (values
  344. ; total number of proposals
  345. (query-value conn
  346. (string-append get_prop_count_base
  347. mysel-one))
  348. ; Number of pending proposals
  349. (query-value conn
  350. (string-append get_prop_count_base
  351. "WHERE status='submitted'"
  352. mysel))
  353. ; Number of rejected proposals
  354. (query-value conn
  355. (string-append get_prop_count_base
  356. "WHERE status LIKE '%rejected%'"
  357. mysel))))
  358. ; make sure we can use the sqlite3 connection
  359. (define checkdblib
  360. (cond (not (sqlite3-available?))
  361. (error-handler "Sqlite3 library not available.")))
  362. ; catch-all routine for when we need to access the database
  363. (define (querysys mode)
  364. ; check if the user would like to create the database or not
  365. (cond
  366. [(string=? "create-database" mode) (createdb dbloc)])
  367. ; see if we need write access or if we can use read only
  368. (define dbmode (if (or (string=? "add" mode)
  369. (string=? "update" mode))
  370. 'read/write
  371. 'read-only))
  372. ; open the database with the specified mode
  373. (define conn (sqlite3-connect #:database dbloc
  374. #:mode dbmode))
  375. ; now handle the user's request
  376. (cond
  377. [(string=? "create-database" mode) (checkdb conn)]
  378. [(string=? "add" mode) (addnew conn)]
  379. [(string=? "update" mode) (findpending conn)]
  380. [(string=? "stats" mode) (proposal-stats conn)]
  381. [(string=? "list-open-calls" mode) (print-open-calls conn)]
  382. [(string=? "list-open" mode) (printprop conn #:submitted #t)]
  383. [(string=? "list-closed" mode) (printprop conn #:submitted #f)]
  384. [(string=? "list-accepted" mode) (printprop conn #:submitted #f #:accepted #t)]
  385. [(string=? "list-rejected" mode) (printprop conn #:submitted #f #:rejected #t)]
  386. [else (error-handler (string-append "Unknown mode. Try " progname " help\n\n"))])
  387. ; close the databse
  388. (disconnect conn))
  389. (querysys (mode))