use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IngestDocument {
pub version: String,
#[serde(default = "default_page_size")]
pub page_size: PageSize,
#[serde(default = "default_font")]
pub default_font: String,
#[serde(default)]
pub header_text: Option<String>,
#[serde(default)]
pub footer_text: Option<String>,
#[serde(default)]
pub form_label: Option<String>,
#[serde(default)]
pub passages: Vec<Passage>,
pub questions: Vec<Question>,
}
fn default_page_size() -> PageSize {
PageSize {
width_mm: 210.0,
height_mm: 297.0,
}
}
fn default_font() -> String {
"함초롬바탕".to_string()
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PageSize {
pub width_mm: f32,
pub height_mm: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Passage {
pub id: String,
#[serde(default)]
pub blocks: Vec<StemBlock>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Question {
pub number: u32,
pub stem: String,
#[serde(default)]
pub passage_ref: Option<String>,
#[serde(default)]
pub stem_blocks: Vec<StemBlock>,
pub choices: Vec<Choice>,
#[serde(default)]
pub media: Vec<Media>,
#[serde(default = "default_auto_number")]
pub auto_number: bool,
}
fn default_auto_number() -> bool {
true
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum StemBlock {
Paragraph { runs: Vec<InlineRun> },
Text { text: String },
Image {
#[serde(rename = "ref")]
ref_: String,
#[serde(default)]
placement: Placement,
},
Boxed {
#[serde(default)]
title: Option<String>,
#[serde(default)]
blocks: Vec<StemBlock>,
},
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum InlineRun {
Text {
text: String,
},
Image {
#[serde(rename = "ref")]
ref_: String,
},
}
impl<'de> Deserialize<'de> for InlineRun {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de::Error;
let raw = RawStemBlock::deserialize(deserializer)?;
if raw.placement.is_some()
|| raw.title.is_some()
|| raw.blocks.is_some()
|| raw.runs.is_some()
{
return Err(D::Error::custom(
"inline run에는 type과 text 또는 ref만 허용됩니다",
));
}
match raw.block_type.as_str() {
"text" if raw.ref_.is_none() => Ok(Self::Text {
text: raw
.text
.ok_or_else(|| D::Error::custom("text run에 text가 필요합니다"))?,
}),
"image" if raw.text.is_none() => Ok(Self::Image {
ref_: raw
.ref_
.ok_or_else(|| D::Error::custom("image run에 ref가 필요합니다"))?,
}),
_ => Err(D::Error::custom(
"inline run은 text 또는 image이며 다른 필드는 허용되지 않습니다",
)),
}
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawStemBlock {
#[serde(rename = "type")]
block_type: String,
#[serde(default)]
text: Option<String>,
#[serde(rename = "ref", default)]
ref_: Option<String>,
#[serde(default)]
placement: Option<Placement>,
#[serde(default)]
title: Option<String>,
#[serde(default)]
blocks: Option<Vec<StemBlock>>,
#[serde(default)]
runs: Option<Vec<InlineRun>>,
}
impl<'de> Deserialize<'de> for StemBlock {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let raw = RawStemBlock::deserialize(deserializer)?;
let forbid =
|present: bool, block: &str, field: &str, hint: &str| -> Result<(), D::Error> {
if present {
Err(D::Error::custom(format!(
"{block} 블록에 허용되지 않는 필드 '{field}' — {hint}"
)))
} else {
Ok(())
}
};
if raw.block_type != "paragraph" && raw.runs.is_some() {
return Err(D::Error::custom("runs는 paragraph 블록 전용입니다"));
}
match raw.block_type.as_str() {
"paragraph" => {
if raw.text.is_some()
|| raw.ref_.is_some()
|| raw.placement.is_some()
|| raw.title.is_some()
|| raw.blocks.is_some()
{
return Err(D::Error::custom("paragraph에는 type과 runs만 허용됩니다"));
}
Ok(StemBlock::Paragraph {
runs: raw
.runs
.ok_or_else(|| D::Error::custom("paragraph 블록에 runs가 필요합니다"))?,
})
}
"text" => {
forbid(
raw.ref_.is_some(),
"text",
"ref",
"이미지는 type:\"image\" 블록을 쓰세요",
)?;
forbid(
raw.placement.is_some(),
"text",
"placement",
"placement 는 image 블록 전용입니다",
)?;
forbid(
raw.title.is_some(),
"text",
"title",
"title 은 boxed 블록 전용입니다",
)?;
forbid(
raw.blocks.is_some(),
"text",
"blocks",
"blocks 는 boxed 블록 전용입니다",
)?;
let text = raw
.text
.ok_or_else(|| D::Error::custom("text 블록에 'text' 필드가 필요합니다"))?;
Ok(StemBlock::Text { text })
}
"image" => {
forbid(
raw.text.is_some(),
"image",
"text",
"본문은 type:\"text\" 블록으로 넣으세요",
)?;
forbid(
raw.title.is_some(),
"image",
"title",
"title 은 boxed 블록 전용입니다",
)?;
forbid(
raw.blocks.is_some(),
"image",
"blocks",
"blocks 는 boxed 블록 전용입니다",
)?;
let ref_ = raw.ref_.ok_or_else(|| {
D::Error::custom("image 블록에 'ref' 필드가 필요합니다 (media[].id 참조)")
})?;
Ok(StemBlock::Image {
ref_,
placement: raw.placement.unwrap_or_default(),
})
}
"boxed" => {
forbid(
raw.text.is_some(),
"boxed",
"text",
"박스 내용은 'blocks' 배열의 text 블록으로 넣으세요",
)?;
forbid(
raw.ref_.is_some(),
"boxed",
"ref",
"이미지는 blocks 안의 image 블록으로 넣으세요",
)?;
forbid(
raw.placement.is_some(),
"boxed",
"placement",
"placement 는 image 블록 전용입니다",
)?;
Ok(StemBlock::Boxed {
title: raw.title,
blocks: raw.blocks.unwrap_or_default(),
})
}
other => Err(D::Error::custom(format!(
"알 수 없는 블록 type '{other}' (지원: text|image|boxed|paragraph)"
))),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Choice {
pub label: String,
pub text: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Media {
pub id: String,
pub natural_w: u32,
pub natural_h: u32,
#[serde(default)]
pub target_w_mm: Option<f32>,
#[serde(default)]
pub placement: Placement,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Placement {
#[default]
Between,
Above,
Below,
Inline,
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_minimal_json() -> &'static str {
r#"{
"version": "1",
"page_size": {"width_mm": 210.0, "height_mm": 297.0},
"default_font": "함초롬바탕",
"header_text": "국어 영역",
"footer_text": "1/20",
"form_label": "홀수형",
"passages": [
{
"id": "p1-2",
"blocks": [
{"type": "text", "text": "[1~2] 다음 글을 읽고 물음에 답하시오."},
{"type": "text", "text": "공유 지문입니다."}
]
}
],
"questions": [
{
"number": 1,
"passage_ref": "p1-2",
"stem": "다음 글의 주제로 가장 적절한 것은?",
"stem_blocks": [
{"type": "text", "text": "다음 글의 주제로 가장 적절한 것은?"},
{
"type": "boxed",
"title": "<보기>",
"blocks": [
{"type": "text", "text": "보기 본문"}
]
}
],
"choices": [
{"label": "①", "text": "환경 보호"},
{"label": "②", "text": "도시 생활"},
{"label": "③", "text": "전통 음식"},
{"label": "④", "text": "기술 발전"},
{"label": "⑤", "text": "진로 탐색"}
],
"media": []
}
]
}"#
}
#[test]
fn test_parse_minimal() {
let doc: IngestDocument = serde_json::from_str(sample_minimal_json()).unwrap();
assert_eq!(doc.version, "1");
assert_eq!(doc.header_text.as_deref(), Some("국어 영역"));
assert_eq!(doc.footer_text.as_deref(), Some("1/20"));
assert_eq!(doc.form_label.as_deref(), Some("홀수형"));
assert_eq!(doc.passages.len(), 1);
assert_eq!(doc.passages[0].id, "p1-2");
assert_eq!(doc.questions.len(), 1);
assert_eq!(doc.questions[0].number, 1);
assert_eq!(doc.questions[0].passage_ref.as_deref(), Some("p1-2"));
assert_eq!(doc.questions[0].choices.len(), 5);
assert_eq!(doc.questions[0].choices[0].label, "①");
assert!(matches!(
&doc.questions[0].stem_blocks[1],
StemBlock::Boxed { .. }
));
}
#[test]
fn test_parse_legacy_minimal_defaults() {
let json = r#"{
"version": "1",
"questions": [{
"number": 1,
"stem": "기존 입력",
"choices": [{"label": "①", "text": "A"}]
}]
}"#;
let doc: IngestDocument = serde_json::from_str(json).unwrap();
assert!(doc.header_text.is_none());
assert!(doc.footer_text.is_none());
assert!(doc.form_label.is_none());
assert!(doc.passages.is_empty());
assert!(doc.questions[0].passage_ref.is_none());
assert!(doc.questions[0].stem_blocks.is_empty());
assert!(doc.questions[0].media.is_empty());
assert!(doc.questions[0].auto_number);
}
#[test]
fn test_placement_default() {
assert_eq!(Placement::default(), Placement::Between);
}
#[test]
fn test_roundtrip() {
let doc: IngestDocument = serde_json::from_str(sample_minimal_json()).unwrap();
let s = serde_json::to_string(&doc).unwrap();
let doc2: IngestDocument = serde_json::from_str(&s).unwrap();
assert_eq!(doc.questions.len(), doc2.questions.len());
assert_eq!(doc.questions[0].stem, doc2.questions[0].stem);
assert_eq!(doc.passages.len(), doc2.passages.len());
}
#[test]
fn test_placement_serde() {
let p_str = serde_json::to_string(&Placement::Between).unwrap();
assert_eq!(p_str, r#""between""#);
let p: Placement = serde_json::from_str(r#""inline""#).unwrap();
assert_eq!(p, Placement::Inline);
}
#[test]
fn boxed_with_text_is_rejected_with_hint() {
let e = serde_json::from_str::<StemBlock>(r#"{"type":"boxed","text":"소속: 성명:"}"#)
.unwrap_err()
.to_string();
assert!(e.contains("boxed 블록에 허용되지 않는 필드 'text'"), "{e}");
assert!(e.contains("blocks"), "힌트가 있어야 합니다: {e}");
}
#[test]
fn unknown_block_field_is_rejected() {
let e = serde_json::from_str::<StemBlock>(r#"{"type":"text","text":"a","bold":true}"#)
.unwrap_err()
.to_string();
assert!(e.contains("bold"), "{e}");
}
#[test]
fn unknown_block_type_is_rejected() {
let e = serde_json::from_str::<StemBlock>(r#"{"type":"table"}"#)
.unwrap_err()
.to_string();
assert!(e.contains("알 수 없는 블록 type 'table'"), "{e}");
}
#[test]
fn top_level_typo_is_rejected() {
let json = r#"{"version":"1","defaul_font":"바탕","questions":[]}"#;
let e = serde_json::from_str::<IngestDocument>(json)
.unwrap_err()
.to_string();
assert!(e.contains("defaul_font"), "{e}");
}
#[test]
fn question_typo_is_rejected() {
let json = r#"{
"version": "1",
"questions": [{
"number": 1, "stem": "Q", "choice": [], "choices": []
}]
}"#;
let e = serde_json::from_str::<IngestDocument>(json)
.unwrap_err()
.to_string();
assert!(e.contains("choice"), "{e}");
}
#[test]
fn valid_blocks_still_parse() {
let b: StemBlock =
serde_json::from_str(r#"{"type":"image","ref":"img/a.png","placement":"below"}"#)
.unwrap();
assert!(matches!(b, StemBlock::Image { .. }));
let b: StemBlock = serde_json::from_str(
r#"{"type":"boxed","title":"<보기>","blocks":[{"type":"text","text":"본문"}]}"#,
)
.unwrap();
assert!(matches!(b, StemBlock::Boxed { .. }));
}
}