proposal_database.rkt 18 KB

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