proposal_database.rkt 14 KB

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