proposal_database.rkt 18 KB

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